Skip to content

The open alternative to Salesforce, designed for AI.

Scope application variable reads and updates to the calling application and workspace (#26192)

Paul Rastoin6d8d17389e32
diff --git a/packages/twenty-apps/public/call-recorder/package.json b/packages/twenty-apps/public/call-recorder/package.json
index f4b0ae97e9c..afd6edd40b3 100644
--- a/packages/twenty-apps/public/call-recorder/package.json
+++ b/packages/twenty-apps/public/call-recorder/package.json
@@ -1,6 +1,6 @@
{
"name": "@twentyhq/call-recorder",
- "version": "1.13.0",
+ "version": "1.13.1",
"license": "MIT",
"engines": {
"node": "^24.5.0",
diff --git a/packages/twenty-apps/public/call-recorder/src/front-components/components/CallRecorderSettings.tsx b/packages/twenty-apps/public/call-recorder/src/front-components/components/CallRecorderSettings.tsx
index 244cff7e731..d8769b1609d 100644
--- a/packages/twenty-apps/public/call-recorder/src/front-components/components/CallRecorderSettings.tsx
+++ b/packages/twenty-apps/public/call-recorder/src/front-components/components/CallRecorderSettings.tsx
@@ -2,10 +2,7 @@ import 'twenty-ui/style.css';
import styled from '@emotion/styled';
import { useState } from 'react';
-import {
- useColorScheme,
- useFrontComponentId,
-} from 'twenty-sdk/front-component';
+import { useColorScheme } from 'twenty-sdk/front-component';
import { THEME_DARK, THEME_LIGHT } from 'twenty-ui/theme';
import {
ThemeContext,
@@ -36,7 +33,6 @@ const StyledPausedNotice = styled.div`
export const CallRecorderSettings = () => {
const colorScheme = useColorScheme();
- const frontComponentId = useFrontComponentId();
const [isSchedulingEnabled, setIsSchedulingEnabled] = useState(
() =>
getApplicationVariableValue(
@@ -58,15 +54,14 @@ export const CallRecorderSettings = () => {
>
<StyledContainer>
<SchedulingSection
- frontComponentId={frontComponentId}
isEnabled={isSchedulingEnabled}
onEnabledChange={setIsSchedulingEnabled}
/>
{isSchedulingEnabled ? (
<>
- <RecorderSection frontComponentId={frontComponentId} />
- <InCallSection frontComponentId={frontComponentId} />
- <TranscriptionSection frontComponentId={frontComponentId} />
+ <RecorderSection />
+ <InCallSection />
+ <TranscriptionSection />
</>
) : (
<StyledPausedNotice>
diff --git a/packages/twenty-apps/public/call-recorder/src/front-components/components/InCallSection.tsx b/packages/twenty-apps/public/call-recorder/src/front-components/components/InCallSection.tsx
index 9aa3ce3a2f1..b0feebcef22 100644
--- a/packages/twenty-apps/public/call-recorder/src/front-components/components/InCallSection.tsx
+++ b/packages/twenty-apps/public/call-recorder/src/front-components/components/InCallSection.tsx
@@ -18,11 +18,7 @@ import { useAutosaveApplicationVariable } from 'src/front-components/hooks/use-a
import { getApplicationVariableValue } from 'src/front-components/utils/get-application-variable-value.util';
import { truncateRecordingNoticeMessage } from 'src/logic-functions/utils/truncate-recording-notice-message.util';
-type InCallSectionProps = {
- frontComponentId: string;
-};
-
-export const InCallSection = ({ frontComponentId }: InCallSectionProps) => {
+export const InCallSection = () => {
const noticeMessageInputId = useId();
const [isNoticeEnabled, setIsNoticeEnabled] = useState(
() =>
@@ -38,12 +34,10 @@ export const InCallSection = ({ frontComponentId }: InCallSectionProps) => {
const { saveImmediately: saveNoticeEnabledImmediately } =
useAutosaveApplicationVariable({
- frontComponentId,
variableKey: CALL_RECORDER_RECORDING_NOTICE_ROW.variableKey,
});
const { saveDebounced: saveNoticeMessageDebounced } =
useAutosaveApplicationVariable({
- frontComponentId,
variableKey: CALL_RECORDER_RECORDING_NOTICE_MESSAGE_FIELD.variableKey,
});
@@ -72,7 +66,6 @@ export const InCallSection = ({ frontComponentId }: InCallSectionProps) => {
{CALL_RECORDER_TIMING_ROWS.map((row) => (
<TimingCounterRow
key={row.variableKey}
- frontComponentId={frontComponentId}
variableKey={row.variableKey}
title={row.title}
description={row.description}
diff --git a/packages/twenty-apps/public/call-recorder/src/front-components/components/RecorderSection.tsx b/packages/twenty-apps/public/call-recorder/src/front-components/components/RecorderSection.tsx
index c2a12a69705..36c47264855 100644
--- a/packages/twenty-apps/public/call-recorder/src/front-components/components/RecorderSection.tsx
+++ b/packages/twenty-apps/public/call-recorder/src/front-components/components/RecorderSection.tsx
@@ -26,11 +26,7 @@ import { getThemeColorFromHex } from 'src/front-components/utils/get-theme-color
import { normalizeHexColor } from 'src/front-components/utils/normalize-hex-color.util';
import { DEFAULT_CALL_RECORDER_BOT_IMAGE_BACKGROUND } from 'src/logic-functions/constants/default-call-recorder-bot-image-background';
-type RecorderSectionProps = {
- frontComponentId: string;
-};
-
-export const RecorderSection = ({ frontComponentId }: RecorderSectionProps) => {
+export const RecorderSection = () => {
const nameInputId = useId();
const hexInputId = useId();
const [nameValue, setNameValue] = useState(() =>
@@ -50,19 +46,16 @@ export const RecorderSection = ({ frontComponentId }: RecorderSectionProps) => {
>(undefined);
const { saveDebounced: saveNameDebounced } = useAutosaveApplicationVariable({
- frontComponentId,
variableKey: CALL_RECORDER_NAME_FIELD.variableKey,
});
const { saveImmediately: saveWorkspaceLogoImmediately } =
useAutosaveApplicationVariable({
- frontComponentId,
variableKey: CALL_RECORDER_USE_WORKSPACE_LOGO_ROW.variableKey,
});
const {
saveDebounced: saveTileBackgroundDebounced,
saveImmediately: saveTileBackgroundImmediately,
} = useAutosaveApplicationVariable({
- frontComponentId,
variableKey: CALL_RECORDER_TILE_BACKGROUND_ROW.variableKey,
});
diff --git a/packages/twenty-apps/public/call-recorder/src/front-components/components/SchedulingSection.tsx b/packages/twenty-apps/public/call-recorder/src/front-components/components/SchedulingSection.tsx
index 1c479406f4c..16ea3b3f685 100644
--- a/packages/twenty-apps/public/call-recorder/src/front-components/components/SchedulingSection.tsx
+++ b/packages/twenty-apps/public/call-recorder/src/front-components/components/SchedulingSection.tsx
@@ -7,18 +7,15 @@ import { useAutosaveApplicationVariable } from 'src/front-components/hooks/use-a
import { requestCalendarBotSchedulingSync } from 'src/front-components/utils/request-calendar-bot-scheduling-sync.util';
type SchedulingSectionProps = {
- frontComponentId: string;
isEnabled: boolean;
onEnabledChange: (isEnabled: boolean) => void;
};
export const SchedulingSection = ({
- frontComponentId,
isEnabled,
onEnabledChange,
}: SchedulingSectionProps) => {
const { saveImmediately } = useAutosaveApplicationVariable({
- frontComponentId,
variableKey: CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ROW.variableKey,
onSaveSuccess: () => requestCalendarBotSchedulingSync(),
onSaveError: (value) => onEnabledChange(value !== 'true'),
diff --git a/packages/twenty-apps/public/call-recorder/src/front-components/components/TimingCounterRow.tsx b/packages/twenty-apps/public/call-recorder/src/front-components/components/TimingCounterRow.tsx
index e81daed5254..4454256bd7c 100644
--- a/packages/twenty-apps/public/call-recorder/src/front-components/components/TimingCounterRow.tsx
+++ b/packages/twenty-apps/public/call-recorder/src/front-components/components/TimingCounterRow.tsx
@@ -7,7 +7,6 @@ import { useAutosaveApplicationVariable } from 'src/front-components/hooks/use-a
import { getNormalizedNumberValue } from 'src/front-components/utils/get-normalized-number-value.util';
type TimingCounterRowProps = {
- frontComponentId: string;
variableKey: string;
title: string;
description: string;
@@ -17,7 +16,6 @@ type TimingCounterRowProps = {
};
export const TimingCounterRow = ({
- frontComponentId,
variableKey,
title,
description,
@@ -28,7 +26,6 @@ export const TimingCounterRow = ({
const inputId = useId();
const [inputValue, setInputValue] = useState(persistedValue);
const { saveDebounced, saveImmediately } = useAutosaveApplicationVariable({
- frontComponentId,
variableKey,
});
diff --git a/packages/twenty-apps/public/call-recorder/src/front-components/components/TranscriptionSection.tsx b/packages/twenty-apps/public/call-recorder/src/front-components/components/TranscriptionSection.tsx
index 56ca633d7cd..be81528dc1a 100644
--- a/packages/twenty-apps/public/call-recorder/src/front-components/components/TranscriptionSection.tsx
+++ b/packages/twenty-apps/public/call-recorder/src/front-components/components/TranscriptionSection.tsx
@@ -21,13 +21,7 @@ import { getApplicationVariableValue } from 'src/front-components/utils/get-appl
import { serializeRichTextMarkdown } from 'src/front-components/utils/serialize-rich-text-markdown.util';
import { extractRichTextMarkdown } from 'src/logic-functions/utils/extract-rich-text-markdown.util';
-type TranscriptionSectionProps = {
- frontComponentId: string;
-};
-
-export const TranscriptionSection = ({
- frontComponentId,
-}: TranscriptionSectionProps) => {
+export const TranscriptionSection = () => {
const inputId = useId();
const [providerValue, setProviderValue] = useState(() =>
getApplicationVariableValue(
@@ -51,17 +45,14 @@ export const TranscriptionSection = ({
const { saveImmediately: saveProviderImmediately } =
useAutosaveApplicationVariable({
- frontComponentId,
variableKey: CALL_RECORDER_TRANSCRIPT_PROVIDER_ROW.variableKey,
});
const { saveImmediately: saveSummaryEnabledImmediately } =
useAutosaveApplicationVariable({
- frontComponentId,
variableKey: CALL_RECORDER_SUMMARY_ENABLED_ROW.variableKey,
});
const { saveDebounced: savePromptDebounced } = useAutosaveApplicationVariable(
{
- frontComponentId,
variableKey: CALL_RECORDER_SUMMARY_PROMPT_FIELD.variableKey,
},
);
diff --git a/packages/twenty-apps/public/call-recorder/src/front-components/hooks/use-autosave-application-variable.ts b/packages/twenty-apps/public/call-recorder/src/front-components/hooks/use-autosave-application-variable.ts
index f8b341d89af..830878136c5 100644
--- a/packages/twenty-apps/public/call-recorder/src/front-components/hooks/use-autosave-application-variable.ts
+++ b/packages/twenty-apps/public/call-recorder/src/front-components/hooks/use-autosave-application-variable.ts
@@ -7,20 +7,17 @@ import { useSaveApplicationVariable } from 'src/front-components/hooks/use-save-
import { createApplicationVariableSaveQueue } from 'src/front-components/utils/create-application-variable-save-queue.util';
type UseAutosaveApplicationVariableParams = {
- frontComponentId: string;
variableKey: string;
onSaveSuccess?: (value: string) => void | Promise<void>;
onSaveError?: (value: string) => void;
};
export const useAutosaveApplicationVariable = ({
- frontComponentId,
variableKey,
onSaveSuccess,
onSaveError,
}: UseAutosaveApplicationVariableParams) => {
- const { saveApplicationVariable } =
- useSaveApplicationVariable(frontComponentId);
+ const { saveApplicationVariable } = useSaveApplicationVariable();
const saveApplicationVariableRef = useRef(saveApplicationVariable);
const onSaveSuccessRef = useRef(onSaveSuccess);
const onSaveErrorRef = useRef(onSaveError);
diff --git a/packages/twenty-apps/public/call-recorder/src/front-components/hooks/use-save-application-variable.ts b/packages/twenty-apps/public/call-recorder/src/front-components/hooks/use-save-application-variable.ts
index 0904e3399cd..bd2a0dd1f70 100644
--- a/packages/twenty-apps/public/call-recorder/src/front-components/hooks/use-save-application-variable.ts
+++ b/packages/twenty-apps/public/call-recorder/src/front-components/hooks/use-save-application-variable.ts
@@ -7,9 +7,8 @@ type SaveApplicationVariableParams = {
value: string;
};
-export const useSaveApplicationVariable = (frontComponentId: string) => {
- const { updateApplicationVariable } =
- useUpdateApplicationVariable(frontComponentId);
+export const useSaveApplicationVariable = () => {
+ const { updateApplicationVariable } = useUpdateApplicationVariable();
const saveApplicationVariable = async ({
variableKey,
diff --git a/packages/twenty-apps/public/call-recorder/src/front-components/hooks/use-update-application-variable.ts b/packages/twenty-apps/public/call-recorder/src/front-components/hooks/use-update-application-variable.ts
index 77661ca4b78..d9f4c63dc83 100644
--- a/packages/twenty-apps/public/call-recorder/src/front-components/hooks/use-update-application-variable.ts
+++ b/packages/twenty-apps/public/call-recorder/src/front-components/hooks/use-update-application-variable.ts
@@ -13,29 +13,27 @@ type UpdateApplicationVariableState = {
) => Promise<boolean>;
};
-export const useUpdateApplicationVariable = (
- frontComponentId: string,
-): UpdateApplicationVariableState => {
- const updateApplicationVariable = async ({
- variableKey,
- value,
- }: UpdateApplicationVariableParams): Promise<boolean> => {
- try {
- const applicationId =
- await resolveCallRecorderApplicationId(frontComponentId);
- const client = new MetadataApiClient();
+export const useUpdateApplicationVariable =
+ (): UpdateApplicationVariableState => {
+ const updateApplicationVariable = async ({
+ variableKey,
+ value,
+ }: UpdateApplicationVariableParams): Promise<boolean> => {
+ try {
+ const applicationId = await resolveCallRecorderApplicationId();
+ const client = new MetadataApiClient();
- await client.mutation({
- updateOneApplicationVariable: {
- __args: { key: variableKey, value, applicationId },
- },
- });
+ await client.mutation({
+ updateOneApplicationVariable: {
+ __args: { key: variableKey, value, applicationId },
+ },
+ });
- return true;
- } catch {
- return false;
- }
- };
+ return true;
+ } catch {
+ return false;
+ }
+ };
- return { updateApplicationVariable };
-};
+ return { updateApplicationVariable };
+ };
diff --git a/packages/twenty-apps/public/call-recorder/src/front-components/utils/__tests__/resolve-call-recorder-application-id.test.ts b/packages/twenty-apps/public/call-recorder/src/front-components/utils/__tests__/resolve-call-recorder-application-id.test.ts
index f51742add86..3c31092a084 100644
--- a/packages/twenty-apps/public/call-recorder/src/front-components/utils/__tests__/resolve-call-recorder-application-id.test.ts
+++ b/packages/twenty-apps/public/call-recorder/src/front-components/utils/__tests__/resolve-call-recorder-application-id.test.ts
@@ -10,22 +10,28 @@ vi.mock('twenty-client-sdk/metadata', () => ({
},
}));
-import { resolveCallRecorderApplicationId } from 'src/front-components/utils/resolve-call-recorder-application-id.util';
-
describe('resolveCallRecorderApplicationId', () => {
beforeEach(() => {
+ vi.resetModules();
metadataQuery.mockReset();
});
+ const importResolver = async () => {
+ const module =
+ await import('src/front-components/utils/resolve-call-recorder-application-id.util');
+
+ return module.resolveCallRecorderApplicationId;
+ };
+
it('shares one application lookup across concurrent saves', async () => {
metadataQuery.mockResolvedValue({
- frontComponent: { applicationId: 'application-id' },
+ findOneApplication: { id: 'application-id' },
});
- const firstResolution =
- resolveCallRecorderApplicationId('front-component-id');
- const secondResolution =
- resolveCallRecorderApplicationId('front-component-id');
+ const resolveCallRecorderApplicationId = await importResolver();
+
+ const firstResolution = resolveCallRecorderApplicationId();
+ const secondResolution = resolveCallRecorderApplicationId();
await expect(firstResolution).resolves.toBe('application-id');
await expect(secondResolution).resolves.toBe('application-id');
@@ -34,17 +40,17 @@ describe('resolveCallRecorderApplicationId', () => {
it('retries the lookup after a failed resolution', async () => {
metadataQuery
- .mockResolvedValueOnce({ frontComponent: null })
- .mockResolvedValueOnce({
- frontComponent: { applicationId: 'application-id' },
- });
-
- await expect(
- resolveCallRecorderApplicationId('retry-front-component-id'),
- ).rejects.toThrow('Could not resolve the call recorder application.');
- await expect(
- resolveCallRecorderApplicationId('retry-front-component-id'),
- ).resolves.toBe('application-id');
+ .mockResolvedValueOnce({ findOneApplication: null })
+ .mockResolvedValueOnce({ findOneApplication: { id: 'application-id' } });
+
+ const resolveCallRecorderApplicationId = await importResolver();
+
+ await expect(resolveCallRecorderApplicationId()).rejects.toThrow(
+ 'Could not resolve the call recorder application.',
+ );
+ await expect(resolveCallRecorderApplicationId()).resolves.toBe(
+ 'application-id',
+ );
expect(metadataQuery).toHaveBeenCalledTimes(2);
});
diff --git a/packages/twenty-apps/public/call-recorder/src/front-components/utils/resolve-call-recorder-application-id.util.ts b/packages/twenty-apps/public/call-recorder/src/front-components/utils/resolve-call-recorder-application-id.util.ts
index 176a5621457..041e28fabf4 100644
--- a/packages/twenty-apps/public/call-recorder/src/front-components/utils/resolve-call-recorder-application-id.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/front-components/utils/resolve-call-recorder-application-id.util.ts
@@ -1,20 +1,19 @@
import { isNonEmptyString, isUndefined } from '@sniptt/guards';
import { MetadataApiClient } from 'twenty-client-sdk/metadata';
-const applicationIdPromiseByFrontComponentId = new Map<
- string,
- Promise<string>
->();
+import { APPLICATION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
-const fetchCallRecorderApplicationId = async (frontComponentId: string) => {
+let applicationIdPromise: Promise<string> | undefined;
+
+const fetchCallRecorderApplicationId = async () => {
const client = new MetadataApiClient();
- const frontComponentResult = await client.query({
- frontComponent: {
- __args: { id: frontComponentId },
- applicationId: true,
+ const applicationResult = await client.query({
+ findOneApplication: {
+ __args: { universalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER },
+ id: true,
},
});
- const applicationId = frontComponentResult.frontComponent?.applicationId;
+ const applicationId = applicationResult.findOneApplication?.id;
if (!isNonEmptyString(applicationId)) {
throw new Error('Could not resolve the call recorder application.');
@@ -23,32 +22,20 @@ const fetchCallRecorderApplicationId = async (frontComponentId: string) => {
return applicationId;
};
-export const resolveCallRecorderApplicationId = (
- frontComponentId: string,
-): Promise<string> => {
- const existingApplicationIdPromise =
- applicationIdPromiseByFrontComponentId.get(frontComponentId);
-
- if (isUndefined(existingApplicationIdPromise)) {
- const applicationIdPromise =
- fetchCallRecorderApplicationId(frontComponentId);
-
- applicationIdPromiseByFrontComponentId.set(
- frontComponentId,
- applicationIdPromise,
- );
-
- void applicationIdPromise.catch(() => {
- if (
- applicationIdPromiseByFrontComponentId.get(frontComponentId) ===
- applicationIdPromise
- ) {
- applicationIdPromiseByFrontComponentId.delete(frontComponentId);
+export const resolveCallRecorderApplicationId = (): Promise<string> => {
+ if (isUndefined(applicationIdPromise)) {
+ const pendingApplicationIdPromise = fetchCallRecorderApplicationId();
+
+ applicationIdPromise = pendingApplicationIdPromise;
+
+ void pendingApplicationIdPromise.catch(() => {
+ if (applicationIdPromise === pendingApplicationIdPromise) {
+ applicationIdPromise = undefined;
}
});
- return applicationIdPromise;
+ return pendingApplicationIdPromise;
}
- return existingApplicationIdPromise;
+ return applicationIdPromise;
};
diff --git a/packages/twenty-apps/public/companion/package.json b/packages/twenty-apps/public/companion/package.json
index 8518f18ae9f..296d285fd58 100644
--- a/packages/twenty-apps/public/companion/package.json
+++ b/packages/twenty-apps/public/companion/package.json
@@ -1,6 +1,6 @@
{
"name": "@twentyhq/companion-app",
- "version": "0.1.0",
+ "version": "0.1.1",
"license": "MIT",
"engines": {
"node": "^24.5.0",
diff --git a/packages/twenty-apps/public/companion/src/components/DesktopSettings.tsx b/packages/twenty-apps/public/companion/src/components/DesktopSettings.tsx
index ac331e7c22e..1f0875b62a8 100644
--- a/packages/twenty-apps/public/companion/src/components/DesktopSettings.tsx
+++ b/packages/twenty-apps/public/companion/src/components/DesktopSettings.tsx
@@ -1,10 +1,12 @@
import { useEffect, useState } from 'react';
import { MetadataApiClient } from 'twenty-client-sdk/metadata';
-import { useFrontComponentId, useTranslate } from 'twenty-sdk/front-component';
+import { useTranslate } from 'twenty-sdk/front-component';
import { Button } from 'twenty-ui/input';
import { H2Title } from 'twenty-ui/typography';
import { themeCssVariables } from 'twenty-ui/theme-constants';
+import { APPLICATION_UNIVERSAL_IDENTIFIER } from 'src/constants/APPLICATION_UNIVERSAL_IDENTIFIER';
+
type ApplicationVariable = {
key: string;
value: string;
@@ -13,7 +15,6 @@ type ApplicationVariable = {
export const DesktopSettings = () => {
const { t } = useTranslate();
- const frontComponentId = useFrontComponentId();
const [applicationId, setApplicationId] = useState<string>();
const [variables, setVariables] = useState<ApplicationVariable[]>([]);
const [drafts, setDrafts] = useState<Record<string, string>>({});
@@ -39,17 +40,10 @@ export const DesktopSettings = () => {
const load = async () => {
try {
const client = new MetadataApiClient();
- const component = await client.query({
- frontComponent: {
- __args: { id: frontComponentId },
- applicationId: true,
- },
- });
- const id = component.frontComponent?.applicationId;
- if (!id) throw new Error('Settings application not found');
const result = await client.query({
findOneApplication: {
- __args: { id },
+ __args: { universalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER },
+ id: true,
applicationVariables: {
key: true,
value: true,
@@ -60,6 +54,8 @@ export const DesktopSettings = () => {
},
});
if (cancelled) return;
+ const id = result.findOneApplication?.id;
+ if (!id) throw new Error('Settings application not found');
setVariables(
(result.findOneApplication?.applicationVariables ?? []).filter(
(variable) => !variable.isDeprecated && !variable.isSecret,
@@ -74,7 +70,7 @@ export const DesktopSettings = () => {
return () => {
cancelled = true;
};
- }, [frontComponentId]);
+ }, []);
const save = async () => {
if (!applicationId) return;
diff --git a/packages/twenty-apps/public/fireflies/package.json b/packages/twenty-apps/public/fireflies/package.json
index bf94117499a..3c3425a5a22 100644
--- a/packages/twenty-apps/public/fireflies/package.json
+++ b/packages/twenty-apps/public/fireflies/package.json
@@ -1,6 +1,6 @@
{
"name": "@twentyhq/fireflies",
- "version": "0.4.0",
+ "version": "0.4.1",
"description": "Fireflies call-transcript connector for Twenty",
"license": "MIT",
"engines": {
diff --git a/packages/twenty-apps/public/fireflies/src/front-components/hooks/use-fireflies-application-variables.ts b/packages/twenty-apps/public/fireflies/src/front-components/hooks/use-fireflies-application-variables.ts
index a5645cb9700..8178c29cec9 100644
--- a/packages/twenty-apps/public/fireflies/src/front-components/hooks/use-fireflies-application-variables.ts
+++ b/packages/twenty-apps/public/fireflies/src/front-components/hooks/use-fireflies-application-variables.ts
@@ -1,8 +1,8 @@
import { isNonEmptyString } from '@sniptt/guards';
import { useEffect, useState } from 'react';
import { MetadataApiClient } from 'twenty-client-sdk/metadata';
-import { useFrontComponentId } from 'twenty-sdk/front-component';
+import { APPLICATION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
import { type FirefliesApplicationVariable } from 'src/front-components/types/fireflies-application-variable.type';
import { shouldDisplayApplicationVariable } from 'src/front-components/utils/should-display-application-variable.util';
@@ -25,7 +25,6 @@ const APPLICATION_VARIABLES_LOADING_STATE: FirefliesApplicationVariablesState =
export const useFirefliesApplicationVariables =
(): FirefliesApplicationVariablesState => {
- const frontComponentId = useFrontComponentId();
const [state, setState] = useState<FirefliesApplicationVariablesState>(
APPLICATION_VARIABLES_LOADING_STATE,
);
@@ -38,31 +37,10 @@ export const useFirefliesApplicationVariables =
const fetchApplicationVariables = async () => {
try {
const client = new MetadataApiClient();
- const frontComponentResult = await client.query({
- frontComponent: {
- __args: { id: frontComponentId },
- applicationId: true,
- },
- });
-
- const applicationId =
- frontComponentResult.frontComponent?.applicationId;
-
- if (!isNonEmptyString(applicationId)) {
- if (!cancelled) {
- setState({
- applicationId: undefined,
- applicationVariables: [],
- isApplicationVariablesQueryLoading: false,
- errorMessage: APPLICATION_VARIABLES_ERROR_MESSAGE,
- });
- }
- return;
- }
-
const applicationResult = await client.query({
findOneApplication: {
- __args: { id: applicationId },
+ __args: { universalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER },
+ id: true,
applicationVariables: {
key: true,
value: true,
@@ -77,6 +55,18 @@ export const useFirefliesApplicationVariables =
return;
}
+ const applicationId = applicationResult.findOneApplication?.id;
+
+ if (!isNonEmptyString(applicationId)) {
+ setState({
+ applicationId: undefined,
+ applicationVariables: [],
+ isApplicationVariablesQueryLoading: false,
+ errorMessage: APPLICATION_VARIABLES_ERROR_MESSAGE,
+ });
+ return;
+ }
+
const applicationVariables = [
...(applicationResult.findOneApplication?.applicationVariables ??
[]),
@@ -109,7 +99,7 @@ export const useFirefliesApplicationVariables =
return () => {
cancelled = true;
};
- }, [frontComponentId]);
+ }, []);
return state;
};
diff --git a/packages/twenty-apps/public/granola/package.json b/packages/twenty-apps/public/granola/package.json
index bd913cffe89..3a236f1707d 100644
--- a/packages/twenty-apps/public/granola/package.json
+++ b/packages/twenty-apps/public/granola/package.json
@@ -1,6 +1,6 @@
{
"name": "@twentyhq/granola",
- "version": "0.1.0",
+ "version": "0.1.1",
"description": "Sync Granola meeting notes into Twenty Call Recordings",
"license": "MIT",
"engines": {
diff --git a/packages/twenty-apps/public/granola/src/front-components/components/GranolaSettings.tsx b/packages/twenty-apps/public/granola/src/front-components/components/GranolaSettings.tsx
index ed60e7b5b4e..f5ada619145 100644
--- a/packages/twenty-apps/public/granola/src/front-components/components/GranolaSettings.tsx
+++ b/packages/twenty-apps/public/granola/src/front-components/components/GranolaSettings.tsx
@@ -2,12 +2,7 @@ import 'twenty-ui/style.css';
import styled from '@emotion/styled';
import { useState } from 'react';
-import {
- enqueueSnackbar,
- t,
- useColorScheme,
- useFrontComponentId,
-} from 'twenty-sdk/front-component';
+import { enqueueSnackbar, t, useColorScheme } from 'twenty-sdk/front-component';
import { isDefined } from 'twenty-sdk/utils';
import { Info } from 'twenty-ui/feedback';
import { THEME_DARK, THEME_LIGHT } from 'twenty-ui/theme';
@@ -79,7 +74,6 @@ const registerGranolaLiveSync = async (): Promise<boolean> => {
export const GranolaSettings = () => {
const colorScheme = useColorScheme();
- const frontComponentId = useFrontComponentId();
const [state, setState] = useState<GranolaSettingsState>({ step: 'loading' });
const [isSettingUpConnection, setIsSettingUpConnection] = useState(true);
const [hasSetupFailed, setHasSetupFailed] = useState(false);
@@ -142,7 +136,7 @@ export const GranolaSettings = () => {
setConnectError(undefined);
try {
- await setGranolaApiKeyOrThrow({ frontComponentId, apiKey });
+ await setGranolaApiKeyOrThrow({ apiKey });
} catch {
setConnectError(t('Could not save the API key. Try again.'));
setIsSettingUpConnection(false);
@@ -167,7 +161,7 @@ export const GranolaSettings = () => {
routePath: GRANOLA_WEBHOOK_REMOVAL_ROUTE_PATH,
body: {},
});
- await setGranolaApiKeyOrThrow({ frontComponentId, apiKey: '' });
+ await setGranolaApiKeyOrThrow({ apiKey: '' });
setConnectError(undefined);
setHasSetupFailed(false);
} catch {
diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/set-granola-api-key-or-throw.util.ts b/packages/twenty-apps/public/granola/src/front-components/utils/set-granola-api-key-or-throw.util.ts
index 15269723a6e..dc896ec2e3b 100644
--- a/packages/twenty-apps/public/granola/src/front-components/utils/set-granola-api-key-or-throw.util.ts
+++ b/packages/twenty-apps/public/granola/src/front-components/utils/set-granola-api-key-or-throw.util.ts
@@ -1,23 +1,22 @@
import { isNonEmptyString } from '@sniptt/guards';
import { MetadataApiClient } from 'twenty-client-sdk/metadata';
+import { APPLICATION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
import { GRANOLA_API_KEY_ENV_VAR_NAME } from 'src/logic-functions/constants/granola-api-key-env-var-name';
export const setGranolaApiKeyOrThrow = async ({
- frontComponentId,
apiKey,
}: {
- frontComponentId: string;
apiKey: string;
}): Promise<void> => {
const client = new MetadataApiClient();
const result = await client.query({
- frontComponent: {
- __args: { id: frontComponentId },
- applicationId: true,
+ findOneApplication: {
+ __args: { universalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER },
+ id: true,
},
});
- const applicationId = result.frontComponent?.applicationId;
+ const applicationId = result.findOneApplication?.id;
if (!isNonEmptyString(applicationId)) {
throw new Error('Could not find the Granola application.');
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index a2f5857e68b..60598df5c12 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -3958,7 +3958,7 @@ type Mutation {
revokeUserSession(userSessionId: UUID!): Boolean!
revokeAllOtherUserSessions: Int!
deleteConnectedAccount(id: UUID!): ConnectedAccountPublicDTO!
- updateOneApplicationVariable(key: String!, value: String!, applicationId: UUID!): Boolean!
+ updateOneApplicationVariable(key: String!, value: String!, applicationId: UUID): Boolean!
checkoutSession(recurringInterval: SubscriptionInterval!, plan: BillingPlanKey! = PRO, requirePaymentMethod: Boolean! = true, successUrlPath: String): BillingSession!
createSubscriptionPaymentIntent(recurringInterval: SubscriptionInterval!, plan: BillingPlanKey! = PRO, requirePaymentMethod: Boolean! = true, successUrlPath: String, idempotencyKey: String!): BillingPaymentIntent!
createBillingPaymentMethodSetupIntent: BillingPaymentIntent!
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index 2031ebd6d06..3431c16d35c 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -7172,7 +7172,7 @@ export interface MutationGenqlSelection{
revokeUserSession?: { __args: {userSessionId: Scalars['UUID']} }
revokeAllOtherUserSessions?: boolean | number
deleteConnectedAccount?: (ConnectedAccountPublicDTOGenqlSelection & { __args: {id: Scalars['UUID']} })
- updateOneApplicationVariable?: { __args: {key: Scalars['String'], value: Scalars['String'], applicationId: Scalars['UUID']} }
+ updateOneApplicationVariable?: { __args: {key: Scalars['String'], value: Scalars['String'], applicationId?: (Scalars['UUID'] | null)} }
checkoutSession?: (BillingSessionGenqlSelection & { __args: {recurringInterval: SubscriptionInterval, plan: BillingPlanKey, requirePaymentMethod: Scalars['Boolean'], successUrlPath?: (Scalars['String'] | null)} })
createSubscriptionPaymentIntent?: (BillingPaymentIntentGenqlSelection & { __args: {recurringInterval: SubscriptionInterval, plan: BillingPlanKey, requirePaymentMethod: Scalars['Boolean'], successUrlPath?: (Scalars['String'] | null), idempotencyKey: Scalars['String']} })
createBillingPaymentMethodSetupIntent?: BillingPaymentIntentGenqlSelection
diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.ts
index 9c3ff167a9f..21f3038a9ad 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts
@@ -8842,8 +8842,7 @@ export default {
"String!"
],
"applicationId": [
- 3,
- "UUID!"
+ 3
]
}
],
diff --git a/packages/twenty-docs/developers/extend/apps/config/application.mdx b/packages/twenty-docs/developers/extend/apps/config/application.mdx
index 555c8244125..a966edd7ac4 100644
--- a/packages/twenty-docs/developers/extend/apps/config/application.mdx
+++ b/packages/twenty-docs/developers/extend/apps/config/application.mdx
@@ -35,6 +35,7 @@ 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.
+- 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 are detected automatically during the manifest build — you do not need to reference them in `defineApplication()`.
- Passing `defaultRoleUniversalIdentifier` explicitly is still supported for backward compatibility, but is deprecated in favor of `defineApplicationRole()`.
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 d23cecc69ce..1ecbf982ac3 100644
--- a/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx
+++ b/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx
@@ -448,6 +448,43 @@ Secret variables (`isSecret: true`) are **not** exposed to front components. The
`getApplicationVariable` always returns a **string** (or `undefined`), regardless of the variable's declared `type`. The string is serialized consistently by type (booleans as `"true"` / `"false"`, numbers as decimal strings, arrays / objects as JSON), the same format used for logic-function `process.env` — parse it yourself (`Number(...)`, `JSON.parse(...)`, `=== 'true'`). See [Variable types](/developers/extend/apps/config/application#variable-types).
+### Reading and updating variables at runtime
+
+`getApplicationVariable` returns the values injected when the component loaded, so a value written afterwards only shows up on the next load. To read the stored values, or to write one (what a [custom settings component](#custom-settings-component) does when it saves what the user typed), go through `MetadataApiClient`:
+
+```tsx src/front-components/app-settings.tsx
+import { MetadataApiClient } from 'twenty-client-sdk/metadata';
+
+const APPLICATION_UNIVERSAL_IDENTIFIER = '39783023-bcac-41e3-b0d2-ff1944d8465d';
+
+const readApplicationVariables = async () => {
+ const { findOneApplication } = await new MetadataApiClient().query({
+ findOneApplication: {
+ __args: { universalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER },
+ applicationVariables: { key: true, value: true, isSecret: true },
+ },
+ });
+
+ return findOneApplication?.applicationVariables ?? [];
+};
+
+const saveRecipientName = async (recipientName: string) => {
+ await new MetadataApiClient().mutation({
+ updateOneApplicationVariable: {
+ __args: { key: 'DEFAULT_RECIPIENT_NAME', value: recipientName },
+ },
+ });
+};
+```
+
+Notes:
+- Your component's token is bound to your own application. `updateOneApplicationVariable` targets it, so `applicationId` is optional and naming another application is refused. Reading the `applicationVariables` of another application is refused the same way, and an application belonging to another workspace reads as not found.
+- 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).
+
+### System variables
+
The following system variables are always available via `process.env`:
| Variable | Description |
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 a6e8b34a5f0..ccff5dbbf2b 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
@@ -906,6 +906,8 @@ setCompany(result.company);
`MetadataApiClient` ships pre-built with the SDK (no generation required). It queries the `/metadata` endpoint for workspace configuration, applications, and file uploads. It takes the same `runAs` option as `CoreApiClient` — see [Whose access a call uses](#whose-access-a-call-uses).
+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.
+
```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 9b605e21d82..c29a4f36af7 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -4257,7 +4257,7 @@ export type MutationUpdateOneAgentArgs = {
export type MutationUpdateOneApplicationVariableArgs = {
- applicationId: Scalars['UUID']['input'];
+ applicationId?: InputMaybe<Scalars['UUID']['input']>;
key: Scalars['String']['input'];
value: Scalars['String']['input'];
};
diff --git a/packages/twenty-oxlint-rules/rules/prefer-workspace-scoped-repository.spec.ts b/packages/twenty-oxlint-rules/rules/prefer-workspace-scoped-repository.spec.ts
index ee880a71740..f6178d03567 100644
--- a/packages/twenty-oxlint-rules/rules/prefer-workspace-scoped-repository.spec.ts
+++ b/packages/twenty-oxlint-rules/rules/prefer-workspace-scoped-repository.spec.ts
@@ -83,6 +83,25 @@ ruleTester.run(RULE_NAME, rule, {
},
],
},
+ {
+ // Application variables carry secrets per workspace: a raw repository
+ // once let a caller overwrite another workspace's variable by id.
+ code: `
+ class ApplicationVariableEntityService {
+ constructor(
+ @InjectRepository(ApplicationVariableEntity)
+ private readonly applicationVariableRepository: Repository<ApplicationVariableEntity>,
+ ) {}
+ }
+ `,
+ filename: 'application-variable.service.ts',
+ errors: [
+ {
+ messageId: 'preferWorkspaceScopedRepository',
+ data: { entityName: 'ApplicationVariableEntity' },
+ },
+ ],
+ },
{
// Plain (non-parameter-property) constructor parameter with an
// explicit assignment in the body. Must still be caught — the
diff --git a/packages/twenty-oxlint-rules/rules/prefer-workspace-scoped-repository.ts b/packages/twenty-oxlint-rules/rules/prefer-workspace-scoped-repository.ts
index 45f23ae86c1..31f45fcd43d 100644
--- a/packages/twenty-oxlint-rules/rules/prefer-workspace-scoped-repository.ts
+++ b/packages/twenty-oxlint-rules/rules/prefer-workspace-scoped-repository.ts
@@ -18,7 +18,6 @@ const STRUCTURAL_EXEMPTIONS = new Set<string>([
// user-scoped auth sessions; workspaceId is null for workspace-agnostic sessions
'UserSessionEntity',
- 'ApplicationVariableEntity',
'BillingMeterEntity',
'BillingPriceEntity',
'BillingProductEntity',
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-install/application-install.resolver.ts b/packages/twenty-server/src/engine/core-modules/application/application-install/application-install.resolver.ts
index 3739e5da8b2..4cdeecac449 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-install/application-install.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-install/application-install.resolver.ts
@@ -25,10 +25,13 @@ import { ApplicationRegistrationExceptionFilter } from 'src/engine/core-modules/
import { ApplicationService } from 'src/engine/core-modules/application/application.service';
import { ApplicationDTO } from 'src/engine/core-modules/application/dtos/application.dto';
import { UpdateApplicationInput } from 'src/engine/core-modules/application/dtos/update-application.input';
+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
+import { resolveTargetApplicationOrThrow } from 'src/engine/core-modules/application/utils/resolve-target-application-or-throw.util';
import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filters/auth-graphql-api-exception.filter';
import { ResolverValidationPipe } from 'src/engine/core-modules/graphql/pipes/resolver-validation.pipe';
import { JobStatusDTO } from 'src/engine/core-modules/message-queue/dtos/job-status.dto';
import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
+import { AuthApplication } from 'src/engine/decorators/auth/auth-application.decorator';
import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
import { AllowSuspendedWorkspace } from 'src/engine/decorators/auth/allow-suspended-workspace.decorator';
import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';
@@ -66,6 +69,8 @@ export class ApplicationInstallResolver {
@UseGuards(SettingsPermissionGuard(PermissionFlagType.APPLICATIONS))
async findOneApplication(
@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
+ @AuthApplication({ allowUndefined: true })
+ callingApplication: FlatApplication | undefined,
@Args('id', { type: () => UUIDScalarType, nullable: true }) id?: string,
@Args('universalIdentifier', {
type: () => UUIDScalarType,
@@ -73,11 +78,20 @@ export class ApplicationInstallResolver {
})
universalIdentifier?: string,
) {
- return await this.applicationService.findOneApplicationOrThrow({
- id,
- universalIdentifier,
- workspaceId,
- });
+ const { targetApplicationId, targetApplicationUniversalIdentifier } =
+ resolveTargetApplicationOrThrow({
+ callingApplication,
+ applicationId: id,
+ applicationUniversalIdentifier: universalIdentifier,
+ });
+
+ return await this.applicationService.findOneApplicationWithRelationsOrThrow(
+ {
+ id: targetApplicationId,
+ universalIdentifier: targetApplicationUniversalIdentifier,
+ workspaceId,
+ },
+ );
}
@Mutation(() => Boolean, {
@@ -113,7 +127,7 @@ export class ApplicationInstallResolver {
workspaceId: workspace.id,
});
- return this.applicationService.findOneApplicationOrThrow({
+ return this.applicationService.findOneApplicationWithRelationsOrThrow({
universalIdentifier,
workspaceId: workspace.id,
});
@@ -190,7 +204,7 @@ export class ApplicationInstallResolver {
@Args('input') input: UpdateApplicationInput,
@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
) {
- await this.applicationService.findOneApplicationOrThrow({
+ await this.applicationService.findOneApplicationWithRelationsOrThrow({
id,
workspaceId,
});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-install/services/__tests__/application-lifecycle-job.service.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-install/services/__tests__/application-lifecycle-job.service.spec.ts
index cc01ddd9618..5b9d880b3a5 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-install/services/__tests__/application-lifecycle-job.service.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-install/services/__tests__/application-lifecycle-job.service.spec.ts
@@ -18,7 +18,7 @@ const BROADCAST_TO = { workspaceId: WORKSPACE_ID };
describe('ApplicationLifecycleJobService', () => {
const applicationService = {
- findOneApplicationOrThrow: jest.fn().mockResolvedValue({}),
+ findOneApplicationWithRelationsOrThrow: jest.fn().mockResolvedValue({}),
} as unknown as ApplicationService;
const marketplaceQueryService = {
findRegistrationByUniversalIdentifier: jest
@@ -124,9 +124,9 @@ describe('ApplicationLifecycleJobService', () => {
const result = await service.triggerUninstallApplicationJob(target);
expect(result).toEqual({ jobId: UNINSTALL_JOB_ID });
- expect(applicationService.findOneApplicationOrThrow).toHaveBeenCalledWith(
- target,
- );
+ expect(
+ applicationService.findOneApplicationWithRelationsOrThrow,
+ ).toHaveBeenCalledWith(target);
expect(workspaceQueueService.add).toHaveBeenCalledWith(
TriggerUninstallApplicationJob.name,
target,
@@ -149,7 +149,7 @@ describe('ApplicationLifecycleJobService', () => {
it('does not queue anything when the application is not installed', async () => {
jest
- .spyOn(applicationService, 'findOneApplicationOrThrow')
+ .spyOn(applicationService, 'findOneApplicationWithRelationsOrThrow')
.mockRejectedValueOnce(new Error('Application not found'));
await expect(
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-install/services/application-lifecycle-job.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-install/services/application-lifecycle-job.service.ts
index 4a787b62e22..f787d930bc9 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-install/services/application-lifecycle-job.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-install/services/application-lifecycle-job.service.ts
@@ -75,7 +75,7 @@ export class ApplicationLifecycleJobService {
universalIdentifier,
workspaceId,
}: LifecycleJobTarget): Promise<{ jobId: string }> {
- await this.applicationService.findOneApplicationOrThrow({
+ await this.applicationService.findOneApplicationWithRelationsOrThrow({
universalIdentifier,
workspaceId,
});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-sync.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-sync.service.ts
index 49fbdb1e26f..ca1ab28864d 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-sync.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-sync.service.ts
@@ -257,12 +257,11 @@ export class ApplicationSyncService {
).toString('utf-8'),
) as PackageJson;
- const application = await this.applicationService.findOneApplicationOrThrow(
- {
+ const application =
+ await this.applicationService.findOneApplicationWithRelationsOrThrow({
universalIdentifier: manifest.application.universalIdentifier,
workspaceId,
- },
- );
+ });
const resolvedRegistrationId =
applicationRegistrationId ?? application.applicationRegistrationId;
@@ -351,9 +350,11 @@ export class ApplicationSyncService {
applicationUniversalIdentifier: string;
shouldRunUninstallHook?: boolean;
}): Promise<WorkspaceMigration> {
- const application = await this.applicationService.findOneApplicationOrThrow(
- { universalIdentifier: applicationUniversalIdentifier, workspaceId },
- );
+ const application =
+ await this.applicationService.findOneApplicationWithRelationsOrThrow({
+ universalIdentifier: applicationUniversalIdentifier,
+ workspaceId,
+ });
if (!application.canBeUninstalled) {
throw new ApplicationException(
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 0d3448aab8e..b1255ce88ac 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
@@ -9,6 +9,7 @@ import { WorkspaceApplicationVariableMapCacheService } from 'src/engine/core-mod
import { SecretEncryptionModule } from 'src/engine/core-modules/secret-encryption/secret-encryption.module';
import { FlatApplicationVariableModule } from 'src/engine/metadata-modules/flat-application-variable/flat-application-variable.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({
@@ -20,6 +21,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
FlatApplicationVariableModule,
],
providers: [
+ provideWorkspaceScopedRepository(ApplicationVariableEntity),
ApplicationVariableEntityService,
ApplicationVariableEntityResolver,
WorkspaceApplicationVariableMapCacheService,
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-variable/application-variable.resolver.ts b/packages/twenty-server/src/engine/core-modules/application/application-variable/application-variable.resolver.ts
index 1ed6e900364..aa89c136a6f 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-variable/application-variable.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-variable/application-variable.resolver.ts
@@ -2,13 +2,18 @@ import { UseFilters, UseGuards } from '@nestjs/common';
import { Args, Mutation, Parent, ResolveField } from '@nestjs/graphql';
import { PermissionFlagType } from 'twenty-shared/constants';
+import { assertIsDefinedOrThrow } from 'twenty-shared/utils';
+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 { ApplicationVariableEntity } from 'src/engine/core-modules/application/application-variable/application-variable.entity';
import { ApplicationVariableEntityService } from 'src/engine/core-modules/application/application-variable/application-variable.service';
import { ApplicationVariableEntityDTO } from 'src/engine/core-modules/application/application-variable/dtos/application-variable.dto';
import { UpdateApplicationVariableEntityInput } from 'src/engine/core-modules/application/application-variable/dtos/update-application-variable.input';
+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
+import { resolveTargetApplicationOrThrow } from 'src/engine/core-modules/application/utils/resolve-target-application-or-throw.util';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
+import { AuthApplication } from 'src/engine/decorators/auth/auth-application.decorator';
import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
import { MetadataResolver } from 'src/engine/api/graphql/graphql-config/decorators/metadata-resolver.decorator';
import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';
@@ -22,6 +27,7 @@ import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filt
@MetadataResolver(() => ApplicationVariableEntityDTO)
@UseFilters(
ApplicationVariableEntityExceptionFilter,
+ ApplicationExceptionFilter,
AuthGraphqlApiExceptionFilter,
)
export class ApplicationVariableEntityResolver {
@@ -38,11 +44,21 @@ export class ApplicationVariableEntityResolver {
async updateOneApplicationVariable(
@Args() { key, value, applicationId }: UpdateApplicationVariableEntityInput,
@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
+ @AuthApplication({ allowUndefined: true })
+ callingApplication: FlatApplication | undefined,
) {
+ const { targetApplicationId } = resolveTargetApplicationOrThrow({
+ callingApplication,
+ applicationId,
+ });
+
+ // Without a universal identifier the lookup always carries an id
+ assertIsDefinedOrThrow(targetApplicationId);
+
await this.applicationVariableService.update({
key,
plainTextValue: value,
- applicationId,
+ applicationId: targetApplicationId,
workspaceId,
});
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 3966ef81240..1ec26a67335 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
@@ -1,8 +1,6 @@
import { Injectable } from '@nestjs/common';
-import { InjectRepository } from '@nestjs/typeorm';
import { isDefined } from 'twenty-shared/utils';
-import { Repository } from 'typeorm';
import { ApplicationVariableEntity } from 'src/engine/core-modules/application/application-variable/application-variable.entity';
import {
@@ -14,6 +12,8 @@ import { type ApplicationVariableCacheMaps } from 'src/engine/core-modules/appli
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 { 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 GetEnvVariablesArgs = {
@@ -25,8 +25,8 @@ type GetEnvVariablesArgs = {
@Injectable()
export class ApplicationVariableEntityService {
constructor(
- @InjectRepository(ApplicationVariableEntity)
- private readonly applicationVariableRepository: Repository<ApplicationVariableEntity>,
+ @InjectWorkspaceScopedRepository(ApplicationVariableEntity)
+ private readonly applicationVariableRepository: WorkspaceScopedRepository<ApplicationVariableEntity>,
private readonly workspaceCacheService: WorkspaceCacheService,
private readonly secretEncryptionService: SecretEncryptionService,
) {}
@@ -131,9 +131,10 @@ export class ApplicationVariableEntityService {
workspaceId: string;
plainTextValue: PlaintextString;
}) {
- const existingVariable = await this.applicationVariableRepository.findOne({
- where: { key, applicationId },
- });
+ const existingVariable = await this.applicationVariableRepository.findOne(
+ workspaceId,
+ { where: { key, applicationId } },
+ );
if (!isDefined(existingVariable)) {
throw new ApplicationVariableEntityException(
@@ -143,6 +144,7 @@ export class ApplicationVariableEntityService {
}
await this.applicationVariableRepository.update(
+ workspaceId,
{ key, applicationId },
{
value: this.secretEncryptionService.encryptVersioned(plainTextValue, {
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-variable/dtos/update-application-variable.input.ts b/packages/twenty-server/src/engine/core-modules/application/application-variable/dtos/update-application-variable.input.ts
index 323e29a964b..784407bf1d7 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-variable/dtos/update-application-variable.input.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-variable/dtos/update-application-variable.input.ts
@@ -11,6 +11,7 @@ export class UpdateApplicationVariableEntityInput {
@Field(() => String, { nullable: false })
value: PlaintextString;
- @Field(() => UUIDScalarType, { nullable: false })
- applicationId: string;
+ // Inferred from the token for an application caller; required for a session
+ @Field(() => UUIDScalarType, { nullable: true })
+ applicationId?: string;
}
diff --git a/packages/twenty-server/src/engine/core-modules/application/application.module.ts b/packages/twenty-server/src/engine/core-modules/application/application.module.ts
index be0124c3638..d183f2c11a6 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application.module.ts
@@ -53,6 +53,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
ApplicationGaugeService,
WorkspaceFlatApplicationMapCacheService,
provideWorkspaceScopedRepository(AgentEntity),
+ provideWorkspaceScopedRepository(ApplicationVariableEntity),
provideWorkspaceScopedRepository(CommandMenuItemEntity),
],
})
diff --git a/packages/twenty-server/src/engine/core-modules/application/application.resolver.ts b/packages/twenty-server/src/engine/core-modules/application/application.resolver.ts
index 7abc3cbd4e6..1349adbf700 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application.resolver.ts
@@ -6,12 +6,21 @@ import { isDefined } from 'twenty-shared/utils';
import { MetadataResolver } from 'src/engine/api/graphql/graphql-config/decorators/metadata-resolver.decorator';
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
import { ApplicationStopService } from 'src/engine/core-modules/application/application-stop/application-stop.service';
+import { type ApplicationVariableEntity } from 'src/engine/core-modules/application/application-variable/application-variable.entity';
+import { ApplicationVariableEntityDTO } from 'src/engine/core-modules/application/application-variable/dtos/application-variable.dto';
+import {
+ ApplicationException,
+ ApplicationExceptionCode,
+} from 'src/engine/core-modules/application/application.exception';
import { ApplicationDTO } from 'src/engine/core-modules/application/dtos/application.dto';
+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
import { buildPublicAssetLogoUrl } from 'src/engine/core-modules/application/utils/build-public-asset-logo-url.util';
+import { ForbiddenError } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
import { SdkClientChecksumsDTO } from 'src/engine/core-modules/sdk-client/dtos/sdk-client-checksums.dto';
import { getInstalledSdkMetadataModule } from 'src/engine/core-modules/sdk-client/utils/get-installed-sdk-metadata-module.util';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
+import { AuthApplication } from 'src/engine/decorators/auth/auth-application.decorator';
import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
import { NoPermissionGuard } from 'src/engine/guards/no-permission.guard';
import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
@@ -76,4 +85,28 @@ export class ApplicationResolver {
applicationId: application.id,
});
}
+
+ @ResolveField(() => [ApplicationVariableEntityDTO])
+ applicationVariables(
+ @Parent()
+ application: Pick<ApplicationDTO, 'id'> & {
+ applicationVariables?: ApplicationVariableEntity[];
+ },
+ @AuthApplication({ allowUndefined: true })
+ callingApplication: FlatApplication | undefined,
+ ): ApplicationVariableEntity[] | undefined {
+ if (
+ isDefined(callingApplication) &&
+ callingApplication.id !== application.id
+ ) {
+ throw new ForbiddenError(
+ new ApplicationException(
+ 'An application token can only read its own application variables',
+ ApplicationExceptionCode.FORBIDDEN,
+ ),
+ );
+ }
+
+ return application.applicationVariables;
+ }
}
diff --git a/packages/twenty-server/src/engine/core-modules/application/application.service.ts b/packages/twenty-server/src/engine/core-modules/application/application.service.ts
index c15715d6c8b..6a878d4f998 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application.service.ts
@@ -59,8 +59,8 @@ export class ApplicationService {
private readonly commandMenuItemRepository: WorkspaceScopedRepository<CommandMenuItemEntity>,
@InjectRepository(ObjectMetadataEntity)
private readonly objectMetadataRepository: Repository<ObjectMetadataEntity>,
- @InjectRepository(ApplicationVariableEntity)
- private readonly applicationVariableRepository: Repository<ApplicationVariableEntity>,
+ @InjectWorkspaceScopedRepository(ApplicationVariableEntity)
+ private readonly applicationVariableRepository: WorkspaceScopedRepository<ApplicationVariableEntity>,
private readonly workspaceEventBroadcaster: WorkspaceEventBroadcaster,
) {}
@@ -172,7 +172,7 @@ export class ApplicationService {
);
}
- async findOneApplication({
+ async findOneApplicationWithRelations({
id,
universalIdentifier,
workspaceId,
@@ -225,8 +225,8 @@ export class ApplicationService {
this.objectMetadataRepository.find({
where: { applicationId: application.id, workspaceId },
}),
- this.applicationVariableRepository.find({
- where: { applicationId: application.id, workspaceId },
+ this.applicationVariableRepository.find(workspaceId, {
+ where: { applicationId: application.id },
}),
]);
@@ -240,7 +240,7 @@ export class ApplicationService {
return application;
}
- async findOneApplicationOrThrow({
+ async findOneApplicationWithRelationsOrThrow({
id,
universalIdentifier,
workspaceId,
@@ -249,7 +249,7 @@ export class ApplicationService {
universalIdentifier?: string;
workspaceId: string;
}): Promise<ApplicationEntity> {
- const application = await this.findOneApplication({
+ const application = await this.findOneApplicationWithRelations({
id,
universalIdentifier,
workspaceId,
diff --git a/packages/twenty-server/src/engine/core-modules/application/front-component-shared-dependencies/front-component-shared-dependencies.service.ts b/packages/twenty-server/src/engine/core-modules/application/front-component-shared-dependencies/front-component-shared-dependencies.service.ts
index 14a6a7fc93f..ecad9fea7c0 100644
--- a/packages/twenty-server/src/engine/core-modules/application/front-component-shared-dependencies/front-component-shared-dependencies.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/front-component-shared-dependencies/front-component-shared-dependencies.service.ts
@@ -33,12 +33,11 @@ export class FrontComponentSharedDependenciesService {
fileResponse: FileResponse;
frontComponentSharedDependenciesChecksum: string | null;
}> {
- const application = await this.applicationService.findOneApplicationOrThrow(
- {
+ const application =
+ await this.applicationService.findOneApplicationWithRelationsOrThrow({
id: applicationId,
workspaceId,
- },
- );
+ });
if (!isDefined(application.frontComponentSharedDependenciesBuiltPath)) {
throw new ApplicationException(
diff --git a/packages/twenty-server/src/engine/core-modules/application/utils/__tests__/resolve-target-application-or-throw.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/utils/__tests__/resolve-target-application-or-throw.util.spec.ts
new file mode 100644
index 00000000000..6ad8ac1a77b
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/utils/__tests__/resolve-target-application-or-throw.util.spec.ts
@@ -0,0 +1,116 @@
+import { ApplicationExceptionCode } from 'src/engine/core-modules/application/application.exception';
+import { resolveTargetApplicationOrThrow } from 'src/engine/core-modules/application/utils/resolve-target-application-or-throw.util';
+
+const CALLING_APPLICATION = {
+ id: 'b1a4c0d2-6e1f-4a6b-9c1d-0f2e3a4b5c6d',
+ universalIdentifier: '7d3c2b1a-0f9e-4d8c-b7a6-5f4e3d2c1b0a',
+};
+
+const OTHER_APPLICATION = {
+ id: 'e5f6a7b8-c9d0-4e1f-a2b3-c4d5e6f7a8b9',
+ universalIdentifier: '1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d',
+};
+
+const expectForbidden = (resolve: () => unknown) => {
+ expect(resolve).toThrow(
+ expect.objectContaining({ code: ApplicationExceptionCode.FORBIDDEN }),
+ );
+};
+
+const expectInvalidInput = (resolve: () => unknown) => {
+ expect(resolve).toThrow(
+ expect.objectContaining({ code: ApplicationExceptionCode.INVALID_INPUT }),
+ );
+};
+
+describe('resolveTargetApplicationOrThrow', () => {
+ describe('with an application caller', () => {
+ it('should target the calling application when no argument is given', () => {
+ expect(
+ resolveTargetApplicationOrThrow({
+ callingApplication: CALLING_APPLICATION,
+ }),
+ ).toEqual({ targetApplicationId: CALLING_APPLICATION.id });
+ });
+
+ it('should accept the calling application named by id or universal identifier', () => {
+ expect(
+ resolveTargetApplicationOrThrow({
+ callingApplication: CALLING_APPLICATION,
+ applicationId: CALLING_APPLICATION.id,
+ }),
+ ).toEqual({ targetApplicationId: CALLING_APPLICATION.id });
+ expect(
+ resolveTargetApplicationOrThrow({
+ callingApplication: CALLING_APPLICATION,
+ applicationUniversalIdentifier:
+ CALLING_APPLICATION.universalIdentifier,
+ }),
+ ).toEqual({ targetApplicationId: CALLING_APPLICATION.id });
+ });
+
+ it('should refuse another application named by id', () => {
+ expectForbidden(() =>
+ resolveTargetApplicationOrThrow({
+ callingApplication: CALLING_APPLICATION,
+ applicationId: OTHER_APPLICATION.id,
+ }),
+ );
+ });
+
+ it('should refuse another application named by universal identifier', () => {
+ expectForbidden(() =>
+ resolveTargetApplicationOrThrow({
+ callingApplication: CALLING_APPLICATION,
+ applicationUniversalIdentifier: OTHER_APPLICATION.universalIdentifier,
+ }),
+ );
+ });
+
+ it('should refuse another application even when its own id is also given', () => {
+ expectForbidden(() =>
+ resolveTargetApplicationOrThrow({
+ callingApplication: CALLING_APPLICATION,
+ applicationId: CALLING_APPLICATION.id,
+ applicationUniversalIdentifier: OTHER_APPLICATION.universalIdentifier,
+ }),
+ );
+ });
+ });
+
+ describe('without an application caller', () => {
+ it('should keep the one identifier given', () => {
+ expect(
+ resolveTargetApplicationOrThrow({
+ callingApplication: undefined,
+ applicationId: OTHER_APPLICATION.id,
+ }),
+ ).toEqual({ targetApplicationId: OTHER_APPLICATION.id });
+ expect(
+ resolveTargetApplicationOrThrow({
+ callingApplication: null,
+ applicationUniversalIdentifier: OTHER_APPLICATION.universalIdentifier,
+ }),
+ ).toEqual({
+ targetApplicationUniversalIdentifier:
+ OTHER_APPLICATION.universalIdentifier,
+ });
+ });
+
+ it('should refuse two identifiers, which nothing reconciles', () => {
+ expectInvalidInput(() =>
+ resolveTargetApplicationOrThrow({
+ callingApplication: undefined,
+ applicationId: CALLING_APPLICATION.id,
+ applicationUniversalIdentifier: OTHER_APPLICATION.universalIdentifier,
+ }),
+ );
+ });
+
+ it('should require an identifier', () => {
+ expectInvalidInput(() =>
+ resolveTargetApplicationOrThrow({ callingApplication: undefined }),
+ );
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/application/utils/resolve-target-application-or-throw.util.ts b/packages/twenty-server/src/engine/core-modules/application/utils/resolve-target-application-or-throw.util.ts
new file mode 100644
index 00000000000..bded90f043e
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/utils/resolve-target-application-or-throw.util.ts
@@ -0,0 +1,69 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import {
+ ApplicationException,
+ ApplicationExceptionCode,
+} from 'src/engine/core-modules/application/application.exception';
+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
+
+type TargetApplication =
+ | {
+ targetApplicationId: string;
+ targetApplicationUniversalIdentifier?: never;
+ }
+ | {
+ targetApplicationId?: never;
+ targetApplicationUniversalIdentifier: string;
+ };
+
+export const resolveTargetApplicationOrThrow = ({
+ callingApplication,
+ applicationId,
+ applicationUniversalIdentifier,
+}: {
+ callingApplication:
+ | Pick<FlatApplication, 'id' | 'universalIdentifier'>
+ | null
+ | undefined;
+ applicationId?: string | null;
+ applicationUniversalIdentifier?: string | null;
+}): TargetApplication => {
+ if (!isDefined(callingApplication)) {
+ if (isDefined(applicationId) && isDefined(applicationUniversalIdentifier)) {
+ throw new ApplicationException(
+ 'applicationId and applicationUniversalIdentifier cannot both be given',
+ ApplicationExceptionCode.INVALID_INPUT,
+ );
+ }
+
+ if (isDefined(applicationId)) {
+ return { targetApplicationId: applicationId };
+ }
+
+ if (isDefined(applicationUniversalIdentifier)) {
+ return {
+ targetApplicationUniversalIdentifier: applicationUniversalIdentifier,
+ };
+ }
+
+ throw new ApplicationException(
+ 'applicationId or applicationUniversalIdentifier is required unless the caller is an application',
+ ApplicationExceptionCode.INVALID_INPUT,
+ );
+ }
+
+ const namesAnotherApplication =
+ (isDefined(applicationId) && applicationId !== callingApplication.id) ||
+ (isDefined(applicationUniversalIdentifier) &&
+ applicationUniversalIdentifier !==
+ callingApplication.universalIdentifier);
+
+ if (namesAnotherApplication) {
+ throw new ApplicationException(
+ 'An application token can only target its own application',
+ ApplicationExceptionCode.FORBIDDEN,
+ );
+ }
+
+ return { targetApplicationId: callingApplication.id };
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/front-component/front-component.service.ts b/packages/twenty-server/src/engine/metadata-modules/front-component/front-component.service.ts
index f71937fb201..cde282935ec 100644
--- a/packages/twenty-server/src/engine/metadata-modules/front-component/front-component.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/front-component/front-component.service.ts
@@ -310,12 +310,11 @@ export class FrontComponentService {
workspaceId,
);
- const application = await this.applicationService.findOneApplicationOrThrow(
- {
+ const application =
+ await this.applicationService.findOneApplicationWithRelationsOrThrow({
id: frontComponent.applicationId,
workspaceId,
- },
- );
+ });
const mimeType = 'application/javascript';
const resourceIdentifier = {
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/__snapshots__/failing-application-variable-cross-application-access.integration-spec.ts.snap b/packages/twenty-server/test/integration/metadata/suites/application/__snapshots__/failing-application-variable-cross-application-access.integration-spec.ts.snap
new file mode 100644
index 00000000000..4524ad468a3
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/application/__snapshots__/failing-application-variable-cross-application-access.integration-spec.ts.snap
@@ -0,0 +1,109 @@
+// Jest Snapshot v1, https://goo.gl/fbAQLP
+
+exports[`Application variable access across applications should fail should refuse two application identifiers from a session 1`] = `
+{
+ "extensions": {
+ "code": "BAD_USER_INPUT",
+ "subCode": "INVALID_INPUT",
+ "userFriendlyMessage": "Invalid input provided.",
+ },
+ "message": "applicationId and applicationUniversalIdentifier cannot both be given",
+ "name": "UserInputError",
+}
+`;
+
+exports[`Application variable access across applications should fail should require an application id from a session 1`] = `
+{
+ "extensions": {
+ "code": "BAD_USER_INPUT",
+ "subCode": "INVALID_INPUT",
+ "userFriendlyMessage": "Invalid input provided.",
+ },
+ "message": "applicationId or applicationUniversalIdentifier is required unless the caller is an application",
+ "name": "UserInputError",
+}
+`;
+
+exports[`Application variable access across applications should fail should require an application identifier from a session 1`] = `
+{
+ "extensions": {
+ "code": "BAD_USER_INPUT",
+ "subCode": "INVALID_INPUT",
+ "userFriendlyMessage": "Invalid input provided.",
+ },
+ "message": "applicationId or applicationUniversalIdentifier is required unless the caller is an application",
+ "name": "UserInputError",
+}
+`;
+
+exports[`Application variable access across applications should fail with a user-bound application token should refuse to read another application by id 1`] = `
+{
+ "extensions": {
+ "code": "FORBIDDEN",
+ "subCode": "FORBIDDEN",
+ "userFriendlyMessage": "You do not have permission to perform this action.",
+ },
+ "message": "An application token can only target its own application",
+ "name": "ForbiddenError",
+}
+`;
+
+exports[`Application variable access across applications should fail with a user-bound application token should refuse to read another application by universal identifier 1`] = `
+{
+ "extensions": {
+ "code": "FORBIDDEN",
+ "subCode": "FORBIDDEN",
+ "userFriendlyMessage": "You do not have permission to perform this action.",
+ },
+ "message": "An application token can only target its own application",
+ "name": "ForbiddenError",
+}
+`;
+
+exports[`Application variable access across applications should fail with a user-bound application token should refuse to update another application variable 1`] = `
+{
+ "extensions": {
+ "code": "FORBIDDEN",
+ "subCode": "FORBIDDEN",
+ "userFriendlyMessage": "You do not have permission to perform this action.",
+ },
+ "message": "An application token can only target its own application",
+ "name": "ForbiddenError",
+}
+`;
+
+exports[`Application variable access across applications should fail with an application token without user binding should refuse to read another application by id 1`] = `
+{
+ "extensions": {
+ "code": "FORBIDDEN",
+ "subCode": "FORBIDDEN",
+ "userFriendlyMessage": "You do not have permission to perform this action.",
+ },
+ "message": "An application token can only target its own application",
+ "name": "ForbiddenError",
+}
+`;
+
+exports[`Application variable access across applications should fail with an application token without user binding should refuse to read another application by universal identifier 1`] = `
+{
+ "extensions": {
+ "code": "FORBIDDEN",
+ "subCode": "FORBIDDEN",
+ "userFriendlyMessage": "You do not have permission to perform this action.",
+ },
+ "message": "An application token can only target its own application",
+ "name": "ForbiddenError",
+}
+`;
+
+exports[`Application variable access across applications should fail with an application token without user binding should refuse to update another application variable 1`] = `
+{
+ "extensions": {
+ "code": "FORBIDDEN",
+ "subCode": "FORBIDDEN",
+ "userFriendlyMessage": "You do not have permission to perform this action.",
+ },
+ "message": "An application token can only target its own application",
+ "name": "ForbiddenError",
+}
+`;
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/__snapshots__/failing-application-variable-cross-workspace-access.integration-spec.ts.snap b/packages/twenty-server/test/integration/metadata/suites/application/__snapshots__/failing-application-variable-cross-workspace-access.integration-spec.ts.snap
new file mode 100644
index 00000000000..a4a89a51a2d
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/application/__snapshots__/failing-application-variable-cross-workspace-access.integration-spec.ts.snap
@@ -0,0 +1,13 @@
+// Jest Snapshot v1, https://goo.gl/fbAQLP
+
+exports[`Application variable update across workspaces should fail should refuse to update a variable of an application installed in another workspace 1`] = `
+{
+ "extensions": {
+ "code": "NOT_FOUND",
+ "subCode": "APPLICATION_VARIABLE_NOT_FOUND",
+ "userFriendlyMessage": "Application variable not found.",
+ },
+ "message": "Application variable with key OTHER_WORKSPACE_VARIABLE not found",
+ "name": "NotFoundError",
+}
+`;
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/failing-application-variable-cross-application-access.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/failing-application-variable-cross-application-access.integration-spec.ts
new file mode 100644
index 00000000000..da400cfc84c
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/application/failing-application-variable-cross-application-access.integration-spec.ts
@@ -0,0 +1,205 @@
+import { expectOneNotInternalServerErrorSnapshot } from 'test/integration/graphql/utils/expect-one-not-internal-server-error-snapshot.util';
+import { findManyApplications } from 'test/integration/graphql/utils/find-many-applications.util';
+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import { findOneApplication } from 'test/integration/metadata/suites/application/utils/find-one-application.util';
+import { generateApplicationToken } from 'test/integration/metadata/suites/application/utils/generate-application-token.util';
+import {
+ type ApplicationWithVariable,
+ setupApplicationWithVariable,
+} from 'test/integration/metadata/suites/application/utils/setup-application-with-variable.util';
+import { updateOneApplicationVariable } from 'test/integration/metadata/suites/application/utils/update-one-application-variable.util';
+import { generateApplicationTokenPair } from 'test/integration/utils/generate-application-token-pair.util';
+import {
+ type EachTestingContext,
+ eachTestingContextFilter,
+} from 'twenty-shared/testing';
+
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+
+type GlobalTestContext = {
+ callingApplication: ApplicationWithVariable;
+ otherApplication: ApplicationWithVariable;
+ userBoundToken: string;
+ unboundToken: string;
+};
+
+type TestContext = {
+ token: (globalContext: GlobalTestContext) => string;
+};
+
+const applicationTokenTestCases: EachTestingContext<TestContext>[] = [
+ {
+ title: 'with a user-bound application token',
+ context: { token: (globalContext) => globalContext.userBoundToken },
+ },
+ {
+ title: 'with an application token without user binding',
+ context: { token: (globalContext) => globalContext.unboundToken },
+ },
+];
+
+describe('Application variable access across applications should fail', () => {
+ let globalTestContext: GlobalTestContext;
+
+ beforeAll(async () => {
+ const callingApplication = await setupApplicationWithVariable({
+ name: 'Calling Application',
+ variableKey: 'CALLING_APPLICATION_VARIABLE',
+ });
+ const otherApplication = await setupApplicationWithVariable({
+ name: 'Other Application',
+ variableKey: 'OTHER_APPLICATION_VARIABLE',
+ });
+
+ const [{ data: userBoundTokenData }, unboundTokenPair] = await Promise.all([
+ generateApplicationToken({
+ applicationId: callingApplication.id,
+ expectToFail: false,
+ }),
+ generateApplicationTokenPair({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ applicationId: callingApplication.id,
+ }),
+ ]);
+
+ globalTestContext = {
+ callingApplication,
+ otherApplication,
+ userBoundToken:
+ userBoundTokenData.generateApplicationToken.applicationAccessToken
+ .token,
+ unboundToken: unboundTokenPair.applicationAccessToken.token,
+ };
+ }, 120000);
+
+ afterAll(async () => {
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier:
+ globalTestContext.callingApplication.universalIdentifier,
+ });
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier:
+ globalTestContext.otherApplication.universalIdentifier,
+ });
+ });
+
+ describe.each(eachTestingContextFilter(applicationTokenTestCases))(
+ '$title',
+ ({ context }) => {
+ it('should refuse to update another application variable', async () => {
+ const { otherApplication } = globalTestContext;
+
+ const { errors } = await updateOneApplicationVariable({
+ input: {
+ key: otherApplication.variableKey,
+ value: 'overwritten',
+ applicationId: otherApplication.id,
+ },
+ token: context.token(globalTestContext),
+ expectToFail: true,
+ });
+
+ expectOneNotInternalServerErrorSnapshot({ errors });
+
+ const { data } = await findOneApplication({
+ input: { id: otherApplication.id },
+ gqlFields: `
+ applicationVariables {
+ key
+ value
+ }
+ `,
+ expectToFail: false,
+ });
+
+ expect(data.findOneApplication.applicationVariables).toEqual([
+ { key: otherApplication.variableKey, value: 'initial' },
+ ]);
+ });
+
+ it('should refuse to read another application by id', async () => {
+ const { errors } = await findOneApplication({
+ input: { id: globalTestContext.otherApplication.id },
+ gqlFields: `
+ id
+ applicationVariables {
+ key
+ value
+ }
+ `,
+ token: context.token(globalTestContext),
+ expectToFail: true,
+ });
+
+ expectOneNotInternalServerErrorSnapshot({ errors });
+ });
+
+ it('should refuse to read another application by universal identifier', async () => {
+ const { errors } = await findOneApplication({
+ input: {
+ universalIdentifier:
+ globalTestContext.otherApplication.universalIdentifier,
+ },
+ token: context.token(globalTestContext),
+ expectToFail: true,
+ });
+
+ expectOneNotInternalServerErrorSnapshot({ errors });
+ });
+
+ it('should never resolve another application variables in a list', async () => {
+ const { data, errors } = await findManyApplications({
+ gqlFields: `
+ id
+ applicationVariables {
+ key
+ value
+ }
+ `,
+ accessToken: context.token(globalTestContext),
+ expectToFail: true,
+ });
+
+ expect(data).toBeNull();
+ expect(errors.map(({ extensions }) => extensions.code)).toContain(
+ 'FORBIDDEN',
+ );
+ });
+ },
+ );
+
+ it('should refuse two application identifiers from a session', async () => {
+ const { callingApplication, otherApplication } = globalTestContext;
+
+ const { errors } = await findOneApplication({
+ input: {
+ id: callingApplication.id,
+ universalIdentifier: otherApplication.universalIdentifier,
+ },
+ expectToFail: true,
+ });
+
+ expectOneNotInternalServerErrorSnapshot({ errors });
+ });
+
+ it('should require an application identifier from a session', async () => {
+ const { errors } = await findOneApplication({
+ input: {},
+ expectToFail: true,
+ });
+
+ expectOneNotInternalServerErrorSnapshot({ errors });
+ });
+
+ it('should require an application id from a session', async () => {
+ const { errors } = await updateOneApplicationVariable({
+ input: {
+ key: globalTestContext.callingApplication.variableKey,
+ value: 'from-session',
+ },
+ expectToFail: true,
+ });
+
+ expectOneNotInternalServerErrorSnapshot({ errors });
+ });
+});
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/failing-application-variable-cross-workspace-access.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/failing-application-variable-cross-workspace-access.integration-spec.ts
new file mode 100644
index 00000000000..01404631bcd
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/application/failing-application-variable-cross-workspace-access.integration-spec.ts
@@ -0,0 +1,85 @@
+import { expectOneNotInternalServerErrorSnapshot } from 'test/integration/graphql/utils/expect-one-not-internal-server-error-snapshot.util';
+import { updateOneApplicationVariable } from 'test/integration/metadata/suites/application/utils/update-one-application-variable.util';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { v4 as uuidv4 } from 'uuid';
+
+import { type PlaintextString } from 'src/engine/core-modules/secret-encryption/branded-strings/plaintext-string.type';
+import { type SecretEncryptionService } from 'src/engine/core-modules/secret-encryption/secret-encryption.service';
+import { SEED_YCOMBINATOR_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+
+const VARIABLE_KEY = 'OTHER_WORKSPACE_VARIABLE';
+
+// The harness only holds sessions of the Apple workspace, so the application
+// and its variable are inserted directly into the other seeded workspace.
+describe('Application variable update across workspaces should fail', () => {
+ let otherWorkspaceApplicationId: string;
+ let storedValue: string;
+
+ beforeAll(async () => {
+ const [{ id }] = await globalThis.testDataSource.query(
+ `INSERT INTO core."application"
+ ("universalIdentifier", "name", "sourcePath", "workspaceId")
+ VALUES ($1, $2, $3, $4)
+ RETURNING id`,
+ [
+ uuidv4(),
+ 'Other workspace application',
+ 'other-workspace-application',
+ SEED_YCOMBINATOR_WORKSPACE_ID,
+ ],
+ );
+
+ otherWorkspaceApplicationId = id;
+
+ storedValue = getAppProviderByClassName<SecretEncryptionService>(
+ 'SecretEncryptionService',
+ ).encryptVersioned('initial' as PlaintextString, {
+ workspaceId: SEED_YCOMBINATOR_WORKSPACE_ID,
+ });
+
+ await globalThis.testDataSource.query(
+ `INSERT INTO core."applicationVariable"
+ ("universalIdentifier", "key", "value", "applicationId", "workspaceId")
+ VALUES ($1, $2, $3, $4, $5)`,
+ [
+ uuidv4(),
+ VARIABLE_KEY,
+ storedValue,
+ otherWorkspaceApplicationId,
+ SEED_YCOMBINATOR_WORKSPACE_ID,
+ ],
+ );
+ });
+
+ afterAll(async () => {
+ await globalThis.testDataSource.query(
+ `DELETE FROM core."applicationVariable" WHERE "applicationId" = $1`,
+ [otherWorkspaceApplicationId],
+ );
+ await globalThis.testDataSource.query(
+ `DELETE FROM core."application" WHERE id = $1`,
+ [otherWorkspaceApplicationId],
+ );
+ });
+
+ it('should refuse to update a variable of an application installed in another workspace', async () => {
+ const { errors } = await updateOneApplicationVariable({
+ input: {
+ key: VARIABLE_KEY,
+ value: 'overwritten',
+ applicationId: otherWorkspaceApplicationId,
+ },
+ expectToFail: true,
+ });
+
+ expectOneNotInternalServerErrorSnapshot({ errors });
+
+ const [row] = await globalThis.testDataSource.query(
+ `SELECT "value" FROM core."applicationVariable"
+ WHERE "applicationId" = $1 AND "key" = $2`,
+ [otherWorkspaceApplicationId, VARIABLE_KEY],
+ );
+
+ expect(row.value).toBe(storedValue);
+ });
+});
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/successful-application-variable-own-application-access.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/successful-application-variable-own-application-access.integration-spec.ts
new file mode 100644
index 00000000000..89b6fd654c2
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/application/successful-application-variable-own-application-access.integration-spec.ts
@@ -0,0 +1,182 @@
+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import { findOneApplication } from 'test/integration/metadata/suites/application/utils/find-one-application.util';
+import { generateApplicationToken } from 'test/integration/metadata/suites/application/utils/generate-application-token.util';
+import {
+ type ApplicationWithVariable,
+ setupApplicationWithVariable,
+} from 'test/integration/metadata/suites/application/utils/setup-application-with-variable.util';
+import { updateOneApplicationVariable } from 'test/integration/metadata/suites/application/utils/update-one-application-variable.util';
+import { generateApplicationTokenPair } from 'test/integration/utils/generate-application-token-pair.util';
+import {
+ type EachTestingContext,
+ eachTestingContextFilter,
+} from 'twenty-shared/testing';
+
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+
+type GlobalTestContext = {
+ application: ApplicationWithVariable;
+ otherApplication: ApplicationWithVariable;
+ userBoundToken: string;
+ unboundToken: string;
+};
+
+type TestContext = {
+ token: (globalContext: GlobalTestContext) => string;
+};
+
+const APPLICATION_VARIABLES_GQL_FIELDS = `
+ id
+ applicationVariables {
+ key
+ value
+ }
+`;
+
+const applicationTokenTestCases: EachTestingContext<TestContext>[] = [
+ {
+ title: 'with a user-bound application token',
+ context: { token: (globalContext) => globalContext.userBoundToken },
+ },
+ {
+ title: 'with an application token without user binding',
+ context: { token: (globalContext) => globalContext.unboundToken },
+ },
+];
+
+describe('Application variable access to the own application should succeed', () => {
+ let globalTestContext: GlobalTestContext;
+
+ beforeAll(async () => {
+ const application = await setupApplicationWithVariable({
+ name: 'Own Application',
+ variableKey: 'OWN_APPLICATION_VARIABLE',
+ });
+ const otherApplication = await setupApplicationWithVariable({
+ name: 'Other Application',
+ variableKey: 'OTHER_APPLICATION_VARIABLE',
+ });
+
+ const [{ data: userBoundTokenData }, unboundTokenPair] = await Promise.all([
+ generateApplicationToken({
+ applicationId: application.id,
+ expectToFail: false,
+ }),
+ generateApplicationTokenPair({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ applicationId: application.id,
+ }),
+ ]);
+
+ globalTestContext = {
+ application,
+ otherApplication,
+ userBoundToken:
+ userBoundTokenData.generateApplicationToken.applicationAccessToken
+ .token,
+ unboundToken: unboundTokenPair.applicationAccessToken.token,
+ };
+ }, 120000);
+
+ afterAll(async () => {
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier:
+ globalTestContext.application.universalIdentifier,
+ });
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier:
+ globalTestContext.otherApplication.universalIdentifier,
+ });
+ });
+
+ describe.each(eachTestingContextFilter(applicationTokenTestCases))(
+ '$title',
+ ({ context }) => {
+ it('should update and read the own variables without an application id', async () => {
+ const { application } = globalTestContext;
+ const token = context.token(globalTestContext);
+
+ const { data: updateData } = await updateOneApplicationVariable({
+ input: { key: application.variableKey, value: 'inferred' },
+ token,
+ expectToFail: false,
+ });
+
+ expect(updateData.updateOneApplicationVariable).toBe(true);
+
+ const { data } = await findOneApplication({
+ input: {},
+ gqlFields: APPLICATION_VARIABLES_GQL_FIELDS,
+ token,
+ expectToFail: false,
+ });
+
+ expect(data.findOneApplication).toEqual({
+ id: application.id,
+ applicationVariables: [
+ { key: application.variableKey, value: 'inferred' },
+ ],
+ });
+ });
+
+ it('should keep accepting the own application id, as published apps send it', async () => {
+ const { application } = globalTestContext;
+ const token = context.token(globalTestContext);
+
+ const { data: updateData } = await updateOneApplicationVariable({
+ input: {
+ key: application.variableKey,
+ value: 'explicit',
+ applicationId: application.id,
+ },
+ token,
+ expectToFail: false,
+ });
+
+ expect(updateData.updateOneApplicationVariable).toBe(true);
+
+ const { data } = await findOneApplication({
+ input: { id: application.id },
+ gqlFields: APPLICATION_VARIABLES_GQL_FIELDS,
+ token,
+ expectToFail: false,
+ });
+
+ expect(data.findOneApplication).toEqual({
+ id: application.id,
+ applicationVariables: [
+ { key: application.variableKey, value: 'explicit' },
+ ],
+ });
+ });
+ },
+ );
+
+ it('should let a session edit and read any chosen application', async () => {
+ const { otherApplication } = globalTestContext;
+
+ const { data: updateData } = await updateOneApplicationVariable({
+ input: {
+ key: otherApplication.variableKey,
+ value: 'from-session',
+ applicationId: otherApplication.id,
+ },
+ expectToFail: false,
+ });
+
+ expect(updateData.updateOneApplicationVariable).toBe(true);
+
+ const { data } = await findOneApplication({
+ input: { id: otherApplication.id },
+ gqlFields: APPLICATION_VARIABLES_GQL_FIELDS,
+ expectToFail: false,
+ });
+
+ expect(data.findOneApplication).toEqual({
+ id: otherApplication.id,
+ applicationVariables: [
+ { key: otherApplication.variableKey, value: 'from-session' },
+ ],
+ });
+ });
+});
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/utils/find-one-application-query-factory.util.ts b/packages/twenty-server/test/integration/metadata/suites/application/utils/find-one-application-query-factory.util.ts
new file mode 100644
index 00000000000..d7ab0ecb820
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/application/utils/find-one-application-query-factory.util.ts
@@ -0,0 +1,29 @@
+import gql from 'graphql-tag';
+import { type PerformMetadataQueryParams } from 'test/integration/metadata/types/perform-metadata-query.type';
+
+export type FindOneApplicationFactoryInput = {
+ id?: string;
+ universalIdentifier?: string;
+};
+
+const DEFAULT_APPLICATION_GQL_FIELDS = `
+ id
+ universalIdentifier
+`;
+
+export const findOneApplicationQueryFactory = ({
+ input,
+ gqlFields = DEFAULT_APPLICATION_GQL_FIELDS,
+}: PerformMetadataQueryParams<FindOneApplicationFactoryInput>) => ({
+ query: gql`
+ query FindOneApplication($id: UUID, $universalIdentifier: UUID) {
+ findOneApplication(id: $id, universalIdentifier: $universalIdentifier) {
+ ${gqlFields}
+ }
+ }
+ `,
+ variables: {
+ id: input.id,
+ universalIdentifier: input.universalIdentifier,
+ },
+});
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/utils/find-one-application.util.ts b/packages/twenty-server/test/integration/metadata/suites/application/utils/find-one-application.util.ts
new file mode 100644
index 00000000000..d1bef701a45
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/application/utils/find-one-application.util.ts
@@ -0,0 +1,43 @@
+import {
+ type FindOneApplicationFactoryInput,
+ findOneApplicationQueryFactory,
+} from 'test/integration/metadata/suites/application/utils/find-one-application-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 ApplicationDTO } from 'src/engine/core-modules/application/dtos/application.dto';
+
+export const findOneApplication = async ({
+ input,
+ gqlFields,
+ expectToFail = false,
+ token,
+}: PerformMetadataQueryParams<FindOneApplicationFactoryInput>): CommonResponseBody<{
+ findOneApplication: ApplicationDTO;
+}> => {
+ const graphqlOperation = findOneApplicationQueryFactory({
+ input,
+ gqlFields,
+ });
+
+ const response = await makeMetadataAPIRequest(graphqlOperation, token);
+
+ if (expectToFail === true) {
+ warnIfNoErrorButExpectedToFail({
+ response,
+ errorMessage: 'Finding application should have failed but did not',
+ });
+ }
+
+ if (expectToFail === false) {
+ warnIfErrorButNotExpectedToFail({
+ response,
+ errorMessage: 'Finding application 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
new file mode 100644
index 00000000000..5b6c05651b6
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/application/utils/setup-application-with-variable.util.ts
@@ -0,0 +1,77 @@
+import { buildBaseManifest } from 'test/integration/metadata/suites/application/utils/build-base-manifest.util';
+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 { SystemPermissionFlag } from 'twenty-shared/constants';
+import { v4 as uuidv4 } from 'uuid';
+
+export type ApplicationWithVariable = {
+ id: string;
+ universalIdentifier: string;
+ variableKey: string;
+};
+
+// Syncs an application whose default role holds APPLICATIONS, as the official
+// apps with a settings component do, and declares one non-secret variable.
+export const setupApplicationWithVariable = async ({
+ name,
+ variableKey,
+}: {
+ name: string;
+ variableKey: string;
+}): Promise<ApplicationWithVariable> => {
+ const applicationUniversalIdentifier = uuidv4();
+ const roleUniversalIdentifier = uuidv4();
+
+ await setupApplicationForSync({
+ applicationUniversalIdentifier,
+ name,
+ description: `${name} for application variable access tests`,
+ sourcePath: `test-${applicationUniversalIdentifier}`,
+ });
+
+ await syncApplication({
+ manifest: buildBaseManifest({
+ appId: applicationUniversalIdentifier,
+ roleId: roleUniversalIdentifier,
+ overrides: {
+ application: {
+ universalIdentifier: applicationUniversalIdentifier,
+ defaultRoleUniversalIdentifier: roleUniversalIdentifier,
+ displayName: name,
+ description: `${name} for application variable access tests`,
+ applicationVariables: {
+ [variableKey]: {
+ universalIdentifier: uuidv4(),
+ value: 'initial',
+ },
+ },
+ packageJsonChecksum: null,
+ yarnLockChecksum: null,
+ },
+ roles: [
+ {
+ universalIdentifier: roleUniversalIdentifier,
+ label: `${name} role`,
+ description: 'Manages applications',
+ permissionFlagUniversalIdentifiers: [
+ SystemPermissionFlag.APPLICATIONS,
+ ],
+ },
+ ],
+ },
+ }),
+ expectToFail: false,
+ });
+
+ const { data } = await findOneApplication({
+ input: { universalIdentifier: applicationUniversalIdentifier },
+ expectToFail: false,
+ });
+
+ return {
+ id: data.findOneApplication.id,
+ universalIdentifier: applicationUniversalIdentifier,
+ variableKey,
+ };
+};
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/utils/update-one-application-variable-query-factory.util.ts b/packages/twenty-server/test/integration/metadata/suites/application/utils/update-one-application-variable-query-factory.util.ts
new file mode 100644
index 00000000000..e2f605b17b3
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/application/utils/update-one-application-variable-query-factory.util.ts
@@ -0,0 +1,51 @@
+import gql from 'graphql-tag';
+import { type PerformMetadataQueryParams } from 'test/integration/metadata/types/perform-metadata-query.type';
+import { isDefined } from 'twenty-shared/utils';
+
+export type UpdateOneApplicationVariableFactoryInput = {
+ key: string;
+ value: string;
+ applicationId?: string;
+};
+
+// The argument is left out of the document when the caller does not name an
+// application, so the request exercises the inferred target rather than an
+// explicit null.
+export const updateOneApplicationVariableQueryFactory = ({
+ input,
+}: PerformMetadataQueryParams<UpdateOneApplicationVariableFactoryInput>) =>
+ isDefined(input.applicationId)
+ ? {
+ query: gql`
+ mutation UpdateOneApplicationVariable(
+ $key: String!
+ $value: String!
+ $applicationId: UUID!
+ ) {
+ updateOneApplicationVariable(
+ key: $key
+ value: $value
+ applicationId: $applicationId
+ )
+ }
+ `,
+ variables: {
+ key: input.key,
+ value: input.value,
+ applicationId: input.applicationId,
+ },
+ }
+ : {
+ query: gql`
+ mutation UpdateOneApplicationVariable(
+ $key: String!
+ $value: String!
+ ) {
+ updateOneApplicationVariable(key: $key, value: $value)
+ }
+ `,
+ variables: {
+ key: input.key,
+ value: input.value,
+ },
+ };
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/utils/update-one-application-variable.util.ts b/packages/twenty-server/test/integration/metadata/suites/application/utils/update-one-application-variable.util.ts
new file mode 100644
index 00000000000..41a0e6cc352
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/application/utils/update-one-application-variable.util.ts
@@ -0,0 +1,38 @@
+import {
+ type UpdateOneApplicationVariableFactoryInput,
+ updateOneApplicationVariableQueryFactory,
+} from 'test/integration/metadata/suites/application/utils/update-one-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 updateOneApplicationVariable = async ({
+ input,
+ expectToFail = false,
+ token,
+}: PerformMetadataQueryParams<UpdateOneApplicationVariableFactoryInput>): CommonResponseBody<{
+ updateOneApplicationVariable: boolean;
+}> => {
+ const graphqlOperation = updateOneApplicationVariableQueryFactory({ input });
+
+ const response = await makeMetadataAPIRequest(graphqlOperation, token);
+
+ if (expectToFail === true) {
+ warnIfNoErrorButExpectedToFail({
+ response,
+ errorMessage:
+ 'Updating application variable should have failed but did not',
+ });
+ }
+
+ if (expectToFail === false) {
+ warnIfErrorButNotExpectedToFail({
+ response,
+ errorMessage: 'Updating application variable has failed but should not',
+ });
+ }
+
+ return { data: response.body.data, errors: response.body.errors };
+};