The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
feat: private workflows on the core schema (#26243)
Félix Malfait84b446a29ae7
diff --git a/packages/twenty-front/src/generated/graphql.ts b/packages/twenty-front/src/generated/graphql.tsindex 19a6621a3f1..71d1b3c1856 100644--- a/packages/twenty-front/src/generated/graphql.ts+++ b/packages/twenty-front/src/generated/graphql.ts@@ -61,6 +61,7 @@ export type CoreWorkflowConnection = {export type CoreWorkflowDto = {__typename?: 'CoreWorkflowDTO';applicationId?: Maybe<Scalars['UUID']['output']>;+ canChangeVisibility: Scalars['Boolean']['output'];createdAt: Scalars['String']['output'];id: Scalars['UUID']['output'];lastPublishedCoreWorkflowVersionId?: Maybe<Scalars['UUID']['output']>;@@ -68,6 +69,7 @@ export type CoreWorkflowDto = {name?: Maybe<Scalars['String']['output']>;statuses: Array<CoreWorkflowStatus>;updatedAt: Scalars['String']['output'];+ visibility: WorkflowVisibility;workspaceWorkflowId?: Maybe<Scalars['UUID']['output']>;};@@ -171,6 +173,7 @@ export type CoreWorkflowsWithCurrentVersionsInput = {export type CreateCoreWorkflowInput = {name?: InputMaybe<Scalars['String']['input']>;+ visibility?: InputMaybe<WorkflowVisibility>;};export type CreateCoreWorkflowVersionEdgeInput = {@@ -450,6 +453,7 @@ export type Mutation = {updateCoreWorkflowVersionPositions: Scalars['Boolean']['output'];updateCoreWorkflowVersionStep: WorkflowAction;updateCoreWorkflowVersionTrigger: WorkflowVersionTrigger;+ updateCoreWorkflowVisibility?: Maybe<CoreWorkflowDto>;updateWorkflowRunStep: WorkflowAction;updateWorkflowVersionPositions: Scalars['Boolean']['output'];updateWorkflowVersionStep: WorkflowAction;@@ -629,6 +633,11 @@ export type MutationUpdateCoreWorkflowVersionTriggerArgs = {};+export type MutationUpdateCoreWorkflowVisibilityArgs = {+ input: UpdateCoreWorkflowVisibilityInput;+};++export type MutationUpdateWorkflowRunStepArgs = {input: UpdateWorkflowRunStepInput;};@@ -1024,6 +1033,11 @@ export type UpdateCoreWorkflowVersionTriggerInput = {trigger: Scalars['JSON']['input'];};+export type UpdateCoreWorkflowVisibilityInput = {+ coreWorkflowId: Scalars['UUID']['input'];+ visibility: WorkflowVisibility;+};+export type UpdateWorkflowRunStepInput = {/** Step to update in JSON format */step: Scalars['JSON']['input'];@@ -1150,6 +1164,11 @@ export type WorkflowVersionTrigger = {trigger?: Maybe<Scalars['JSON']['output']>;};+export enum WorkflowVisibility {+ PRIVATE = 'PRIVATE',+ WORKSPACE = 'WORKSPACE'+}+export type TimelineCalendarEventCallRecordingFragmentFragment = { __typename?: 'TimelineCalendarEventCallRecording', id: any, status: CallRecordingStatus, applicationId?: any | null };export type TimelineCalendarEventFragmentFragment = { __typename?: 'TimelineCalendarEvent', id: any, title: string, description: string, location: string, startsAt: string, endsAt: string, isFullDay: boolean, visibility: CalendarChannelVisibility, participants: Array<{ __typename?: 'TimelineCalendarEventParticipant', personId?: any | null, workspaceMemberId?: any | null, firstName: string, lastName: string, displayName: string, avatarUrl: string, handle: string }>, callRecordings: Array<{ __typename?: 'TimelineCalendarEventCallRecording', id: any, status: CallRecordingStatus, applicationId?: any | null }> };@@ -1315,6 +1334,13 @@ export type UpdateCoreWorkflowVersionTriggerMutationVariables = Exact<{export type UpdateCoreWorkflowVersionTriggerMutation = { __typename?: 'Mutation', updateWorkflowVersionTrigger: { __typename?: 'WorkflowVersionTrigger', trigger?: any | null } };+export type UpdateCoreWorkflowVisibilityMutationVariables = Exact<{+ input: UpdateCoreWorkflowVisibilityInput;+}>;+++export type UpdateCoreWorkflowVisibilityMutation = { __typename?: 'Mutation', updateCoreWorkflowVisibility?: { __typename?: 'CoreWorkflowDTO', id: any, visibility: WorkflowVisibility, canChangeVisibility: boolean, updatedAt: string } | null };+export type ValidateCoreWorkflowVersionMutationVariables = Exact<{coreWorkflowVersionId: Scalars['UUID']['input'];}>;@@ -1327,7 +1353,7 @@ export type GetCoreWorkflowQueryVariables = Exact<{}>;-export type GetCoreWorkflowQuery = { __typename?: 'Query', coreWorkflow?: { __typename?: 'CoreWorkflowDTO', id: any, name?: string | null, statuses: Array<CoreWorkflowStatus>, lastPublishedCoreWorkflowVersionId?: any | null, workspaceWorkflowId?: any | null, createdAt: string, updatedAt: string } | null };+export type GetCoreWorkflowQuery = { __typename?: 'Query', coreWorkflow?: { __typename?: 'CoreWorkflowDTO', id: any, name?: string | null, statuses: Array<CoreWorkflowStatus>, lastPublishedCoreWorkflowVersionId?: any | null, workspaceWorkflowId?: any | null, visibility: WorkflowVisibility, canChangeVisibility: boolean, createdAt: string, updatedAt: string } | null };export type GetCoreWorkflowLegacyMappingQueryVariables = Exact<{workspaceWorkflowId: Scalars['UUID']['input'];@@ -1352,7 +1378,7 @@ export type GetCoreWorkflowsQueryVariables = Exact<{}>;-export type GetCoreWorkflowsQuery = { __typename?: 'Query', coreWorkflows: { __typename?: 'CoreWorkflowConnection', totalCount: number, edges: Array<{ __typename?: 'CoreWorkflowEdge', cursor: string, node: { __typename?: 'CoreWorkflowDTO', id: any, name?: string | null, statuses: Array<CoreWorkflowStatus>, workspaceWorkflowId?: any | null, updatedAt: string } }>, pageInfo: { __typename?: 'CoreWorkflowPageInfo', endCursor?: string | null, hasNextPage: boolean } } };+export type GetCoreWorkflowsQuery = { __typename?: 'Query', coreWorkflows: { __typename?: 'CoreWorkflowConnection', totalCount: number, edges: Array<{ __typename?: 'CoreWorkflowEdge', cursor: string, node: { __typename?: 'CoreWorkflowDTO', id: any, name?: string | null, statuses: Array<CoreWorkflowStatus>, workspaceWorkflowId?: any | null, visibility: WorkflowVisibility, canChangeVisibility: boolean, updatedAt: string } }>, pageInfo: { __typename?: 'CoreWorkflowPageInfo', endCursor?: string | null, hasNextPage: boolean } } };export type GetCoreWorkflowsWithCurrentVersionsQueryVariables = Exact<{input: CoreWorkflowsWithCurrentVersionsInput;@@ -1552,11 +1578,12 @@ export const UpdateCoreWorkflowDocument = {"kind":"Document","definitions":[{"kiexport const UpdateCoreWorkflowVersionPositionsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateCoreWorkflowVersionPositions"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateCoreWorkflowVersionPositionsInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"updateWorkflowVersionPositions"},"name":{"kind":"Name","value":"updateCoreWorkflowVersionPositions"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}]}]}}]} as unknown as DocumentNode<UpdateCoreWorkflowVersionPositionsMutation, UpdateCoreWorkflowVersionPositionsMutationVariables>;export const UpdateCoreWorkflowVersionStepDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateCoreWorkflowVersionStep"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateCoreWorkflowVersionStepInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"updateWorkflowVersionStep"},"name":{"kind":"Name","value":"updateCoreWorkflowVersionStep"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"settings"}},{"kind":"Field","name":{"kind":"Name","value":"valid"}},{"kind":"Field","name":{"kind":"Name","value":"nextStepIds"}},{"kind":"Field","name":{"kind":"Name","value":"position"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"x"}},{"kind":"Field","name":{"kind":"Name","value":"y"}}]}}]}}]}}]} as unknown as DocumentNode<UpdateCoreWorkflowVersionStepMutation, UpdateCoreWorkflowVersionStepMutationVariables>;export const UpdateCoreWorkflowVersionTriggerDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateCoreWorkflowVersionTrigger"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateCoreWorkflowVersionTriggerInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"updateWorkflowVersionTrigger"},"name":{"kind":"Name","value":"updateCoreWorkflowVersionTrigger"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"trigger"}}]}}]}}]} as unknown as DocumentNode<UpdateCoreWorkflowVersionTriggerMutation, UpdateCoreWorkflowVersionTriggerMutationVariables>;+export const UpdateCoreWorkflowVisibilityDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateCoreWorkflowVisibility"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateCoreWorkflowVisibilityInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateCoreWorkflowVisibility"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"visibility"}},{"kind":"Field","name":{"kind":"Name","value":"canChangeVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<UpdateCoreWorkflowVisibilityMutation, UpdateCoreWorkflowVisibilityMutationVariables>;export const ValidateCoreWorkflowVersionDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"ValidateCoreWorkflowVersion"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"coreWorkflowVersionId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"validateCoreWorkflowVersion"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"coreWorkflowVersionId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"coreWorkflowVersionId"}}}]}]}}]} as unknown as DocumentNode<ValidateCoreWorkflowVersionMutation, ValidateCoreWorkflowVersionMutationVariables>;-export const GetCoreWorkflowDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetCoreWorkflow"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"coreWorkflowId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"coreWorkflow"},"name":{"kind":"Name","value":"coreWorkflowById"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"coreWorkflowId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"coreWorkflowId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"statuses"}},{"kind":"Field","name":{"kind":"Name","value":"lastPublishedCoreWorkflowVersionId"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceWorkflowId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<GetCoreWorkflowQuery, GetCoreWorkflowQueryVariables>;+export const GetCoreWorkflowDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetCoreWorkflow"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"coreWorkflowId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"coreWorkflow"},"name":{"kind":"Name","value":"coreWorkflowById"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"coreWorkflowId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"coreWorkflowId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"statuses"}},{"kind":"Field","name":{"kind":"Name","value":"lastPublishedCoreWorkflowVersionId"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceWorkflowId"}},{"kind":"Field","name":{"kind":"Name","value":"visibility"}},{"kind":"Field","name":{"kind":"Name","value":"canChangeVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<GetCoreWorkflowQuery, GetCoreWorkflowQueryVariables>;export const GetCoreWorkflowLegacyMappingDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetCoreWorkflowLegacyMapping"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceWorkflowId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"coreWorkflow"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workspaceWorkflowId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceWorkflowId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}}]}}]} as unknown as DocumentNode<GetCoreWorkflowLegacyMappingQuery, GetCoreWorkflowLegacyMappingQueryVariables>;export const GetCoreWorkflowVersionLegacyMappingDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetCoreWorkflowVersionLegacyMapping"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceWorkflowVersionId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"coreWorkflowVersion"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workspaceWorkflowVersionId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceWorkflowVersionId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"coreWorkflowId"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceWorkflowVersionId"}}]}}]}}]} as unknown as DocumentNode<GetCoreWorkflowVersionLegacyMappingQuery, GetCoreWorkflowVersionLegacyMappingQueryVariables>;-export const GetCoreWorkflowsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetCoreWorkflows"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"first"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"after"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"orderBy"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"CoreWorkflowOrderByField"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"orderByDirection"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"CoreWorkflowOrderByDirection"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"filter"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"CoreWorkflowFilterInput"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"coreWorkflows"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"first"},"value":{"kind":"Variable","name":{"kind":"Name","value":"first"}}},{"kind":"Argument","name":{"kind":"Name","value":"after"},"value":{"kind":"Variable","name":{"kind":"Name","value":"after"}}},{"kind":"Argument","name":{"kind":"Name","value":"orderBy"},"value":{"kind":"Variable","name":{"kind":"Name","value":"orderBy"}}},{"kind":"Argument","name":{"kind":"Name","value":"orderByDirection"},"value":{"kind":"Variable","name":{"kind":"Name","value":"orderByDirection"}}},{"kind":"Argument","name":{"kind":"Name","value":"filter"},"value":{"kind":"Variable","name":{"kind":"Name","value":"filter"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"edges"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"node"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"statuses"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceWorkflowId"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"cursor"}}]}},{"kind":"Field","name":{"kind":"Name","value":"pageInfo"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"endCursor"}},{"kind":"Field","name":{"kind":"Name","value":"hasNextPage"}}]}},{"kind":"Field","name":{"kind":"Name","value":"totalCount"}}]}}]}}]} as unknown as DocumentNode<GetCoreWorkflowsQuery, GetCoreWorkflowsQueryVariables>;+export const GetCoreWorkflowsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetCoreWorkflows"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"first"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"after"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"orderBy"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"CoreWorkflowOrderByField"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"orderByDirection"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"CoreWorkflowOrderByDirection"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"filter"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"CoreWorkflowFilterInput"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"coreWorkflows"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"first"},"value":{"kind":"Variable","name":{"kind":"Name","value":"first"}}},{"kind":"Argument","name":{"kind":"Name","value":"after"},"value":{"kind":"Variable","name":{"kind":"Name","value":"after"}}},{"kind":"Argument","name":{"kind":"Name","value":"orderBy"},"value":{"kind":"Variable","name":{"kind":"Name","value":"orderBy"}}},{"kind":"Argument","name":{"kind":"Name","value":"orderByDirection"},"value":{"kind":"Variable","name":{"kind":"Name","value":"orderByDirection"}}},{"kind":"Argument","name":{"kind":"Name","value":"filter"},"value":{"kind":"Variable","name":{"kind":"Name","value":"filter"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"edges"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"node"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"statuses"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceWorkflowId"}},{"kind":"Field","name":{"kind":"Name","value":"visibility"}},{"kind":"Field","name":{"kind":"Name","value":"canChangeVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"cursor"}}]}},{"kind":"Field","name":{"kind":"Name","value":"pageInfo"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"endCursor"}},{"kind":"Field","name":{"kind":"Name","value":"hasNextPage"}}]}},{"kind":"Field","name":{"kind":"Name","value":"totalCount"}}]}}]}}]} as unknown as DocumentNode<GetCoreWorkflowsQuery, GetCoreWorkflowsQueryVariables>;export const GetCoreWorkflowsWithCurrentVersionsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetCoreWorkflowsWithCurrentVersions"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"CoreWorkflowsWithCurrentVersionsInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"coreWorkflowsWithCurrentVersions"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"workflow"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"statuses"}},{"kind":"Field","name":{"kind":"Name","value":"lastPublishedCoreWorkflowVersionId"}}]}},{"kind":"Field","name":{"kind":"Name","value":"versions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"coreWorkflowId"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"currentVersion"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"coreWorkflowId"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"trigger"}},{"kind":"Field","name":{"kind":"Name","value":"steps"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]}}]} as unknown as DocumentNode<GetCoreWorkflowsWithCurrentVersionsQuery, GetCoreWorkflowsWithCurrentVersionsQueryVariables>;export const GetCoreWorkflowVersionDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetCoreWorkflowVersion"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"coreWorkflowVersionId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"coreWorkflowVersion"},"name":{"kind":"Name","value":"coreWorkflowVersionById"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"coreWorkflowVersionId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"coreWorkflowVersionId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceWorkflowVersionId"}},{"kind":"Field","name":{"kind":"Name","value":"coreWorkflowId"}},{"kind":"Field","name":{"kind":"Name","value":"trigger"}},{"kind":"Field","name":{"kind":"Name","value":"steps"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<GetCoreWorkflowVersionQuery, GetCoreWorkflowVersionQueryVariables>;export const GetCoreWorkflowVersionsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetCoreWorkflowVersions"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"coreWorkflowId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"coreWorkflowVersions"},"name":{"kind":"Name","value":"coreWorkflowVersionsByCoreWorkflowId"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"coreWorkflowId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"coreWorkflowId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"coreWorkflowId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<GetCoreWorkflowVersionsQuery, GetCoreWorkflowVersionsQueryVariables>;diff --git a/packages/twenty-front/src/modules/object-core/workflows/components/CoreWorkflowShowToolbar.tsx b/packages/twenty-front/src/modules/object-core/workflows/components/CoreWorkflowShowToolbar.tsxindex 154619b37b0..1c728e3a6f0 100644--- a/packages/twenty-front/src/modules/object-core/workflows/components/CoreWorkflowShowToolbar.tsx+++ b/packages/twenty-front/src/modules/object-core/workflows/components/CoreWorkflowShowToolbar.tsx@@ -6,9 +6,13 @@ import { Button } from 'twenty-ui/primitives/input';import { themeCssVariables } from 'twenty-ui/theme-constants';import { Select } from '@/ui/input/components/Select';+import { CoreWorkflowVisibilitySelect } from '@/object-core/workflows/components/CoreWorkflowVisibilitySelect';import { CoreWorkflowVersionRestoreButton } from '@/object-core/workflows/versions/components/CoreWorkflowVersionRestoreButton';import { CORE_WORKFLOW_VERSION_STATUS_TAG_PROPS } from '@/object-core/workflows/versions/constants/CoreWorkflowVersionStatusTagProps';-import { type GetCoreWorkflowVersionsQuery } from '~/generated/graphql';+import {+ type GetCoreWorkflowVersionsQuery,+ type WorkflowVisibility,+} from '~/generated/graphql';const StyledToolbar = styled.div`align-items: center;@@ -22,6 +26,8 @@ type CoreWorkflowShowToolbarProps = {coreWorkflowId: string;versions: GetCoreWorkflowVersionsQuery['coreWorkflowVersions'];selectedVersionId: string | undefined;+ visibility: WorkflowVisibility;+ canChangeVisibility: boolean;isHistoricalVersion: boolean;isValidating: boolean;onVersionChange: (versionId: string) => void;@@ -33,6 +39,8 @@ export const CoreWorkflowShowToolbar = ({coreWorkflowId,versions,selectedVersionId,+ visibility,+ canChangeVisibility,isHistoricalVersion,isValidating,onVersionChange,@@ -66,5 +74,10 @@ export const CoreWorkflowShowToolbar = ({<Button size="sm" startIcon={<IconRefresh />} onClick={onRefresh}>{t`Refresh`}</Button>+ <CoreWorkflowVisibilitySelect+ coreWorkflowId={coreWorkflowId}+ visibility={visibility}+ disabled={!canChangeVisibility}+ /></StyledToolbar>);diff --git a/packages/twenty-front/src/modules/object-core/workflows/components/CoreWorkflowVisibilityCell.tsx b/packages/twenty-front/src/modules/object-core/workflows/components/CoreWorkflowVisibilityCell.tsxnew file mode 100644index 00000000000..f3d85ecba3b--- /dev/null+++ b/packages/twenty-front/src/modules/object-core/workflows/components/CoreWorkflowVisibilityCell.tsx@@ -0,0 +1,28 @@+import { t } from '@lingui/core/macro';+import { isDefined } from 'twenty-shared/utils';+import { Tag } from 'twenty-ui/primitives/data-display';++import { type WorkflowVisibility } from '~/generated/graphql';+import { CORE_WORKFLOW_VISIBILITY_OPTIONS } from '@/object-core/workflows/constants/CoreWorkflowVisibilityOptions';++type CoreWorkflowVisibilityCellProps = {+ visibility: WorkflowVisibility;+};++export const CoreWorkflowVisibilityCell = ({+ visibility,+}: CoreWorkflowVisibilityCellProps) => {+ const visibilityOption = CORE_WORKFLOW_VISIBILITY_OPTIONS.find(+ ({ value }) => value === visibility,+ );++ if (!isDefined(visibilityOption)) {+ return null;+ }++ return (+ <Tag preventShrink color="gray" startIcon={<visibilityOption.Icon />}>+ {t(visibilityOption.label)}+ </Tag>+ );+};diff --git a/packages/twenty-front/src/modules/object-core/workflows/components/CoreWorkflowVisibilitySelect.tsx b/packages/twenty-front/src/modules/object-core/workflows/components/CoreWorkflowVisibilitySelect.tsxnew file mode 100644index 00000000000..762826981e4--- /dev/null+++ b/packages/twenty-front/src/modules/object-core/workflows/components/CoreWorkflowVisibilitySelect.tsx@@ -0,0 +1,39 @@+import { t } from '@lingui/core/macro';++import { type WorkflowVisibility } from '~/generated/graphql';+import { CORE_WORKFLOW_VISIBILITY_OPTIONS } from '@/object-core/workflows/constants/CoreWorkflowVisibilityOptions';+import { useUpdateCoreWorkflowVisibility } from '@/object-core/workflows/hooks/useUpdateCoreWorkflowVisibility';+import { Select } from '@/ui/input/components/Select';++type CoreWorkflowVisibilitySelectProps = {+ coreWorkflowId: string;+ visibility: WorkflowVisibility;+ disabled?: boolean;+};++export const CoreWorkflowVisibilitySelect = ({+ coreWorkflowId,+ visibility,+ disabled = false,+}: CoreWorkflowVisibilitySelectProps) => {+ const { updateVisibility, isUpdatingVisibility } =+ useUpdateCoreWorkflowVisibility({ coreWorkflowId });++ return (+ <Select+ dropdownId={`core-workflow-visibility-${coreWorkflowId}`}+ aria-label={t`Visibility`}+ value={visibility}+ disabled={disabled || isUpdatingVisibility}+ showIconInControl+ showContextualTextInControl+ options={CORE_WORKFLOW_VISIBILITY_OPTIONS.map((option) => ({+ value: option.value,+ label: t(option.label),+ contextualText: t(option.contextualText),+ Icon: option.Icon,+ }))}+ onChange={updateVisibility}+ />+ );+};diff --git a/packages/twenty-front/src/modules/object-core/workflows/constants/CoreWorkflowVisibilityOptions.ts b/packages/twenty-front/src/modules/object-core/workflows/constants/CoreWorkflowVisibilityOptions.tsnew file mode 100644index 00000000000..d497a29c1c5--- /dev/null+++ b/packages/twenty-front/src/modules/object-core/workflows/constants/CoreWorkflowVisibilityOptions.ts@@ -0,0 +1,21 @@+import { msg } from '@lingui/core/macro';+import { IconCircle, IconCircleDashed } from 'twenty-ui/icon';++import { type CoreWorkflowVisibilityOption } from '@/object-core/workflows/types/CoreWorkflowVisibilityOption';+import { WorkflowVisibility } from '~/generated/graphql';++export const CORE_WORKFLOW_VISIBILITY_OPTIONS: CoreWorkflowVisibilityOption[] =+ [+ {+ value: WorkflowVisibility.WORKSPACE,+ label: msg`Workspace`,+ contextualText: msg`Everyone`,+ Icon: IconCircle,+ },+ {+ value: WorkflowVisibility.PRIVATE,+ label: msg`Private`,+ contextualText: msg`Only you`,+ Icon: IconCircleDashed,+ },+ ];diff --git a/packages/twenty-front/src/modules/object-core/workflows/constants/WorkflowCoreTableColumns.tsx b/packages/twenty-front/src/modules/object-core/workflows/constants/WorkflowCoreTableColumns.tsxindex 3f24e27a426..7972fb23172 100644--- a/packages/twenty-front/src/modules/object-core/workflows/constants/WorkflowCoreTableColumns.tsx+++ b/packages/twenty-front/src/modules/object-core/workflows/constants/WorkflowCoreTableColumns.tsx@@ -2,6 +2,7 @@ import { msg } from '@lingui/core/macro';import { CoreWorkflowNameCell } from '@/object-core/workflows/components/CoreWorkflowNameCell';import { CoreWorkflowStatusesCell } from '@/object-core/workflows/components/CoreWorkflowStatusesCell';+import { CoreWorkflowVisibilityCell } from '@/object-core/workflows/components/CoreWorkflowVisibilityCell';import { type CoreObjectTableColumn } from '@/object-core/types/CoreObjectTableColumn';import { DateTimeDisplay } from '@/ui/field/display/components/DateTimeDisplay';import { type CoreWorkflow } from '@/object-core/workflows/types/CoreWorkflow';@@ -27,6 +28,15 @@ export const WORKFLOW_CORE_TABLE_COLUMNS: CoreObjectTableColumn<CoreWorkflow>[]<CoreWorkflowStatusesCell statuses={workflow.statuses} />),},+ {+ fieldName: 'visibility',+ fieldLabel: msg`Visibility`,+ align: 'left',+ gridTrack: '140px',+ renderCell: (workflow) => (+ <CoreWorkflowVisibilityCell visibility={workflow.visibility} />+ ),+ },{fieldName: 'updatedAt',fieldLabel: msg`Last update`,diff --git a/packages/twenty-front/src/modules/object-core/workflows/graphql/mutations/updateCoreWorkflowVisibility.ts b/packages/twenty-front/src/modules/object-core/workflows/graphql/mutations/updateCoreWorkflowVisibility.tsnew file mode 100644index 00000000000..fe385073630--- /dev/null+++ b/packages/twenty-front/src/modules/object-core/workflows/graphql/mutations/updateCoreWorkflowVisibility.ts@@ -0,0 +1,14 @@+import { gql } from '@apollo/client';++export const UPDATE_CORE_WORKFLOW_VISIBILITY = gql`+ mutation UpdateCoreWorkflowVisibility(+ $input: UpdateCoreWorkflowVisibilityInput!+ ) {+ updateCoreWorkflowVisibility(input: $input) {+ id+ visibility+ canChangeVisibility+ updatedAt+ }+ }+`;diff --git a/packages/twenty-front/src/modules/object-core/workflows/graphql/queries/getCoreWorkflow.ts b/packages/twenty-front/src/modules/object-core/workflows/graphql/queries/getCoreWorkflow.tsindex 0d3c124e103..6ffad19b1cc 100644--- a/packages/twenty-front/src/modules/object-core/workflows/graphql/queries/getCoreWorkflow.ts+++ b/packages/twenty-front/src/modules/object-core/workflows/graphql/queries/getCoreWorkflow.ts@@ -8,6 +8,8 @@ export const GET_CORE_WORKFLOW = gql`statuseslastPublishedCoreWorkflowVersionIdworkspaceWorkflowId+ visibility+ canChangeVisibilitycreatedAtupdatedAt}diff --git a/packages/twenty-front/src/modules/object-core/workflows/graphql/queries/getCoreWorkflows.ts b/packages/twenty-front/src/modules/object-core/workflows/graphql/queries/getCoreWorkflows.tsindex 60117d2106b..ef2c72ec9da 100644--- a/packages/twenty-front/src/modules/object-core/workflows/graphql/queries/getCoreWorkflows.ts+++ b/packages/twenty-front/src/modules/object-core/workflows/graphql/queries/getCoreWorkflows.ts@@ -21,6 +21,8 @@ export const GET_CORE_WORKFLOWS = gql`namestatusesworkspaceWorkflowId+ visibility+ canChangeVisibilityupdatedAt}cursordiff --git a/packages/twenty-front/src/modules/object-core/workflows/hooks/useCoreWorkflowShowPageResource.ts b/packages/twenty-front/src/modules/object-core/workflows/hooks/useCoreWorkflowShowPageResource.tsindex 34c95a79286..ae5eed042df 100644--- a/packages/twenty-front/src/modules/object-core/workflows/hooks/useCoreWorkflowShowPageResource.ts+++ b/packages/twenty-front/src/modules/object-core/workflows/hooks/useCoreWorkflowShowPageResource.ts@@ -23,5 +23,5 @@ export const useCoreWorkflowShowPageResource = ({[data?.coreWorkflow],);- return { record, loading, error, refetch };+ return { record, coreWorkflow: data?.coreWorkflow, loading, error, refetch };};diff --git a/packages/twenty-front/src/modules/object-core/workflows/hooks/useUpdateCoreWorkflowVisibility.ts b/packages/twenty-front/src/modules/object-core/workflows/hooks/useUpdateCoreWorkflowVisibility.tsnew file mode 100644index 00000000000..ddeb2f06c9d--- /dev/null+++ b/packages/twenty-front/src/modules/object-core/workflows/hooks/useUpdateCoreWorkflowVisibility.ts@@ -0,0 +1,40 @@+import { useMutation } from '@apollo/client/react';+import { t } from '@lingui/core/macro';+import { useToast } from 'twenty-ui/primitives/feedback';++import { useApolloCoreClient } from '@/object-metadata/hooks/useApolloCoreClient';+import {+ UpdateCoreWorkflowVisibilityDocument,+ type WorkflowVisibility,+} from '~/generated/graphql';+import { logError } from '~/utils/logError';++export const useUpdateCoreWorkflowVisibility = ({+ coreWorkflowId,+}: {+ coreWorkflowId: string;+}) => {+ const client = useApolloCoreClient();+ const [updateVisibilityMutation, { loading: isUpdatingVisibility }] =+ useMutation(UpdateCoreWorkflowVisibilityDocument, { client });+ const { enqueueToast } = useToast();++ const updateVisibility = async (visibility: WorkflowVisibility) => {+ try {+ await updateVisibilityMutation({+ variables: { input: { coreWorkflowId, visibility } },+ });+ } catch (mutationError) {+ logError(mutationError);+ enqueueToast({+ variant: 'error',+ children:+ mutationError instanceof Error+ ? mutationError.message+ : t`Could not change who can see this workflow`,+ });+ }+ };++ return { updateVisibility, isUpdatingVisibility };+};diff --git a/packages/twenty-front/src/modules/object-core/workflows/types/CoreWorkflowVisibilityOption.ts b/packages/twenty-front/src/modules/object-core/workflows/types/CoreWorkflowVisibilityOption.tsnew file mode 100644index 00000000000..1260977c6f4--- /dev/null+++ b/packages/twenty-front/src/modules/object-core/workflows/types/CoreWorkflowVisibilityOption.ts@@ -0,0 +1,11 @@+import { type MessageDescriptor } from '@lingui/core';+import { type IconComponent } from 'twenty-ui/icon';++import { type WorkflowVisibility } from '~/generated/graphql';++export type CoreWorkflowVisibilityOption = {+ value: WorkflowVisibility;+ label: MessageDescriptor;+ contextualText: MessageDescriptor;+ Icon: IconComponent;+};diff --git a/packages/twenty-front/src/modules/object-core/workflows/utils/__tests__/buildWorkflowShowPageRecordFromCoreWorkflow.test.ts b/packages/twenty-front/src/modules/object-core/workflows/utils/__tests__/buildWorkflowShowPageRecordFromCoreWorkflow.test.tsindex 8518b05daa0..d18ff642994 100644--- a/packages/twenty-front/src/modules/object-core/workflows/utils/__tests__/buildWorkflowShowPageRecordFromCoreWorkflow.test.ts+++ b/packages/twenty-front/src/modules/object-core/workflows/utils/__tests__/buildWorkflowShowPageRecordFromCoreWorkflow.test.ts@@ -1,5 +1,5 @@import { buildWorkflowShowPageRecordFromCoreWorkflow } from '@/object-core/workflows/utils/buildWorkflowShowPageRecordFromCoreWorkflow';-import { CoreWorkflowStatus } from '~/generated/graphql';+import { CoreWorkflowStatus, WorkflowVisibility } from '~/generated/graphql';describe('buildWorkflowShowPageRecordFromCoreWorkflow', () => {const coreWorkflow = {@@ -9,6 +9,8 @@ describe('buildWorkflowShowPageRecordFromCoreWorkflow', () => {statuses: [CoreWorkflowStatus.ACTIVE],lastPublishedCoreWorkflowVersionId: 'published-version-id',workspaceWorkflowId: 'workspace-workflow-id',+ visibility: WorkflowVisibility.WORKSPACE,+ canChangeVisibility: true,createdAt: '2026-09-01T00:00:00.000Z',updatedAt: '2026-09-14T00:00:00.000Z',};diff --git a/packages/twenty-front/src/modules/object-core/workflows/versions/utils/__tests__/invalidateCoreWorkflowVersions.test.ts b/packages/twenty-front/src/modules/object-core/workflows/versions/utils/__tests__/invalidateCoreWorkflowVersions.test.tsindex fb66669ce9e..28aa61b6165 100644--- a/packages/twenty-front/src/modules/object-core/workflows/versions/utils/__tests__/invalidateCoreWorkflowVersions.test.ts+++ b/packages/twenty-front/src/modules/object-core/workflows/versions/utils/__tests__/invalidateCoreWorkflowVersions.test.ts@@ -27,6 +27,8 @@ describe('invalidateCoreWorkflowVersions', () => {statuses: ['DRAFT'],lastPublishedCoreWorkflowVersionId: null,workspaceWorkflowId: null,+ visibility: 'WORKSPACE',+ canChangeVisibility: true,createdAt: '2026-09-17T00:00:00Z',updatedAt: '2026-09-17T00:00:00Z',},diff --git a/packages/twenty-front/src/pages/object-core/WorkflowCoreShowPage.tsx b/packages/twenty-front/src/pages/object-core/WorkflowCoreShowPage.tsxindex 15cf09c840b..e87006b0544 100644--- a/packages/twenty-front/src/pages/object-core/WorkflowCoreShowPage.tsx+++ b/packages/twenty-front/src/pages/object-core/WorkflowCoreShowPage.tsx@@ -33,6 +33,7 @@ import { PageCardHeader } from '@/ui/layout/page/components/PageCardHeader';import { PageCardLayout } from '@/ui/layout/page/components/PageCardLayout';import { PageTitle } from '@/ui/utilities/page-title/components/PageTitle';import { useIsWorkflowCoreEnabled } from '@/workflow/hooks/useIsWorkflowCoreEnabled';+import { WorkflowVisibility } from '~/generated/graphql';import { getWorkflowCurrentVersion } from '@/workflow/utils/getWorkflowCurrentVersion';const StyledContainer = styled.div`@@ -49,9 +50,10 @@ const CoreWorkflowShowContent = ({}) => {const client = useApolloCoreClient();const { closeSidePanelMenu } = useSidePanelMenu();- const { record, loading, error } = useCoreWorkflowShowPageResource({- coreWorkflowId,- });+ const { record, coreWorkflow, loading, error } =+ useCoreWorkflowShowPageResource({+ coreWorkflowId,+ });const versions = useCoreWorkflowVersions(coreWorkflowId);const [searchParams, setSearchParams] = useSearchParams();const [editedName, setEditedName] = useState<string>();@@ -158,6 +160,10 @@ const CoreWorkflowShowContent = ({coreWorkflowId={coreWorkflowId}versions={versions.coreWorkflowVersions}selectedVersionId={selectedVersion?.id}+ visibility={+ coreWorkflow?.visibility ?? WorkflowVisibility.WORKSPACE+ }+ canChangeVisibility={coreWorkflow?.canChangeVisibility ?? false}isHistoricalVersion={isHistoricalVersion}isValidating={isValidating}onVersionChange={(versionId) => {diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-42/2-42-instance-command-fast-1789893300000-add-workflow-visibility.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-42/2-42-instance-command-fast-1789893300000-add-workflow-visibility.tsnew file mode 100644index 00000000000..764ea4c30d9--- /dev/null+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-42/2-42-instance-command-fast-1789893300000-add-workflow-visibility.ts@@ -0,0 +1,59 @@+import { type QueryRunner } from 'typeorm';++import { RegisteredInstanceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-instance-command.decorator';+import { type FastInstanceCommand } from 'src/engine/core-modules/upgrade/interfaces/fast-instance-command.interface';++// Existing workflows were authored before anyone could keep one to themselves,+// so they default to WORKSPACE: nobody loses sight of a workflow they had. They+// also have no owner, which is what lets the first member who makes one private+// claim it.+@RegisteredInstanceCommand('2.42.0', 1789893300000)+export class AddWorkflowVisibilityFastInstanceCommand+ implements FastInstanceCommand+{+ async up(queryRunner: QueryRunner): Promise<void> {+ await queryRunner.query(+ `ALTER TABLE "core"."workflow" ADD COLUMN IF NOT EXISTS "visibility" varchar NOT NULL DEFAULT 'WORKSPACE'`,+ );++ await queryRunner.query(+ `ALTER TABLE "core"."workflow" ADD COLUMN IF NOT EXISTS "createdByUserWorkspaceId" uuid NULL`,+ );++ await queryRunner.query(+ `DO $$+ BEGIN+ ALTER TABLE "core"."workflow"+ ADD CONSTRAINT "FK_WORKFLOW_CREATED_BY_USER_WORKSPACE"+ FOREIGN KEY ("createdByUserWorkspaceId")+ REFERENCES "core"."userWorkspace"("id") ON DELETE SET NULL;+ EXCEPTION+ WHEN duplicate_object THEN NULL;+ END $$`,+ );++ // The list query filters on both columns together for every reader, so the+ // index carries the visibility as well as the owner.+ await queryRunner.query(+ `CREATE INDEX IF NOT EXISTS "IDX_WORKFLOW_VISIBILITY_CREATED_BY" ON "core"."workflow" ("workspaceId", "visibility", "createdByUserWorkspaceId")`,+ );+ }++ async down(queryRunner: QueryRunner): Promise<void> {+ await queryRunner.query(+ `DROP INDEX IF EXISTS "core"."IDX_WORKFLOW_VISIBILITY_CREATED_BY"`,+ );++ await queryRunner.query(+ `ALTER TABLE "core"."workflow" DROP CONSTRAINT IF EXISTS "FK_WORKFLOW_CREATED_BY_USER_WORKSPACE"`,+ );++ await queryRunner.query(+ `ALTER TABLE "core"."workflow" DROP COLUMN IF EXISTS "createdByUserWorkspaceId"`,+ );++ await queryRunner.query(+ `ALTER TABLE "core"."workflow" DROP COLUMN IF EXISTS "visibility"`,+ );+ }+}diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-42/add-workflow-visibility-upgrade-command-name.constant.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-42/add-workflow-visibility-upgrade-command-name.constant.tsnew file mode 100644index 00000000000..a2e5dd113d8--- /dev/null+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-42/add-workflow-visibility-upgrade-command-name.constant.ts@@ -0,0 +1,5 @@+// Referenced by @WasIntroducedInUpgrade on the core workflow visibility+// columns so pre-2.42 upgrade steps don't SELECT them before this command+// creates them.+export const ADD_WORKFLOW_VISIBILITY_UPGRADE_COMMAND_NAME =+ '2.42.0_AddWorkflowVisibilityFastInstanceCommand_1789893300000';diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.tsindex 4fe92ef4aa5..0bcb87b299d 100644--- a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts@@ -196,6 +196,7 @@ import { AddAppMessageChannelTypeFastInstanceCommand } from 'src/database/commanimport { AddAppMessageChannelUniqueHandleFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-41/2-41-instance-command-fast-1789418882171-add-app-message-channel-unique-handle';import { AddWorkflowExecutionCompatibilityFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-42/2-42-instance-command-fast-1789719131000-add-workflow-execution-compatibility';import { CoreWorkflowCommandMenuItemsFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-42/2-42-instance-command-fast-1789730706712-core-workflow-command-menu-items';+import { AddWorkflowVisibilityFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-42/2-42-instance-command-fast-1789893300000-add-workflow-visibility';export const INSTANCE_COMMANDS = [AddViewFieldGroupIdIndexOnViewFieldFastInstanceCommand,@@ -391,6 +392,7 @@ export const INSTANCE_COMMANDS = [AddWorkspaceWorkflowVersionIdToWorkflowVersionFastInstanceCommand,AddWorkflowExecutionCompatibilityFastInstanceCommand,CoreWorkflowCommandMenuItemsFastInstanceCommand,+ AddWorkflowVisibilityFastInstanceCommand,AddReadabilityParentFieldsToObjectMetadataFastInstanceCommand,AddAppMessageChannelTypeFastInstanceCommand,AddAppMessageChannelUniqueHandleFastInstanceCommand,diff --git a/packages/twenty-server/src/engine/core-modules/workflow/core-workflow-access.module.ts b/packages/twenty-server/src/engine/core-modules/workflow/core-workflow-access.module.tsnew file mode 100644index 00000000000..55b693086b8--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/workflow/core-workflow-access.module.ts@@ -0,0 +1,20 @@+import { Module } from '@nestjs/common';+import { TypeOrmModule } from '@nestjs/typeorm';++import { WorkflowVersionEntity } from 'src/engine/core-modules/workflow/entities/workflow-version.entity';+import { WorkflowEntity } from 'src/engine/core-modules/workflow/entities/workflow.entity';+import { CoreWorkflowAccessService } from 'src/engine/core-modules/workflow/services/core-workflow-access.service';+import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/provide-workspace-scoped-repository';++// The rule is reached from the command menu as well as from the workflow API,+// and those two modules already depend on each other, so it lives on its own.+@Module({+ imports: [TypeOrmModule.forFeature([WorkflowEntity, WorkflowVersionEntity])],+ providers: [+ CoreWorkflowAccessService,+ provideWorkspaceScopedRepository(WorkflowEntity),+ provideWorkspaceScopedRepository(WorkflowVersionEntity),+ ],+ exports: [CoreWorkflowAccessService],+})+export class CoreWorkflowAccessModule {}diff --git a/packages/twenty-server/src/engine/core-modules/workflow/dtos/core-workflow.dto.ts b/packages/twenty-server/src/engine/core-modules/workflow/dtos/core-workflow.dto.tsindex 5810566c367..1854b0067a8 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/dtos/core-workflow.dto.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/dtos/core-workflow.dto.ts@@ -1,5 +1,7 @@import { Field, ObjectType, registerEnumType } from '@nestjs/graphql';+import { WorkflowVisibility } from 'twenty-shared/types';+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';import { WorkflowStatus } from 'src/modules/workflow/common/standard-objects/workflow.workspace-entity';@@ -7,6 +9,8 @@ registerEnumType(WorkflowStatus, {name: 'CoreWorkflowStatus',});+registerEnumType(WorkflowVisibility, { name: 'WorkflowVisibility' });+@ObjectType('CoreWorkflowDTO')export class CoreWorkflowDTO {@Field(() => UUIDScalarType)@@ -30,6 +34,14 @@ export class CoreWorkflowDTO {@Field(() => UUIDScalarType, { nullable: true })workspaceWorkflowId: string | null;+ @Field(() => WorkflowVisibility, { nullable: false })+ visibility: WorkflowVisibility;++ // the reader's own id never leaves the server; the client only needs to know+ // whether this reader is allowed to change who sees the workflow+ @Field(() => Boolean, { nullable: false })+ canChangeVisibility: boolean;+@Field(() => String)createdAt: string;diff --git a/packages/twenty-server/src/engine/core-modules/workflow/dtos/create-core-workflow.input.ts b/packages/twenty-server/src/engine/core-modules/workflow/dtos/create-core-workflow.input.tsindex 9020ac23c47..5d8dbcd7e37 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/dtos/create-core-workflow.input.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/dtos/create-core-workflow.input.ts@@ -1,6 +1,7 @@import { Field, InputType } from '@nestjs/graphql';-import { IsOptional, IsString } from 'class-validator';+import { IsEnum, IsOptional, IsString } from 'class-validator';+import { WorkflowVisibility } from 'twenty-shared/types';@InputType()export class CreateCoreWorkflowInput {@@ -8,4 +9,9 @@ export class CreateCoreWorkflowInput {@IsOptional()@IsString()name?: string;++ @Field(() => WorkflowVisibility, { nullable: true })+ @IsOptional()+ @IsEnum(WorkflowVisibility)+ visibility?: WorkflowVisibility;}diff --git a/packages/twenty-server/src/engine/core-modules/workflow/dtos/update-core-workflow-visibility.input.ts b/packages/twenty-server/src/engine/core-modules/workflow/dtos/update-core-workflow-visibility.input.tsnew file mode 100644index 00000000000..5f0cf7e8e47--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/workflow/dtos/update-core-workflow-visibility.input.ts@@ -0,0 +1,17 @@+import { Field, InputType } from '@nestjs/graphql';++import { IsEnum, IsUUID } from 'class-validator';+import { WorkflowVisibility } from 'twenty-shared/types';++import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';++@InputType()+export class UpdateCoreWorkflowVisibilityInput {+ @Field(() => UUIDScalarType, { nullable: false })+ @IsUUID()+ coreWorkflowId: string;++ @Field(() => WorkflowVisibility, { nullable: false })+ @IsEnum(WorkflowVisibility)+ visibility: WorkflowVisibility;+}diff --git a/packages/twenty-server/src/engine/core-modules/workflow/entities/workflow.entity.ts b/packages/twenty-server/src/engine/core-modules/workflow/entities/workflow.entity.tsindex 05c7788b9f6..596e2ccce23 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/entities/workflow.entity.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/entities/workflow.entity.ts@@ -3,13 +3,20 @@ import {CreateDateColumn,Entity,Index,+ JoinColumn,+ ManyToOne,PrimaryGeneratedColumn,+ type Relation,UpdateDateColumn,} from 'typeorm';+import { WorkflowVisibility } from 'twenty-shared/types';+import { CREATE_WORKFLOW_CORE_TABLE_UPGRADE_COMMAND_NAME } from 'src/database/commands/upgrade-version-command/2-20/create-workflow-core-table-upgrade-command-name.constant';import { ADD_WORKSPACE_WORKFLOW_ID_TO_WORKFLOW_UPGRADE_COMMAND_NAME } from 'src/database/commands/upgrade-version-command/2-41/add-workspace-workflow-id-to-workflow-upgrade-command-name.constant';import { ADD_CORE_VERSION_POINTERS_UPGRADE_COMMAND_NAME } from 'src/database/commands/upgrade-version-command/2-41/add-core-version-pointers-upgrade-command-name.constant';+import { ADD_WORKFLOW_VISIBILITY_UPGRADE_COMMAND_NAME } from 'src/database/commands/upgrade-version-command/2-42/add-workflow-visibility-upgrade-command-name.constant';+import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';import { WasIntroducedInUpgrade } from 'src/engine/core-modules/upgrade/decorators/was-introduced-in-upgrade.decorator';import { SyncableEntity } from 'src/engine/workspace-manager/types/syncable-entity.interface';@@ -19,6 +26,11 @@ import { SyncableEntity } from 'src/engine/workspace-manager/types/syncable-enti})@Index('IDX_WORKFLOW_WORKSPACE_ID', ['workspaceId'])@Index('IDX_WORKFLOW_APPLICATION_ID', ['applicationId'])+@Index('IDX_WORKFLOW_VISIBILITY_CREATED_BY', [+ 'workspaceId',+ 'visibility',+ 'createdByUserWorkspaceId',+])export class WorkflowEntity extends SyncableEntity {@PrimaryGeneratedColumn('uuid')id: string;@@ -42,6 +54,35 @@ export class WorkflowEntity extends SyncableEntity {@Column({ type: 'uuid', nullable: true })lastPublishedCoreWorkflowVersionId: string | null;+ // Enforced where ids are resolved rather than at each endpoint, so a workflow+ // private to someone else stops resolving at all and its versions and steps+ // are unreachable too. See CoreWorkflowIdResolutionService.+ @WasIntroducedInUpgrade({+ upgradeCommandName: ADD_WORKFLOW_VISIBILITY_UPGRADE_COMMAND_NAME,+ })+ @Column({+ type: 'varchar',+ nullable: false,+ default: WorkflowVisibility.WORKSPACE,+ })+ visibility: WorkflowVisibility;++ @WasIntroducedInUpgrade({+ upgradeCommandName: ADD_WORKFLOW_VISIBILITY_UPGRADE_COMMAND_NAME,+ })+ @Column({ type: 'uuid', nullable: true })+ createdByUserWorkspaceId: string | null;++ @ManyToOne(() => UserWorkspaceEntity, {+ onDelete: 'SET NULL',+ nullable: true,+ })+ @JoinColumn({+ name: 'createdByUserWorkspaceId',+ foreignKeyConstraintName: 'FK_WORKFLOW_CREATED_BY_USER_WORKSPACE',+ })+ createdBy: Relation<UserWorkspaceEntity> | null;+@CreateDateColumn({ type: 'timestamptz' })createdAt: Date;diff --git a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow-version-mutation.resolver.ts b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow-version-mutation.resolver.tsindex d246c822891..8bee85ca054 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow-version-mutation.resolver.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow-version-mutation.resolver.ts@@ -32,6 +32,8 @@ import { CoreWorkflowLifecycleWorkspaceService } from 'src/engine/core-modules/wimport { CoreWorkflowVersionMutationWorkspaceService } from 'src/engine/core-modules/workflow/services/core-workflow-version-mutation.workspace-service';import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';import { AuthUser } from 'src/engine/decorators/auth/auth-user.decorator';+import { CoreWorkflowAccessService } from 'src/engine/core-modules/workflow/services/core-workflow-access.service';+import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';import { UserAuthGuard } from 'src/engine/guards/user-auth.guard';@@ -64,18 +66,23 @@ export class CoreWorkflowVersionMutationResolver {private readonly coreWorkflowVersionMutationWorkspaceService: CoreWorkflowVersionMutationWorkspaceService,private readonly coreWorkflowLifecycleWorkspaceService: CoreWorkflowLifecycleWorkspaceService,private readonly coreWorkflowRunnerService: CoreWorkflowRunnerService,+ private readonly coreWorkflowAccessService: CoreWorkflowAccessService,private readonly workspaceOrmManager: WorkspaceOrmManager,) {}@Mutation(() => Boolean)async validateCoreWorkflowVersion(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@Args('coreWorkflowVersionId', { type: () => UUIDScalarType })coreWorkflowVersionId: string,): Promise<boolean> {return this.coreWorkflowLifecycleWorkspaceService.validateCoreWorkflowVersion({workspaceId,++ userWorkspaceId,coreWorkflowVersionId,},);@@ -84,12 +91,16 @@ export class CoreWorkflowVersionMutationResolver {@Mutation(() => Boolean)async activateCoreWorkflowVersion(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@Args('coreWorkflowVersionId', { type: () => UUIDScalarType })coreWorkflowVersionId: string,): Promise<boolean> {return this.coreWorkflowLifecycleWorkspaceService.activateCoreWorkflowVersion({workspaceId,++ userWorkspaceId,coreWorkflowVersionId,},);@@ -98,12 +109,16 @@ export class CoreWorkflowVersionMutationResolver {@Mutation(() => Boolean)async deactivateCoreWorkflowVersion(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@Args('coreWorkflowVersionId', { type: () => UUIDScalarType })coreWorkflowVersionId: string,): Promise<boolean> {return this.coreWorkflowLifecycleWorkspaceService.deactivateCoreWorkflowVersion({workspaceId,++ userWorkspaceId,coreWorkflowVersionId,},);@@ -113,6 +128,8 @@ export class CoreWorkflowVersionMutationResolver {async runCoreWorkflowVersion(@AuthUser() user: AuthContextUser,@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@Args('input'){coreWorkflowVersionId,@@ -133,6 +150,14 @@ export class CoreWorkflowVersionMutationResolver {});}, buildSystemAuthContext(workspaceId));+ await this.coreWorkflowAccessService.assertCoreWorkflowVersionsAreAccessibleOrThrow(+ {+ workspaceId,+ userWorkspaceId,+ coreWorkflowVersionIds: [coreWorkflowVersionId],+ },+ );+const { payload: triggerPayload, createdBy } =buildWorkflowRunTriggerContext({ workspaceMember, payload });@@ -148,6 +173,8 @@ export class CoreWorkflowVersionMutationResolver {@Mutation(() => CoreWorkflowVersionDTO)async createDraftFromCoreWorkflowVersion(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@Args('input'){coreWorkflowId,@@ -157,6 +184,8 @@ export class CoreWorkflowVersionMutationResolver {return this.coreWorkflowVersionMutationWorkspaceService.createDraftFromCoreWorkflowVersion({workspaceId,++ userWorkspaceId,coreWorkflowId,coreWorkflowVersionIdToCopy,},@@ -166,10 +195,14 @@ export class CoreWorkflowVersionMutationResolver {@Mutation(() => WorkflowVersionStepChangesDTO)async createCoreWorkflowVersionStep(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@Args('input') input: CreateCoreWorkflowVersionStepInput,): Promise<WorkflowVersionStepChangesDTO> {return this.coreWorkflowVersionMutationWorkspaceService.createStep({workspaceId,++ userWorkspaceId,input,});}@@ -177,11 +210,15 @@ export class CoreWorkflowVersionMutationResolver {@Mutation(() => WorkflowActionDTO)async updateCoreWorkflowVersionStep(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@Args('input'){ coreWorkflowVersionId, step }: UpdateCoreWorkflowVersionStepInput,): Promise<WorkflowActionDTO> {return this.coreWorkflowVersionMutationWorkspaceService.updateStep({workspaceId,++ userWorkspaceId,coreWorkflowVersionId,step,});@@ -190,11 +227,15 @@ export class CoreWorkflowVersionMutationResolver {@Mutation(() => WorkflowVersionTriggerDTO)async updateCoreWorkflowVersionTrigger(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@Args('input'){ coreWorkflowVersionId, trigger }: UpdateCoreWorkflowVersionTriggerInput,): Promise<WorkflowVersionTriggerDTO> {return this.coreWorkflowVersionMutationWorkspaceService.updateTrigger({workspaceId,++ userWorkspaceId,coreWorkflowVersionId,trigger,});@@ -203,11 +244,15 @@ export class CoreWorkflowVersionMutationResolver {@Mutation(() => WorkflowVersionStepChangesDTO)async deleteCoreWorkflowVersionStep(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@Args('input'){ coreWorkflowVersionId, stepId }: DeleteCoreWorkflowVersionStepInput,): Promise<WorkflowVersionStepChangesDTO> {return this.coreWorkflowVersionMutationWorkspaceService.deleteStep({workspaceId,++ userWorkspaceId,coreWorkflowVersionId,stepIdToDelete: stepId,});@@ -216,11 +261,15 @@ export class CoreWorkflowVersionMutationResolver {@Mutation(() => WorkflowVersionStepChangesDTO)async duplicateCoreWorkflowVersionStep(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@Args('input'){ coreWorkflowVersionId, stepId }: DuplicateCoreWorkflowVersionStepInput,): Promise<WorkflowVersionStepChangesDTO> {return this.coreWorkflowVersionMutationWorkspaceService.duplicateStep({workspaceId,++ userWorkspaceId,coreWorkflowVersionId,stepId,});@@ -229,6 +278,8 @@ export class CoreWorkflowVersionMutationResolver {@Mutation(() => WorkflowVersionStepChangesDTO)async createCoreWorkflowVersionEdge(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@Args('input'){coreWorkflowVersionId,@@ -239,6 +290,8 @@ export class CoreWorkflowVersionMutationResolver {): Promise<WorkflowVersionStepChangesDTO> {return this.coreWorkflowVersionMutationWorkspaceService.createEdge({workspaceId,++ userWorkspaceId,coreWorkflowVersionId,source,target,@@ -249,6 +302,8 @@ export class CoreWorkflowVersionMutationResolver {@Mutation(() => WorkflowVersionStepChangesDTO)async deleteCoreWorkflowVersionEdge(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@Args('input'){coreWorkflowVersionId,@@ -259,6 +314,8 @@ export class CoreWorkflowVersionMutationResolver {): Promise<WorkflowVersionStepChangesDTO> {return this.coreWorkflowVersionMutationWorkspaceService.deleteEdge({workspaceId,++ userWorkspaceId,coreWorkflowVersionId,source,target,@@ -269,6 +326,8 @@ export class CoreWorkflowVersionMutationResolver {@Mutation(() => Boolean)async updateCoreWorkflowVersionPositions(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@Args('input'){coreWorkflowVersionId,@@ -277,6 +336,8 @@ export class CoreWorkflowVersionMutationResolver {): Promise<boolean> {await this.coreWorkflowVersionMutationWorkspaceService.updatePositions({workspaceId,++ userWorkspaceId,coreWorkflowVersionId,positions,});diff --git a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow.resolver.ts b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow.resolver.tsindex 9d47a100bba..21187edf58a 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow.resolver.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow.resolver.ts@@ -24,6 +24,7 @@ import { CoreWorkflowByIdArgs } from 'src/engine/core-modules/workflow/dtos/coreimport { CoreWorkflowArgs } from 'src/engine/core-modules/workflow/dtos/core-workflow.input';import { DuplicateCoreWorkflowInput } from 'src/engine/core-modules/workflow/dtos/duplicate-core-workflow.input';import { UpdateCoreWorkflowInput } from 'src/engine/core-modules/workflow/dtos/update-core-workflow.input';+import { UpdateCoreWorkflowVisibilityInput } from 'src/engine/core-modules/workflow/dtos/update-core-workflow-visibility.input';import { CoreWorkflowsArgs } from 'src/engine/core-modules/workflow/dtos/core-workflows.input';import { CoreWorkflowListService } from 'src/engine/core-modules/workflow/services/core-workflow-list.service';import { CoreWorkflowMutationWorkspaceService } from 'src/engine/core-modules/workflow/services/core-workflow-mutation.workspace-service';@@ -32,6 +33,7 @@ import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entimport { type AuthContextUser } from 'src/engine/core-modules/auth/types/auth-context.type';import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filters/auth-graphql-api-exception.filter';import { AuthUser } from 'src/engine/decorators/auth/auth-user.decorator';+import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';import { isDefined } from 'twenty-shared/utils';import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';@@ -63,22 +65,41 @@ export class CoreWorkflowResolver {@Mutation(() => CoreWorkflowDTO, { nullable: true })async updateCoreWorkflow(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@Args('input') input: UpdateCoreWorkflowInput,): Promise<CoreWorkflowDTO | null> {- await this.coreWorkflowMutationWorkspaceService.updateWorkflow(+ await this.coreWorkflowMutationWorkspaceService.updateWorkflow({workspaceId,- input,- );+ userWorkspaceId,+ ...input,+ });return this.coreWorkflowListService.findOneById({workspaceId,+ userWorkspaceId,coreWorkflowId: input.coreWorkflowId,});}+ @Mutation(() => CoreWorkflowDTO, { nullable: true })+ async updateCoreWorkflowVisibility(+ @AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthUserWorkspaceId() userWorkspaceId: string,+ @Args('input') input: UpdateCoreWorkflowVisibilityInput,+ ): Promise<CoreWorkflowDTO | null> {+ return this.coreWorkflowMutationWorkspaceService.updateWorkflowVisibility({+ workspaceId,+ userWorkspaceId,+ ...input,+ });+ }+@Mutation(() => CoreWorkflowDTO)async duplicateCoreWorkflow(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@AuthUser() user: AuthContextUser,@Args('input'){@@ -88,6 +109,7 @@ export class CoreWorkflowResolver {): Promise<CoreWorkflowDTO> {return this.coreWorkflowMutationWorkspaceService.duplicateWorkflow({workspaceId,+ userWorkspaceId,user,coreWorkflowIdToDuplicate,coreWorkflowVersionIdToCopy,@@ -97,37 +119,46 @@ export class CoreWorkflowResolver {@Mutation(() => CoreWorkflowDTO)async createCoreWorkflow(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@AuthUser() user: AuthContextUser,@Args('input') input: CreateCoreWorkflowInput,): Promise<CoreWorkflowDTO> {- return this.coreWorkflowMutationWorkspaceService.createWorkflow(+ return this.coreWorkflowMutationWorkspaceService.createWorkflow({workspaceId,+ userWorkspaceId,user,- input,- );+ ...input,+ });}@Mutation(() => [DeletedCoreWorkflowDTO])async deleteCoreWorkflows(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@Args('input') input: DeleteCoreWorkflowsInput,): Promise<DeletedCoreWorkflowDTO[]> {- return this.coreWorkflowMutationWorkspaceService.deleteWorkflows(+ return this.coreWorkflowMutationWorkspaceService.deleteWorkflows({workspaceId,- input,- );+ userWorkspaceId,+ ...input,+ });}@Mutation(() => CoreWorkflowDTO, { nullable: true })async discardCoreWorkflowDraft(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@Args('input') input: DiscardCoreWorkflowDraftInput,): Promise<CoreWorkflowDTO | null> {const coreWorkflowId =- await this.coreWorkflowMutationWorkspaceService.discardDraftVersion(+ await this.coreWorkflowMutationWorkspaceService.discardDraftVersion({workspaceId,- input,- );+ userWorkspaceId,+ ...input,+ });if (!isDefined(coreWorkflowId)) {return null;@@ -135,6 +166,7 @@ export class CoreWorkflowResolver {return this.coreWorkflowListService.findOneById({workspaceId,+ userWorkspaceId,coreWorkflowId,});}@@ -142,21 +174,27 @@ export class CoreWorkflowResolver {@Query(() => CoreWorkflowConnectionDTO)async coreWorkflows(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@Args() coreWorkflowsArgs: CoreWorkflowsArgs,): Promise<CoreWorkflowConnectionDTO> {- return this.coreWorkflowListService.findManyByWorkspaceId(+ return this.coreWorkflowListService.findManyByWorkspaceId({workspaceId,- coreWorkflowsArgs,- );+ userWorkspaceId,+ ...coreWorkflowsArgs,+ });}@Query(() => CoreWorkflowDTO, { nullable: true })async coreWorkflowById(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@Args() { coreWorkflowId }: CoreWorkflowByIdArgs,): Promise<CoreWorkflowDTO | null> {return this.coreWorkflowListService.findOneById({workspaceId,+ userWorkspaceId,coreWorkflowId,});}@@ -164,10 +202,13 @@ export class CoreWorkflowResolver {@Query(() => [CoreWorkflowWithCurrentVersionDTO])async coreWorkflowsWithCurrentVersions(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@Args('input') { coreWorkflowIds }: CoreWorkflowsWithCurrentVersionsInput,): Promise<CoreWorkflowWithCurrentVersionDTO[]> {return this.coreWorkflowListService.findManyWithCurrentVersions({workspaceId,+ userWorkspaceId,coreWorkflowIds,});}@@ -175,10 +216,13 @@ export class CoreWorkflowResolver {@Query(() => CoreWorkflowDTO, { nullable: true })async coreWorkflow(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@Args() { workspaceWorkflowId }: CoreWorkflowArgs,): Promise<CoreWorkflowDTO | null> {return this.coreWorkflowListService.findOneByWorkspaceWorkflowId({workspaceId,+ userWorkspaceId,workspaceWorkflowId,});}@@ -186,10 +230,13 @@ export class CoreWorkflowResolver {@Query(() => [CoreWorkflowVersionDTO])async coreWorkflowVersions(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@Args() { workspaceWorkflowId }: CoreWorkflowVersionsArgs,): Promise<CoreWorkflowVersionDTO[]> {return this.coreWorkflowVersionListService.findManyByWorkspaceWorkflowId({workspaceId,+ userWorkspaceId,workspaceWorkflowId,});}@@ -197,11 +244,14 @@ export class CoreWorkflowResolver {@Query(() => CoreWorkflowVersionDTO, { nullable: true })async coreWorkflowVersion(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@Args() { workspaceWorkflowVersionId }: CoreWorkflowVersionArgs,): Promise<CoreWorkflowVersionDTO | null> {return this.coreWorkflowVersionListService.findOneByWorkspaceWorkflowVersionId({workspaceId,+ userWorkspaceId,workspaceWorkflowVersionId,},);@@ -210,10 +260,13 @@ export class CoreWorkflowResolver {@Query(() => [CoreWorkflowVersionDTO])async coreWorkflowVersionsByCoreWorkflowId(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@Args() { coreWorkflowId }: CoreWorkflowVersionsByCoreWorkflowIdArgs,): Promise<CoreWorkflowVersionDTO[]> {return this.coreWorkflowVersionListService.findManyByCoreWorkflowId({workspaceId,+ userWorkspaceId,coreWorkflowId,});}@@ -221,10 +274,13 @@ export class CoreWorkflowResolver {@Query(() => CoreWorkflowVersionDTO, { nullable: true })async coreWorkflowVersionById(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@Args() { coreWorkflowVersionId }: CoreWorkflowVersionByIdArgs,): Promise<CoreWorkflowVersionDTO | null> {return this.coreWorkflowVersionListService.findOneByCoreWorkflowVersionId({workspaceId,+ userWorkspaceId,coreWorkflowVersionId,});}diff --git a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-builder.resolver.ts b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-builder.resolver.tsindex 9d5c830e306..7b42cc8ef5b 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-builder.resolver.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-builder.resolver.ts@@ -24,7 +24,9 @@ import {import { WorkflowCommonWorkspaceService } from 'src/modules/workflow/common/workspace-services/workflow-common.workspace-service';import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';import { type WorkflowTrigger } from 'src/modules/workflow/workflow-trigger/types/workflow-trigger.type';+import { CoreWorkflowAccessService } from 'src/engine/core-modules/workflow/services/core-workflow-access.service';import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';+import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';import { UserAuthGuard } from 'src/engine/guards/user-auth.guard';@@ -54,10 +56,13 @@ export class WorkflowBuilderResolver {private readonly workflowCommonWorkspaceService: WorkflowCommonWorkspaceService,@InjectWorkspaceScopedRepository(WorkflowVersionEntity)private readonly coreWorkflowVersionRepository: WorkspaceScopedRepository<WorkflowVersionEntity>,+ private readonly coreWorkflowAccessService: CoreWorkflowAccessService,) {}@Mutation(() => graphqlTypeJson)async computeStepOutputSchema(+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,@Args('input'){@@ -71,6 +76,7 @@ export class WorkflowBuilderResolver {workspaceId,workflowVersionContent: await this.resolveWorkflowVersionContent({workspaceId,+ userWorkspaceId,workflowVersionId,coreWorkflowVersionId,}),@@ -79,10 +85,12 @@ export class WorkflowBuilderResolver {private async resolveWorkflowVersionContent({workspaceId,+ userWorkspaceId,workflowVersionId,coreWorkflowVersionId,}: {workspaceId: string;+ userWorkspaceId: string | undefined;workflowVersionId?: string;coreWorkflowVersionId?: string;}): Promise<@@ -90,6 +98,14 @@ export class WorkflowBuilderResolver {| undefined> {if (isDefined(coreWorkflowVersionId)) {+ await this.coreWorkflowAccessService.assertCoreWorkflowVersionsAreAccessibleOrThrow(+ {+ workspaceId,+ userWorkspaceId,+ coreWorkflowVersionIds: [coreWorkflowVersionId],+ },+ );+const coreWorkflowVersion =await this.coreWorkflowVersionRepository.findOne(workspaceId, {where: { id: coreWorkflowVersionId },@@ -115,6 +131,14 @@ export class WorkflowBuilderResolver {return undefined;}+ await this.coreWorkflowAccessService.assertWorkspaceWorkflowVersionsAreAccessibleOrThrow(+ {+ workspaceId,+ userWorkspaceId,+ workspaceWorkflowVersionIds: [workflowVersionId],+ },+ );+const workflowVersion =await this.workflowCommonWorkspaceService.getWorkflowVersionOrFail({workflowVersionId,diff --git a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-trigger.resolver.ts b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-trigger.resolver.tsindex 4e3eac5ba75..7ac3f85f465 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-trigger.resolver.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-trigger.resolver.ts@@ -16,6 +16,7 @@ import { WorkflowTriggerGraphqlApiExceptionFilter } from 'src/engine/core-moduleimport { WorkflowVersionValidationGraphqlApiExceptionFilter } from 'src/engine/core-modules/workflow/filters/workflow-version-validation-graphql-api-exception.filter';import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';import { AuthUser } from 'src/engine/decorators/auth/auth-user.decorator';+import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';import { UserAuthGuard } from 'src/engine/guards/user-auth.guard';@@ -24,6 +25,7 @@ import { PermissionsGraphqlApiExceptionFilter } from 'src/engine/metadata-moduleimport { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';import { buildWorkflowRunTriggerContext } from 'src/modules/workflow/workflow-trigger/utils/build-workflow-run-trigger-context.util';+import { CoreWorkflowAccessService } from 'src/engine/core-modules/workflow/services/core-workflow-access.service';import { WorkflowTriggerWorkspaceService } from 'src/modules/workflow/workflow-trigger/workspace-services/workflow-trigger.workspace-service';import { WorkspaceMemberWorkspaceEntity } from 'src/modules/workspace-member/standard-objects/workspace-member.workspace-entity';@@ -44,14 +46,25 @@ export class WorkflowTriggerResolver {constructor(private readonly workspaceOrmManager: WorkspaceOrmManager,private readonly workflowTriggerWorkspaceService: WorkflowTriggerWorkspaceService,+ private readonly coreWorkflowAccessService: CoreWorkflowAccessService,) {}@Mutation(() => Boolean)async activateWorkflowVersion(+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@AuthWorkspace() workspace: WorkspaceEntity,@Args('workflowVersionId', { type: () => UUIDScalarType })workflowVersionId: string,) {+ await this.coreWorkflowAccessService.assertWorkspaceWorkflowVersionsAreAccessibleOrThrow(+ {+ workspaceId: workspace.id,+ userWorkspaceId,+ workspaceWorkflowVersionIds: [workflowVersionId],+ },+ );+return this.workflowTriggerWorkspaceService.activateWorkflowVersion(workflowVersionId,workspace.id,@@ -60,10 +73,20 @@ export class WorkflowTriggerResolver {@Mutation(() => Boolean)async deactivateWorkflowVersion(+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@AuthWorkspace() workspace: WorkspaceEntity,@Args('workflowVersionId', { type: () => UUIDScalarType })workflowVersionId: string,) {+ await this.coreWorkflowAccessService.assertWorkspaceWorkflowVersionsAreAccessibleOrThrow(+ {+ workspaceId: workspace.id,+ userWorkspaceId,+ workspaceWorkflowVersionIds: [workflowVersionId],+ },+ );+return this.workflowTriggerWorkspaceService.deactivateWorkflowVersion(workflowVersionId,workspace.id,@@ -73,11 +96,21 @@ export class WorkflowTriggerResolver {@Mutation(() => RunWorkflowVersionDTO)@UseGuards(UserAuthGuard)async runWorkflowVersion(+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@AuthUser() user: AuthContextUser,@AuthWorkspace() workspace: WorkspaceEntity,@Args('input'){ workflowVersionId, workflowRunId, payload }: RunWorkflowVersionInput,) {+ await this.coreWorkflowAccessService.assertWorkspaceWorkflowVersionsAreAccessibleOrThrow(+ {+ workspaceId: workspace.id,+ userWorkspaceId,+ workspaceWorkflowVersionIds: [workflowVersionId],+ },+ );+const authContext = buildSystemAuthContext(workspace.id);const workspaceMember =diff --git a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-version-edge.resolver.ts b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-version-edge.resolver.tsindex e68e1ef07a9..832ad4a1883 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-version-edge.resolver.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-version-edge.resolver.ts@@ -11,11 +11,13 @@ import { WorkflowVersionStepChangesDTO } from 'src/engine/core-modules/workflow/import { WorkflowVersionValidationGraphqlApiExceptionFilter } from 'src/engine/core-modules/workflow/filters/workflow-version-validation-graphql-api-exception.filter';import { WorkflowVersionEdgeGraphqlApiExceptionFilter } from 'src/engine/core-modules/workflow/filters/workflow-version-edge-graphql-api-exception.filter';import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';+import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';import { UserAuthGuard } from 'src/engine/guards/user-auth.guard';import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';import { PermissionsGraphqlApiExceptionFilter } from 'src/engine/metadata-modules/permissions/utils/permissions-graphql-api-exception.filter';+import { CoreWorkflowAccessService } from 'src/engine/core-modules/workflow/services/core-workflow-access.service';import { WorkflowVersionEdgeWorkspaceService } from 'src/modules/workflow/workflow-builder/workflow-version-edge/workflow-version-edge.workspace-service';import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filters/auth-graphql-api-exception.filter';@@ -36,10 +38,13 @@ import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filtexport class WorkflowVersionEdgeResolver {constructor(private readonly workflowVersionEdgeWorkspaceService: WorkflowVersionEdgeWorkspaceService,+ private readonly coreWorkflowAccessService: CoreWorkflowAccessService,) {}@Mutation(() => WorkflowVersionStepChangesDTO)async createWorkflowVersionEdge(+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,@Args('input'){@@ -49,6 +54,14 @@ export class WorkflowVersionEdgeResolver {sourceConnectionOptions,}: CreateWorkflowVersionEdgeInput,): Promise<WorkflowVersionStepChangesDTO> {+ await this.coreWorkflowAccessService.assertWorkspaceWorkflowVersionsAreAccessibleOrThrow(+ {+ workspaceId,+ userWorkspaceId,+ workspaceWorkflowVersionIds: [workflowVersionId],+ },+ );+return this.workflowVersionEdgeWorkspaceService.createWorkflowVersionEdge({source,target,@@ -60,6 +73,8 @@ export class WorkflowVersionEdgeResolver {@Mutation(() => WorkflowVersionStepChangesDTO)async deleteWorkflowVersionEdge(+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,@Args('input'){@@ -69,6 +84,14 @@ export class WorkflowVersionEdgeResolver {sourceConnectionOptions,}: CreateWorkflowVersionEdgeInput,): Promise<WorkflowVersionStepChangesDTO> {+ await this.coreWorkflowAccessService.assertWorkspaceWorkflowVersionsAreAccessibleOrThrow(+ {+ workspaceId,+ userWorkspaceId,+ workspaceWorkflowVersionIds: [workflowVersionId],+ },+ );+return this.workflowVersionEdgeWorkspaceService.deleteWorkflowVersionEdge({source,target,diff --git a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-version-step.resolver.ts b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-version-step.resolver.tsindex 9cbf1cc2d2a..df4e22c2b30 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-version-step.resolver.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-version-step.resolver.ts@@ -23,6 +23,7 @@ import { WorkflowVersionTriggerDTO } from 'src/engine/core-modules/workflow/dtosimport { WorkflowVersionValidationGraphqlApiExceptionFilter } from 'src/engine/core-modules/workflow/filters/workflow-version-validation-graphql-api-exception.filter';import { WorkflowVersionStepGraphqlApiExceptionFilter } from 'src/engine/core-modules/workflow/filters/workflow-version-step-graphql-api-exception.filter';import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';+import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';import { UserAuthGuard } from 'src/engine/guards/user-auth.guard';@@ -30,6 +31,7 @@ import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';import { ConnectedAccountMetadataService } from 'src/engine/metadata-modules/connected-account/connected-account-metadata.service';import { ConnectedAccountHandleDTO } from 'src/engine/metadata-modules/connected-account/dtos/connected-account-handle.dto';import { PermissionsGraphqlApiExceptionFilter } from 'src/engine/metadata-modules/permissions/utils/permissions-graphql-api-exception.filter';+import { CoreWorkflowAccessService } from 'src/engine/core-modules/workflow/services/core-workflow-access.service';import { WorkflowVersionStepWorkspaceService } from 'src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step.workspace-service';import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';import { WorkflowRunnerWorkspaceService } from 'src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service';@@ -56,6 +58,7 @@ export class WorkflowVersionStepResolver {private readonly workflowRunWorkspaceService: WorkflowRunWorkspaceService,private readonly httpTool: HttpTool,private readonly connectedAccountMetadataService: ConnectedAccountMetadataService,+ private readonly coreWorkflowAccessService: CoreWorkflowAccessService,) {}// Related to https://github.com/twentyhq/private-issues/issues/478@@ -83,10 +86,20 @@ export class WorkflowVersionStepResolver {@Mutation(() => WorkflowVersionStepChangesDTO)async createWorkflowVersionStep(+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,@Args('input')input: CreateWorkflowVersionStepInput,): Promise<WorkflowVersionStepChangesDTO> {+ await this.coreWorkflowAccessService.assertWorkspaceWorkflowVersionsAreAccessibleOrThrow(+ {+ workspaceId,+ userWorkspaceId,+ workspaceWorkflowVersionIds: [input.workflowVersionId],+ },+ );+return this.workflowVersionStepWorkspaceService.createWorkflowVersionStep({workspaceId,input,@@ -95,10 +108,20 @@ export class WorkflowVersionStepResolver {@Mutation(() => WorkflowActionDTO)async updateWorkflowVersionStep(+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,@Args('input'){ step, workflowVersionId }: UpdateWorkflowVersionStepInput,): Promise<WorkflowActionDTO> {+ await this.coreWorkflowAccessService.assertWorkspaceWorkflowVersionsAreAccessibleOrThrow(+ {+ workspaceId,+ userWorkspaceId,+ workspaceWorkflowVersionIds: [workflowVersionId],+ },+ );+return this.workflowVersionStepWorkspaceService.updateWorkflowVersionStep({workspaceId,workflowVersionId,@@ -108,10 +131,20 @@ export class WorkflowVersionStepResolver {@Mutation(() => WorkflowVersionTriggerDTO)async updateWorkflowVersionTrigger(+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,@Args('input'){ trigger, workflowVersionId }: UpdateWorkflowVersionTriggerInput,): Promise<WorkflowVersionTriggerDTO> {+ await this.coreWorkflowAccessService.assertWorkspaceWorkflowVersionsAreAccessibleOrThrow(+ {+ workspaceId,+ userWorkspaceId,+ workspaceWorkflowVersionIds: [workflowVersionId],+ },+ );+return this.workflowVersionStepWorkspaceService.updateWorkflowVersionTrigger({workspaceId,@@ -123,10 +156,20 @@ export class WorkflowVersionStepResolver {@Mutation(() => WorkflowVersionStepChangesDTO)async deleteWorkflowVersionStep(+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,@Args('input'){ stepId, workflowVersionId }: DeleteWorkflowVersionStepInput,): Promise<WorkflowVersionStepChangesDTO> {+ await this.coreWorkflowAccessService.assertWorkspaceWorkflowVersionsAreAccessibleOrThrow(+ {+ workspaceId,+ userWorkspaceId,+ workspaceWorkflowVersionIds: [workflowVersionId],+ },+ );+return this.workflowVersionStepWorkspaceService.deleteWorkflowVersionStep({workspaceId,workflowVersionId,@@ -167,10 +210,20 @@ export class WorkflowVersionStepResolver {@Mutation(() => WorkflowVersionStepChangesDTO)async duplicateWorkflowVersionStep(+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,@Args('input'){ stepId, workflowVersionId }: DuplicateWorkflowVersionStepInput,): Promise<WorkflowVersionStepChangesDTO> {+ await this.coreWorkflowAccessService.assertWorkspaceWorkflowVersionsAreAccessibleOrThrow(+ {+ workspaceId,+ userWorkspaceId,+ workspaceWorkflowVersionIds: [workflowVersionId],+ },+ );+return this.workflowVersionStepWorkspaceService.duplicateWorkflowVersionStep({workspaceId,diff --git a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-version.resolver.ts b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-version.resolver.tsindex 43151fa8d24..106b683a822 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-version.resolver.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-version.resolver.ts@@ -14,6 +14,7 @@ import { UpdateWorkflowVersionPositionsInput } from 'src/engine/core-modules/worimport { WorkflowVersionContentDTO } from 'src/engine/core-modules/workflow/dtos/workflow-version-content.dto';import { WorkflowVersionDTO } from 'src/engine/core-modules/workflow/dtos/workflow-version.dto';import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';+import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';import { UserAuthGuard } from 'src/engine/guards/user-auth.guard';@@ -21,6 +22,7 @@ import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';import { PermissionsGraphqlApiExceptionFilter } from 'src/engine/metadata-modules/permissions/utils/permissions-graphql-api-exception.filter';import { WorkflowCommonWorkspaceService } from 'src/modules/workflow/common/workspace-services/workflow-common.workspace-service';import { WorkflowVersionValidationWorkspaceService } from 'src/modules/workflow/workflow-builder/workflow-validation/workflow-version-validation.workspace-service';+import { CoreWorkflowAccessService } from 'src/engine/core-modules/workflow/services/core-workflow-access.service';import { WorkflowVersionWorkspaceService } from 'src/modules/workflow/workflow-builder/workflow-version/workflow-version.workspace-service';import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filters/auth-graphql-api-exception.filter';@@ -42,14 +44,25 @@ export class WorkflowVersionResolver {private readonly workflowVersionWorkspaceService: WorkflowVersionWorkspaceService,private readonly workflowCommonWorkspaceService: WorkflowCommonWorkspaceService,private readonly workflowVersionValidationWorkspaceService: WorkflowVersionValidationWorkspaceService,+ private readonly coreWorkflowAccessService: CoreWorkflowAccessService,) {}@Query(() => WorkflowVersionContentDTO)async workflowVersionContent(+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,@Args('workflowVersionId', { type: () => UUIDScalarType })workflowVersionId: string,): Promise<WorkflowVersionContentDTO> {+ await this.coreWorkflowAccessService.assertWorkspaceWorkflowVersionsAreAccessibleOrThrow(+ {+ workspaceId,+ userWorkspaceId,+ workspaceWorkflowVersionIds: [workflowVersionId],+ },+ );+const workflowVersion =await this.workflowCommonWorkspaceService.getWorkflowVersionOrFail({workspaceId,@@ -65,10 +78,20 @@ export class WorkflowVersionResolver {@Mutation(() => Boolean)async validateWorkflowVersion(+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,@Args('workflowVersionId', { type: () => UUIDScalarType })workflowVersionId: string,): Promise<boolean> {+ await this.coreWorkflowAccessService.assertWorkspaceWorkflowVersionsAreAccessibleOrThrow(+ {+ workspaceId,+ userWorkspaceId,+ workspaceWorkflowVersionIds: [workflowVersionId],+ },+ );+const workflowVersion =await this.workflowCommonWorkspaceService.getWorkflowVersionOrFail({workspaceId,@@ -88,6 +111,8 @@ export class WorkflowVersionResolver {@Mutation(() => WorkflowVersionDTO)async createDraftFromWorkflowVersion(+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,@Args('input'){@@ -95,6 +120,14 @@ export class WorkflowVersionResolver {workflowVersionIdToCopy,}: CreateDraftFromWorkflowVersionInput,): Promise<WorkflowVersionDTO> {+ await this.coreWorkflowAccessService.assertWorkspaceWorkflowVersionsAreAccessibleOrThrow(+ {+ workspaceId,+ userWorkspaceId,+ workspaceWorkflowVersionIds: [workflowVersionIdToCopy],+ },+ );+return this.workflowVersionWorkspaceService.createDraftFromWorkflowVersion({workspaceId,workflowId,@@ -104,10 +137,20 @@ export class WorkflowVersionResolver {@Mutation(() => WorkflowVersionDTO)async duplicateWorkflow(+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,@Args('input'){ workflowIdToDuplicate, workflowVersionIdToCopy }: DuplicateWorkflowInput,): Promise<WorkflowVersionDTO> {+ await this.coreWorkflowAccessService.assertWorkspaceWorkflowVersionsAreAccessibleOrThrow(+ {+ workspaceId,+ userWorkspaceId,+ workspaceWorkflowVersionIds: [workflowVersionIdToCopy],+ },+ );+return this.workflowVersionWorkspaceService.duplicateWorkflow({workspaceId,workflowIdToDuplicate,@@ -117,10 +160,20 @@ export class WorkflowVersionResolver {@Mutation(() => Boolean)async updateWorkflowVersionPositions(+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,@Args('input'){ workflowVersionId, positions }: UpdateWorkflowVersionPositionsInput,) {+ await this.coreWorkflowAccessService.assertWorkspaceWorkflowVersionsAreAccessibleOrThrow(+ {+ workspaceId,+ userWorkspaceId,+ workspaceWorkflowVersionIds: [workflowVersionId],+ },+ );+await this.workflowVersionWorkspaceService.updateWorkflowVersionPositions({workspaceId,workflowVersionId,diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/__tests__/core-workflow-version-mutation.workspace-service.spec.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/__tests__/core-workflow-version-mutation.workspace-service.spec.tsindex 83c45bd8546..0ad54cde43f 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/services/__tests__/core-workflow-version-mutation.workspace-service.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/__tests__/core-workflow-version-mutation.workspace-service.spec.ts@@ -5,6 +5,7 @@ import { CoreWorkflowVersionPostCommitError } from 'src/engine/core-modules/workimport { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';const workspaceId = '20202020-0000-0000-0000-000000000001';+const userWorkspaceId = '20202020-0000-0000-0000-000000000009';const coreWorkflowVersionId = '20202020-0000-0000-0000-000000000002';const stepId = '20202020-0000-0000-0000-000000000003';@@ -93,6 +94,7 @@ describe('CoreWorkflowVersionMutationWorkspaceService', () => {await expect(service.updateStep({workspaceId,+ userWorkspaceId,coreWorkflowVersionId,step: { ...replacementEmptyStep, id: stepId },}),@@ -113,6 +115,7 @@ describe('CoreWorkflowVersionMutationWorkspaceService', () => {await service.updateStep({workspaceId,+ userWorkspaceId,coreWorkflowVersionId,step: { ...replacementEmptyStep, id: stepId },});@@ -136,6 +139,7 @@ describe('CoreWorkflowVersionMutationWorkspaceService', () => {await expect(service.updateStep({workspaceId,+ userWorkspaceId,coreWorkflowVersionId,step: { ...replacementEmptyStep, id: stepId },}),diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/__tests__/core-workflow-version-write.service.spec.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/__tests__/core-workflow-version-write.service.spec.tsindex 78c4a4d218c..f1f1886d2f4 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/services/__tests__/core-workflow-version-write.service.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/__tests__/core-workflow-version-write.service.spec.ts@@ -31,6 +31,9 @@ describe('CoreWorkflowVersionWriteService', () => {const service = new CoreWorkflowVersionWriteService({} as never,{ invalidateAutomatedTriggerMaps } as never,+ {+ assertCoreWorkflowVersionsAreAccessibleOrThrow: jest.fn(),+ } as never,{getFlatEntityMaps: jest.fn().mockResolvedValue({flatObjectMetadataMaps: {},diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-access.service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-access.service.tsnew file mode 100644index 00000000000..014243e9d19--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-access.service.ts@@ -0,0 +1,281 @@+import { Injectable } from '@nestjs/common';++import { msg } from '@lingui/core/macro';+import { WorkflowVisibility } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';+import { In } from 'typeorm';++import { WorkflowVersionEntity } from 'src/engine/core-modules/workflow/entities/workflow-version.entity';+import { WorkflowEntity } from 'src/engine/core-modules/workflow/entities/workflow.entity';+import { canChangeCoreWorkflowVisibility } from 'src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility.util';+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 {+ WorkflowQueryValidationException,+ WorkflowQueryValidationExceptionCode,+} from 'src/modules/workflow/common/exceptions/workflow-query-validation.exception';++// A workflow's versions carry its whole definition, so reaching one by id has+// to answer to the same rule as reaching the workflow. Both asserts live here+// so a private workflow has one deny to audit rather than one per entry point.+@Injectable()+export class CoreWorkflowAccessService {+ constructor(+ @InjectWorkspaceScopedRepository(WorkflowEntity)+ private readonly coreWorkflowRepository: WorkspaceScopedRepository<WorkflowEntity>,+ @InjectWorkspaceScopedRepository(WorkflowVersionEntity)+ private readonly coreWorkflowVersionRepository: WorkspaceScopedRepository<WorkflowVersionEntity>,+ ) {}++ async assertCoreWorkflowsAreAccessibleOrThrow({+ workspaceId,+ userWorkspaceId,+ coreWorkflowIds,+ }: {+ workspaceId: string;+ userWorkspaceId: string | undefined;+ coreWorkflowIds: string[];+ }): Promise<void> {+ if (coreWorkflowIds.length === 0) {+ return;+ }++ const inaccessibleCoreWorkflow = await this.findInaccessibleCoreWorkflow({+ workspaceId,+ userWorkspaceId,+ coreWorkflowIds,+ });++ if (isDefined(inaccessibleCoreWorkflow)) {+ throw new WorkflowQueryValidationException(+ `Core workflow '${inaccessibleCoreWorkflow.id}' is private to another member`,+ WorkflowQueryValidationExceptionCode.FORBIDDEN,+ {+ // the same message a missing workflow gets, so a private one does not+ // announce that it exists+ userFriendlyMessage: msg`Workflow not found`,+ },+ );+ }+ }++ async assertCoreWorkflowVersionsAreAccessibleOrThrow({+ workspaceId,+ userWorkspaceId,+ coreWorkflowVersionIds,+ }: {+ workspaceId: string;+ userWorkspaceId: string | undefined;+ coreWorkflowVersionIds: string[];+ }): Promise<void> {+ if (coreWorkflowVersionIds.length === 0) {+ return;+ }++ const coreWorkflowVersions = await this.coreWorkflowVersionRepository.find(+ workspaceId,+ {+ where: { id: In(coreWorkflowVersionIds) },+ select: { id: true, coreWorkflowId: true },+ },+ );++ const coreWorkflowIds = [+ ...new Set(+ coreWorkflowVersions+ .map(({ coreWorkflowId }) => coreWorkflowId)+ .filter(isDefined),+ ),+ ];++ await this.assertCoreWorkflowsAreAccessibleOrThrow({+ workspaceId,+ userWorkspaceId,+ coreWorkflowIds,+ });+ }++ // The legacy resolvers are keyed by the workspace mirror's ids rather than+ // the core ones, so they need the same rule reached from the other side.+ async assertWorkspaceWorkflowVersionsAreAccessibleOrThrow({+ workspaceId,+ userWorkspaceId,+ workspaceWorkflowVersionIds,+ }: {+ workspaceId: string;+ userWorkspaceId: string | undefined;+ workspaceWorkflowVersionIds: string[];+ }): Promise<void> {+ if (workspaceWorkflowVersionIds.length === 0) {+ return;+ }++ const coreWorkflowVersions = await this.coreWorkflowVersionRepository.find(+ workspaceId,+ {+ where: { workspaceWorkflowVersionId: In(workspaceWorkflowVersionIds) },+ select: { id: true, coreWorkflowId: true },+ },+ );++ await this.assertCoreWorkflowsAreAccessibleOrThrow({+ workspaceId,+ userWorkspaceId,+ coreWorkflowIds: [+ ...new Set(+ coreWorkflowVersions+ .map(({ coreWorkflowId }) => coreWorkflowId)+ .filter(isDefined),+ ),+ ],+ });+ }++ async assertWorkspaceWorkflowsAreAccessibleOrThrow({+ workspaceId,+ userWorkspaceId,+ workspaceWorkflowIds,+ }: {+ workspaceId: string;+ userWorkspaceId: string | undefined;+ workspaceWorkflowIds: string[];+ }): Promise<void> {+ if (workspaceWorkflowIds.length === 0) {+ return;+ }++ const coreWorkflows = await this.coreWorkflowRepository.find(workspaceId, {+ where: { workspaceWorkflowId: In(workspaceWorkflowIds) },+ select: { id: true },+ });++ await this.assertCoreWorkflowsAreAccessibleOrThrow({+ workspaceId,+ userWorkspaceId,+ coreWorkflowIds: coreWorkflows.map(({ id }) => id),+ });+ }++ // The command menu lists every member's manual triggers in one read, so the+ // rule has to come back as a filter rather than a deny.+ async findInaccessibleWorkspaceWorkflowVersionIds({+ workspaceId,+ userWorkspaceId,+ workspaceWorkflowVersionIds,+ }: {+ workspaceId: string;+ userWorkspaceId: string | undefined;+ workspaceWorkflowVersionIds: string[];+ }): Promise<Set<string>> {+ if (workspaceWorkflowVersionIds.length === 0) {+ return new Set();+ }++ const coreWorkflowVersions = await this.coreWorkflowVersionRepository.find(+ workspaceId,+ {+ where: { workspaceWorkflowVersionId: In(workspaceWorkflowVersionIds) },+ select: {+ id: true,+ coreWorkflowId: true,+ workspaceWorkflowVersionId: true,+ },+ },+ );++ const inaccessibleCoreWorkflows = await this.findInaccessibleCoreWorkflows({+ workspaceId,+ userWorkspaceId,+ coreWorkflowIds: [+ ...new Set(+ coreWorkflowVersions+ .map(({ coreWorkflowId }) => coreWorkflowId)+ .filter(isDefined),+ ),+ ],+ });++ const inaccessibleCoreWorkflowIds = new Set(+ inaccessibleCoreWorkflows.map(({ id }) => id),+ );++ return new Set(+ coreWorkflowVersions.flatMap(+ ({ coreWorkflowId, workspaceWorkflowVersionId }) =>+ isDefined(coreWorkflowId) &&+ isDefined(workspaceWorkflowVersionId) &&+ inaccessibleCoreWorkflowIds.has(coreWorkflowId)+ ? [workspaceWorkflowVersionId]+ : [],+ ),+ );+ }++ async isCoreWorkflowAccessible({+ workspaceId,+ userWorkspaceId,+ coreWorkflowId,+ }: {+ workspaceId: string;+ userWorkspaceId: string | undefined;+ coreWorkflowId: string;+ }): Promise<boolean> {+ const inaccessibleCoreWorkflow = await this.findInaccessibleCoreWorkflow({+ workspaceId,+ userWorkspaceId,+ coreWorkflowIds: [coreWorkflowId],+ });++ return !isDefined(inaccessibleCoreWorkflow);+ }++ private async findInaccessibleCoreWorkflow({+ workspaceId,+ userWorkspaceId,+ coreWorkflowIds,+ }: {+ workspaceId: string;+ userWorkspaceId: string | undefined;+ coreWorkflowIds: string[];+ }): Promise<WorkflowEntity | undefined> {+ const [inaccessibleCoreWorkflow] = await this.findInaccessibleCoreWorkflows(+ { workspaceId, userWorkspaceId, coreWorkflowIds },+ );++ return inaccessibleCoreWorkflow;+ }++ private async findInaccessibleCoreWorkflows({+ workspaceId,+ userWorkspaceId,+ coreWorkflowIds,+ }: {+ workspaceId: string;+ userWorkspaceId: string | undefined;+ coreWorkflowIds: string[];+ }): Promise<WorkflowEntity[]> {+ if (coreWorkflowIds.length === 0) {+ return [];+ }++ const coreWorkflows = await this.coreWorkflowRepository.find(workspaceId, {+ where: { id: In(coreWorkflowIds) },+ select: {+ id: true,+ visibility: true,+ createdByUserWorkspaceId: true,+ },+ });++ // An id nobody owns keeps behaving exactly as it did before, so an unknown+ // or already deleted workflow is still a no-op rather than a refusal.+ return coreWorkflows.filter(+ (coreWorkflow) =>+ coreWorkflow.visibility === WorkflowVisibility.PRIVATE &&+ !canChangeCoreWorkflowVisibility({+ createdByUserWorkspaceId: coreWorkflow.createdByUserWorkspaceId,+ userWorkspaceId,+ }),+ );+ }+}diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-id-resolution.service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-id-resolution.service.tsindex 4f0df1342f3..e2a68110a2b 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-id-resolution.service.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-id-resolution.service.ts@@ -5,6 +5,7 @@ import { isDefined } from 'twenty-shared/utils';import { WorkflowVersionEntity } from 'src/engine/core-modules/workflow/entities/workflow-version.entity';import { WorkflowEntity } from 'src/engine/core-modules/workflow/entities/workflow.entity';+import { CoreWorkflowAccessService } from 'src/engine/core-modules/workflow/services/core-workflow-access.service';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 {@@ -19,13 +20,16 @@ export class CoreWorkflowIdResolutionService {private readonly coreWorkflowRepository: WorkspaceScopedRepository<WorkflowEntity>,@InjectWorkspaceScopedRepository(WorkflowVersionEntity)private readonly coreWorkflowVersionRepository: WorkspaceScopedRepository<WorkflowVersionEntity>,+ private readonly coreWorkflowAccessService: CoreWorkflowAccessService,) {}async resolveWorkspaceVersionIdOrThrow({workspaceId,+ userWorkspaceId,coreWorkflowVersionId,}: {workspaceId: string;+ userWorkspaceId: string | undefined;coreWorkflowVersionId: string;}): Promise<{coreWorkflowVersion: WorkflowVersionEntity;@@ -33,6 +37,7 @@ export class CoreWorkflowIdResolutionService {}> {const resolved = await this.resolveWorkspaceVersionIdIfCoreVersionExists({workspaceId,+ userWorkspaceId,coreWorkflowVersionId,});@@ -49,11 +54,15 @@ export class CoreWorkflowIdResolutionService {return resolved;}+ // Everything that reaches a workflow by id comes through here, so this is+ // where a workflow private to someone else stops being resolvable at all.async resolveWorkspaceVersionIdIfCoreVersionExists({workspaceId,+ userWorkspaceId,coreWorkflowVersionId,}: {workspaceId: string;+ userWorkspaceId: string | undefined;coreWorkflowVersionId: string;}): Promise<{coreWorkflowVersion: WorkflowVersionEntity;@@ -68,6 +77,14 @@ export class CoreWorkflowIdResolutionService {return null;}+ await this.coreWorkflowAccessService.assertCoreWorkflowVersionsAreAccessibleOrThrow(+ {+ workspaceId,+ userWorkspaceId,+ coreWorkflowVersionIds: [coreWorkflowVersion.id],+ },+ );+const workspaceWorkflowVersionId =coreWorkflowVersion.workspaceWorkflowVersionId;@@ -89,9 +106,11 @@ export class CoreWorkflowIdResolutionService {async resolveWorkspaceWorkflowIdOrThrow({workspaceId,+ userWorkspaceId,coreWorkflowId,}: {workspaceId: string;+ userWorkspaceId: string | undefined;coreWorkflowId: string;}): Promise<{coreWorkflow: WorkflowEntity;@@ -112,6 +131,10 @@ export class CoreWorkflowIdResolutionService {);}+ await this.coreWorkflowAccessService.assertCoreWorkflowsAreAccessibleOrThrow(+ { workspaceId, userWorkspaceId, coreWorkflowIds: [coreWorkflow.id] },+ );+const workspaceWorkflowId = coreWorkflow.workspaceWorkflowId;if (!isDefined(workspaceWorkflowId)) {diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-lifecycle.workspace-service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-lifecycle.workspace-service.tsindex b7b2e9435e1..4380145418c 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-lifecycle.workspace-service.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-lifecycle.workspace-service.ts@@ -15,6 +15,7 @@ import {WorkflowVersionStatus as CoreWorkflowVersionStatus,} from 'src/engine/core-modules/workflow/entities/workflow-version.entity';import { type WorkflowEntity } from 'src/engine/core-modules/workflow/entities/workflow.entity';+import { CoreWorkflowAccessService } from 'src/engine/core-modules/workflow/services/core-workflow-access.service';import { CoreWorkflowIdResolutionService } from 'src/engine/core-modules/workflow/services/core-workflow-id-resolution.service';import { assertExactlyOneMirrorRowWasWritten } from 'src/engine/core-modules/workflow/utils/assert-exactly-one-mirror-row-was-written.util';import { WorkflowVersionCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-version-core-sync.service';@@ -79,6 +80,7 @@ export class CoreWorkflowLifecycleWorkspaceService {@InjectWorkspaceScopedRepository(WorkflowVersionEntity)private readonly coreWorkflowVersionRepository: WorkspaceScopedRepository<WorkflowVersionEntity>,private readonly coreWorkflowIdResolutionService: CoreWorkflowIdResolutionService,+ private readonly coreWorkflowAccessService: CoreWorkflowAccessService,private readonly workflowVersionCoreSyncService: WorkflowVersionCoreSyncService,private readonly workflowCommonWorkspaceService: WorkflowCommonWorkspaceService,private readonly workflowVersionValidationWorkspaceService: WorkflowVersionValidationWorkspaceService,@@ -94,11 +96,23 @@ export class CoreWorkflowLifecycleWorkspaceService {async validateCoreWorkflowVersion({workspaceId,+ userWorkspaceId,coreWorkflowVersionId,}: {workspaceId: string;+ userWorkspaceId: string | undefined;coreWorkflowVersionId: string;}): Promise<boolean> {+ // this one reads the version straight from the repository rather than+ // through the id resolver, so it needs the rule applied by hand+ await this.coreWorkflowAccessService.assertCoreWorkflowVersionsAreAccessibleOrThrow(+ {+ workspaceId,+ userWorkspaceId,+ coreWorkflowVersionIds: [coreWorkflowVersionId],+ },+ );+const coreWorkflowVersion =await this.coreWorkflowVersionRepository.findOne(workspaceId, {where: { id: coreWorkflowVersionId },@@ -127,13 +141,16 @@ export class CoreWorkflowLifecycleWorkspaceService {async activateCoreWorkflowVersion({workspaceId,+ userWorkspaceId,coreWorkflowVersionId,}: {workspaceId: string;+ userWorkspaceId: string | undefined;coreWorkflowVersionId: string;}): Promise<boolean> {const resolved = await this.resolveCoreVersionWithWorkflowOrThrow({workspaceId,+ userWorkspaceId,coreWorkflowVersionId,});@@ -259,6 +276,7 @@ export class CoreWorkflowLifecycleWorkspaceService {previousResolved = await this.resolveCoreVersionWithWorkflowOrThrow({workspaceId,+ userWorkspaceId,coreWorkflowVersionId: previousCoreWorkflowVersionId,},);@@ -352,13 +370,16 @@ export class CoreWorkflowLifecycleWorkspaceService {async deactivateCoreWorkflowVersion({workspaceId,+ userWorkspaceId,coreWorkflowVersionId,}: {workspaceId: string;+ userWorkspaceId: string | undefined;coreWorkflowVersionId: string;}): Promise<boolean> {const resolved = await this.resolveCoreVersionWithWorkflowOrThrow({workspaceId,+ userWorkspaceId,coreWorkflowVersionId,});@@ -403,12 +424,14 @@ export class CoreWorkflowLifecycleWorkspaceService {async runCoreWorkflowVersion({workspaceId,+ userWorkspaceId,coreWorkflowVersionId,payload,createdBy,workflowRunId,}: {workspaceId: string;+ userWorkspaceId: string | undefined;coreWorkflowVersionId: string;payload: object;createdBy: ActorMetadata;@@ -416,7 +439,7 @@ export class CoreWorkflowLifecycleWorkspaceService {}): Promise<{ workflowRunId: string }> {const { workspaceWorkflowVersionId } =await this.coreWorkflowIdResolutionService.resolveWorkspaceVersionIdOrThrow(- { workspaceId, coreWorkflowVersionId },+ { workspaceId, userWorkspaceId, coreWorkflowVersionId },);return this.workflowRunnerWorkspaceService.run({@@ -430,14 +453,16 @@ export class CoreWorkflowLifecycleWorkspaceService {private async resolveCoreVersionWithWorkflowOrThrow({workspaceId,+ userWorkspaceId,coreWorkflowVersionId,}: {workspaceId: string;+ userWorkspaceId: string | undefined;coreWorkflowVersionId: string;}): Promise<ResolvedCoreVersion> {const { coreWorkflowVersion, workspaceWorkflowVersionId } =await this.coreWorkflowIdResolutionService.resolveWorkspaceVersionIdOrThrow(- { workspaceId, coreWorkflowVersionId },+ { workspaceId, userWorkspaceId, coreWorkflowVersionId },);if (!isDefined(coreWorkflowVersion.coreWorkflowId)) {@@ -452,7 +477,11 @@ export class CoreWorkflowLifecycleWorkspaceService {const { coreWorkflow, workspaceWorkflowId } =await this.coreWorkflowIdResolutionService.resolveWorkspaceWorkflowIdOrThrow(- { workspaceId, coreWorkflowId: coreWorkflowVersion.coreWorkflowId },+ {+ workspaceId,+ userWorkspaceId,+ coreWorkflowId: coreWorkflowVersion.coreWorkflowId,+ },);return {diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-list.service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-list.service.tsindex 5fd05439667..319bb1f6e71 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-list.service.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-list.service.ts@@ -1,6 +1,7 @@import { Injectable } from '@nestjs/common';import { InjectDataSource } from '@nestjs/typeorm';+import { type WorkflowVisibility } from 'twenty-shared/types';import { isDefined } from 'twenty-shared/utils';import { DataSource, In } from 'typeorm';@@ -17,6 +18,10 @@ import {type CoreWorkflowsArgs,} from 'src/engine/core-modules/workflow/dtos/core-workflows.input';import { buildCoreWorkflowFilterPredicate } from 'src/engine/core-modules/workflow/utils/build-core-workflow-filter-predicate.util';+import { buildCoreWorkflowVisibilitySqlPredicate } from 'src/engine/core-modules/workflow/utils/build-core-workflow-visibility-sql-predicate.util';+import { buildCoreWorkflowVisibilityWhere } from 'src/engine/core-modules/workflow/utils/build-core-workflow-visibility-where.util';+import { canChangeCoreWorkflowVisibility } from 'src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility.util';+import { canChangeCoreWorkflowVisibilitySelectExpression } from 'src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility-select-expression.util';import { buildCoreWorkflowVersionLabel } from 'src/engine/core-modules/workflow/utils/build-core-workflow-version-label.util';import { computeCoreWorkflowStatuses } from 'src/engine/core-modules/workflow/utils/compute-core-workflow-statuses.util';import { WorkflowEntity } from 'src/engine/core-modules/workflow/entities/workflow.entity';@@ -36,6 +41,8 @@ type CoreWorkflowRow = {lastPublishedCoreWorkflowVersionId: string | null;applicationId: string | null;workspaceWorkflowId: string | null;+ visibility: WorkflowVisibility;+ canChangeVisibility: boolean;updatedAt: Date;hasDraftVersion: boolean;hasActiveVersion: boolean;@@ -68,12 +75,22 @@ const SORT_COLUMN_BY_FIELD: Record<},};+// Every raw query binds the reader as $2, right after the workspace, so the+// filter parameters keep starting at $3 in both the page and the count.+const READER_PARAMETER = '$2';+const VISIBILITY_PREDICATE = buildCoreWorkflowVisibilitySqlPredicate({+ tableAlias: 'c',+ userWorkspaceIdParameter: READER_PARAMETER,+});+const GROUPED_WORKFLOW_COLUMNS = `c.id, c.name, c."createdAt", c."updatedAt"`;const CORE_WORKFLOW_AGGREGATE_COLUMNS = `c.name,c."lastPublishedVersionId", c."lastPublishedCoreWorkflowVersionId",c."applicationId",+ c."visibility",+ ${canChangeCoreWorkflowVisibilitySelectExpression({ tableAlias: 'c', userWorkspaceIdParameter: READER_PARAMETER })} AS "canChangeVisibility",c."createdAt",c."updatedAt",coalesce(bool_or(v.status = 'DRAFT'), false) AS "hasDraftVersion",@@ -92,6 +109,8 @@ const toCoreWorkflowDTO = (row: CoreWorkflowRow): CoreWorkflowDTO => ({lastPublishedCoreWorkflowVersionId: row.lastPublishedCoreWorkflowVersionId,applicationId: row.applicationId,workspaceWorkflowId: row.workspaceWorkflowId,+ visibility: row.visibility,+ canChangeVisibility: row.canChangeVisibility,createdAt: row.createdAt.toISOString(),updatedAt: row.updatedAt.toISOString(),});@@ -114,14 +133,19 @@ export class CoreWorkflowListService {async findManyWithCurrentVersions({workspaceId,+ userWorkspaceId,coreWorkflowIds,}: {workspaceId: string;+ userWorkspaceId: string | undefined;coreWorkflowIds: string[];}): Promise<CoreWorkflowWithCurrentVersionDTO[]> {const [coreWorkflows, coreWorkflowVersions] = await Promise.all([this.coreWorkflowRepository.find(workspaceId, {- where: { id: In(coreWorkflowIds) },+ where: buildCoreWorkflowVisibilityWhere({+ id: In(coreWorkflowIds),+ userWorkspaceId,+ }),}),this.coreWorkflowVersionRepository.find(workspaceId, {where: { coreWorkflowId: In(coreWorkflowIds) },@@ -252,6 +276,11 @@ export class CoreWorkflowListService {workflow.lastPublishedCoreWorkflowVersionId,applicationId: workflow.applicationId,workspaceWorkflowId: workflow.workspaceWorkflowId,+ visibility: workflow.visibility,+ canChangeVisibility: canChangeCoreWorkflowVisibility({+ createdByUserWorkspaceId: workflow.createdByUserWorkspaceId,+ userWorkspaceId,+ }),createdAt: workflow.createdAt.toISOString(),updatedAt: workflow.updatedAt.toISOString(),},@@ -262,10 +291,18 @@ export class CoreWorkflowListService {});}- async findManyByWorkspaceId(- workspaceId: string,- { first, after, orderBy, orderByDirection, filter }: CoreWorkflowsArgs,- ): Promise<CoreWorkflowConnectionDTO> {+ async findManyByWorkspaceId({+ workspaceId,+ userWorkspaceId,+ first,+ after,+ orderBy,+ orderByDirection,+ filter,+ }: CoreWorkflowsArgs & {+ workspaceId: string;+ userWorkspaceId: string | undefined;+ }): Promise<CoreWorkflowConnectionDTO> {const { column, cursorExpression, nullable, cast } =SORT_COLUMN_BY_FIELD[orderBy];const isAscending = orderByDirection === CoreWorkflowOrderByDirection.ASC;@@ -273,7 +310,7 @@ export class CoreWorkflowListService {const direction = isAscending ? 'ASC' : 'DESC';const nullsClause = nullable ? ' NULLS LAST' : '';- const parameters: unknown[] = [workspaceId];+ const parameters: unknown[] = [workspaceId, userWorkspaceId ?? null];const { predicate: filterPredicate, parameters: filterParameters } =buildCoreWorkflowFilterPredicate({@@ -322,6 +359,7 @@ export class CoreWorkflowListService {FROM core."workflow" c${CORE_WORKFLOW_VERSIONS_JOIN_CLAUSE}WHERE c."workspaceId" = $1+ AND ${VISIBILITY_PREDICATE}${keysetCondition}GROUP BY ${GROUP_BY_CLAUSE}${havingClause}@@ -332,6 +370,7 @@ export class CoreWorkflowListService {const totalCount = await this.countByWorkspaceId({workspaceId,+ userWorkspaceId,filterPredicate,filterParameters,});@@ -359,38 +398,46 @@ export class CoreWorkflowListService {async findOneById({workspaceId,+ userWorkspaceId,coreWorkflowId,}: {workspaceId: string;+ userWorkspaceId: string | undefined;coreWorkflowId: string;}): Promise<CoreWorkflowDTO | null> {return this.findOneByFilterExpression({workspaceId,- filterExpression: 'c.id = $2',+ userWorkspaceId,+ filterExpression: 'c.id = $3',filterParameter: coreWorkflowId,});}async findOneByWorkspaceWorkflowId({workspaceId,+ userWorkspaceId,workspaceWorkflowId,}: {workspaceId: string;+ userWorkspaceId: string | undefined;workspaceWorkflowId: string;}): Promise<CoreWorkflowDTO | null> {return this.findOneByFilterExpression({workspaceId,- filterExpression: 'c."workspaceWorkflowId" = $2',+ userWorkspaceId,+ filterExpression: 'c."workspaceWorkflowId" = $3',filterParameter: workspaceWorkflowId,});}private async findOneByFilterExpression({workspaceId,+ userWorkspaceId,filterExpression,filterParameter,}: {workspaceId: string;+ userWorkspaceId: string | undefined;filterExpression: string;filterParameter: string;}): Promise<CoreWorkflowDTO | null> {@@ -403,9 +450,10 @@ export class CoreWorkflowListService {FROM core."workflow" c${CORE_WORKFLOW_VERSIONS_JOIN_CLAUSE}WHERE c."workspaceId" = $1+ AND ${VISIBILITY_PREDICATE}AND ${filterExpression}GROUP BY ${GROUP_BY_CLAUSE}`,- [workspaceId, filterParameter],+ [workspaceId, userWorkspaceId ?? null, filterParameter],);const [row] = rows;@@ -419,21 +467,24 @@ export class CoreWorkflowListService {private async countByWorkspaceId({workspaceId,+ userWorkspaceId,filterPredicate,filterParameters,}: {workspaceId: string;+ userWorkspaceId: string | undefined;filterPredicate?: string;filterParameters: unknown[];}): Promise<number> {- const parameters: unknown[] = [workspaceId];+ const parameters: unknown[] = [workspaceId, userWorkspaceId ?? null];if (!isDefined(filterPredicate)) {const [{ totalCount }]: [{ totalCount: number }] =await this.coreDataSource.query(`SELECT count(*)::int AS "totalCount"FROM core."workflow" c- WHERE c."workspaceId" = $1`,+ WHERE c."workspaceId" = $1+ AND ${VISIBILITY_PREDICATE}`,parameters,);@@ -450,6 +501,7 @@ export class CoreWorkflowListService {FROM core."workflow" c${CORE_WORKFLOW_VERSIONS_JOIN_CLAUSE}WHERE c."workspaceId" = $1+ AND ${VISIBILITY_PREDICATE}GROUP BY ${GROUPED_WORKFLOW_COLUMNS}HAVING ${filterPredicate}) filtered`,diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-mutation.workspace-service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-mutation.workspace-service.tsindex 06240096212..1ca49dadc81 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-mutation.workspace-service.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-mutation.workspace-service.ts@@ -1,7 +1,8 @@import { Injectable, Logger } from '@nestjs/common';-import { In } from 'typeorm';+import { Equal, In, IsNull, Or } from 'typeorm';import { msg } from '@lingui/core/macro';+import { WorkflowVisibility } from 'twenty-shared/types';import { isDefined } from 'twenty-shared/utils';import { v4 as uuidv4 } from 'uuid';@@ -11,6 +12,7 @@ import { RecordPositionService } from 'src/engine/core-modules/record-position/simport { type CoreWorkflowDTO } from 'src/engine/core-modules/workflow/dtos/core-workflow.dto';import { type DeletedCoreWorkflowDTO } from 'src/engine/core-modules/workflow/dtos/deleted-core-workflow.dto';import { type DiscardCoreWorkflowDraftInput } from 'src/engine/core-modules/workflow/dtos/discard-core-workflow-draft.input';+import { type UpdateCoreWorkflowVisibilityInput } from 'src/engine/core-modules/workflow/dtos/update-core-workflow-visibility.input';import {WorkflowVersionEntity,WorkflowVersionStatus as CoreWorkflowVersionStatus,@@ -22,6 +24,7 @@ import { CoreWorkflowIdResolutionService } from 'src/engine/core-modules/workfloimport { CoreWorkflowListService } from 'src/engine/core-modules/workflow/services/core-workflow-list.service';import { CoreWorkflowVersionWriteService } from 'src/engine/core-modules/workflow/services/core-workflow-version-write.service';import { assertExactlyOneMirrorRowWasWritten } from 'src/engine/core-modules/workflow/utils/assert-exactly-one-mirror-row-was-written.util';+import { CoreWorkflowAccessService } from 'src/engine/core-modules/workflow/services/core-workflow-access.service';import { WorkflowCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-core-sync.service';import { WorkflowVersionCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-version-core-sync.service';import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';@@ -56,6 +59,7 @@ export class CoreWorkflowMutationWorkspaceService {private readonly workflowVersionCoreSyncService: WorkflowVersionCoreSyncService,private readonly workflowCommonWorkspaceService: WorkflowCommonWorkspaceService,private readonly coreWorkflowIdResolutionService: CoreWorkflowIdResolutionService,+ private readonly coreWorkflowAccessService: CoreWorkflowAccessService,private readonly commandMenuItemService: CommandMenuItemService,private readonly coreWorkflowListService: CoreWorkflowListService,private readonly coreWorkflowVersionWriteService: CoreWorkflowVersionWriteService,@@ -68,18 +72,32 @@ export class CoreWorkflowMutationWorkspaceService {async duplicateWorkflow({workspaceId,+ userWorkspaceId,user,coreWorkflowIdToDuplicate,coreWorkflowVersionIdToCopy,}: {workspaceId: string;+ userWorkspaceId: string | undefined;user: AuthContextUser;coreWorkflowIdToDuplicate: string;coreWorkflowVersionIdToCopy: string;}): Promise<CoreWorkflowDTO> {+ await this.coreWorkflowAccessService.assertCoreWorkflowsAreAccessibleOrThrow(+ {+ workspaceId,+ userWorkspaceId,+ coreWorkflowIds: [coreWorkflowIdToDuplicate],+ },+ );+const { coreWorkflow: sourceCoreWorkflow } =await this.coreWorkflowIdResolutionService.resolveWorkspaceWorkflowIdOrThrow(- { workspaceId, coreWorkflowId: coreWorkflowIdToDuplicate },+ {+ workspaceId,+ userWorkspaceId,+ coreWorkflowId: coreWorkflowIdToDuplicate,+ },);const sourceVersion = await this.coreWorkflowVersionRepository.findOne(@@ -111,20 +129,28 @@ export class CoreWorkflowMutationWorkspaceService {steps: sourceVersion.steps ?? [],});- const duplicatedWorkflow = await this.createWorkflow(workspaceId, user, {+ const duplicatedWorkflow = await this.createWorkflow({+ workspaceId,+ userWorkspaceId,+ user,name: `${sourceCoreWorkflow.name ?? ''} (Duplicate)`,+ // duplicating a private workflow must not publish it to the workspace+ visibility: sourceCoreWorkflow.visibility,});try {return await this.writeDuplicatedContentAndReturn({workspaceId,+ userWorkspaceId,duplicatedCoreWorkflowId: duplicatedWorkflow.id,trigger: remappedTrigger,steps: remappedSteps,});} catch (error) {try {- await this.deleteWorkflows(workspaceId, {+ await this.deleteWorkflows({+ workspaceId,+ userWorkspaceId,coreWorkflowIds: [duplicatedWorkflow.id],});} catch (cleanupError) {@@ -137,11 +163,13 @@ export class CoreWorkflowMutationWorkspaceService {private async writeDuplicatedContentAndReturn({workspaceId,+ userWorkspaceId,duplicatedCoreWorkflowId,trigger,steps,}: {workspaceId: string;+ userWorkspaceId: string | undefined;duplicatedCoreWorkflowId: string;trigger: NonNullable<WorkflowVersionEntity['triggers']>[number];steps: WorkflowAction[];@@ -177,6 +205,7 @@ export class CoreWorkflowMutationWorkspaceService {const duplicatedCoreWorkflow =await this.coreWorkflowListService.findOneById({workspaceId,+ userWorkspaceId,coreWorkflowId: duplicatedCoreWorkflowId,});@@ -226,13 +255,28 @@ export class CoreWorkflowMutationWorkspaceService {});}- async updateWorkflow(- workspaceId: string,- { coreWorkflowId, name }: { coreWorkflowId: string; name: string },- ): Promise<void> {+ async updateWorkflow({+ workspaceId,+ userWorkspaceId,+ coreWorkflowId,+ name,+ }: {+ workspaceId: string;+ userWorkspaceId: string | undefined;+ coreWorkflowId: string;+ name: string;+ }): Promise<void> {+ await this.coreWorkflowAccessService.assertCoreWorkflowsAreAccessibleOrThrow(+ {+ workspaceId,+ userWorkspaceId,+ coreWorkflowIds: [coreWorkflowId],+ },+ );+const { workspaceWorkflowId } =await this.coreWorkflowIdResolutionService.resolveWorkspaceWorkflowIdOrThrow(- { workspaceId, coreWorkflowId },+ { workspaceId, userWorkspaceId, coreWorkflowId },);await this.workspaceOrmManager.executeInWorkspaceContext(async () => {@@ -308,11 +352,19 @@ export class CoreWorkflowMutationWorkspaceService {);}- async createWorkflow(- workspaceId: string,- user: AuthContextUser,- { name }: { name?: string },- ): Promise<CoreWorkflowDTO> {+ async createWorkflow({+ workspaceId,+ userWorkspaceId,+ user,+ name,+ visibility,+ }: {+ workspaceId: string;+ userWorkspaceId: string | undefined;+ user: AuthContextUser;+ name?: string;+ visibility?: WorkflowVisibility;+ }): Promise<CoreWorkflowDTO> {const applicationId =await this.workflowCoreSyncService.getCustomApplicationIdOrThrow(workspaceId,@@ -343,6 +395,8 @@ export class CoreWorkflowMutationWorkspaceService {universalIdentifier: uuidv4(),applicationId,workspaceWorkflowId,+ visibility: visibility ?? WorkflowVisibility.WORKSPACE,+ createdByUserWorkspaceId: userWorkspaceId,},);@@ -403,15 +457,30 @@ export class CoreWorkflowMutationWorkspaceService {lastPublishedVersionId: null,applicationId,workspaceWorkflowId,+ visibility: coreWorkflow.visibility,+ canChangeVisibility: true,createdAt: coreWorkflow.createdAt.toISOString(),updatedAt: coreWorkflow.updatedAt.toISOString(),};}- async deleteWorkflows(- workspaceId: string,- { coreWorkflowIds }: { coreWorkflowIds: string[] },- ): Promise<DeletedCoreWorkflowDTO[]> {+ async deleteWorkflows({+ workspaceId,+ userWorkspaceId,+ coreWorkflowIds,+ }: {+ workspaceId: string;+ userWorkspaceId: string | undefined;+ coreWorkflowIds: string[];+ }): Promise<DeletedCoreWorkflowDTO[]> {+ await this.coreWorkflowAccessService.assertCoreWorkflowsAreAccessibleOrThrow(+ {+ workspaceId,+ userWorkspaceId,+ coreWorkflowIds,+ },+ );+const coreWorkflowsToDelete = await this.coreWorkflowRepository.find(workspaceId,{@@ -498,13 +567,15 @@ export class CoreWorkflowMutationWorkspaceService {);}- async discardDraftVersion(- workspaceId: string,- {- workspaceWorkflowVersionId,- coreWorkflowVersionId,- }: DiscardCoreWorkflowDraftInput,- ): Promise<string | null> {+ async discardDraftVersion({+ workspaceId,+ userWorkspaceId,+ workspaceWorkflowVersionId,+ coreWorkflowVersionId,+ }: DiscardCoreWorkflowDraftInput & {+ workspaceId: string;+ userWorkspaceId: string | undefined;+ }): Promise<string | null> {if (isDefined(workspaceWorkflowVersionId) &&isDefined(coreWorkflowVersionId)@@ -556,6 +627,14 @@ export class CoreWorkflowMutationWorkspaceService {);}+ await this.coreWorkflowAccessService.assertCoreWorkflowsAreAccessibleOrThrow(+ {+ workspaceId,+ userWorkspaceId,+ coreWorkflowIds: [coreVersion.coreWorkflowId],+ },+ );+const siblingCount = await this.coreWorkflowVersionRepository.count(workspaceId,{ where: { coreWorkflowId: coreVersion.coreWorkflowId } },@@ -654,6 +733,65 @@ export class CoreWorkflowMutationWorkspaceService {}, buildSystemAuthContext(workspaceId));}+ // Owning a workflow means being a person, so this one keeps a strict reader+ async updateWorkflowVisibility({+ workspaceId,+ userWorkspaceId,+ coreWorkflowId,+ visibility,+ }: UpdateCoreWorkflowVisibilityInput & {+ workspaceId: string;+ userWorkspaceId: string;+ }): Promise<CoreWorkflowDTO | null> {+ await this.coreWorkflowAccessService.assertCoreWorkflowsAreAccessibleOrThrow(+ {+ workspaceId,+ userWorkspaceId,+ coreWorkflowIds: [coreWorkflowId],+ },+ );++ // Workflows that predate this column have no owner, and the first member to+ // set a visibility claims one. The ownership test is the UPDATE's own WHERE+ // rather than a preceding read, so two members claiming at the same moment+ // cannot both pass it and have the later write silently take the workflow.+ // A workspace-visible workflow is already editable and deletable by every+ // member, so claiming one grants no access the claimer did not have.+ const claimResult = await this.coreWorkflowRepository.update(+ workspaceId,+ {+ id: coreWorkflowId,+ createdByUserWorkspaceId: Or(IsNull(), Equal(userWorkspaceId)),+ },+ { visibility, createdByUserWorkspaceId: userWorkspaceId },+ );++ if (claimResult.affected === 0) {+ const coreWorkflowExists = await this.coreWorkflowRepository.exists(+ workspaceId,+ { where: { id: coreWorkflowId } },+ );++ if (!coreWorkflowExists) {+ return null;+ }++ throw new WorkflowQueryValidationException(+ `Core workflow '${coreWorkflowId}' can only have its visibility changed by its creator`,+ WorkflowQueryValidationExceptionCode.FORBIDDEN,+ {+ userFriendlyMessage: msg`Only the person who created this workflow can change who sees it`,+ },+ );+ }++ return this.coreWorkflowListService.findOneById({+ workspaceId,+ userWorkspaceId,+ coreWorkflowId,+ });+ }+private async rollbackCreatedWorkflow(workspaceId: string,coreWorkflowId: string,diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-list.service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-list.service.tsindex 290ed264474..175144fe070 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-list.service.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-list.service.ts@@ -7,6 +7,7 @@ import { DataSource } from 'typeorm';import { WorkflowVersionEntity } from 'src/engine/core-modules/workflow/entities/workflow-version.entity';import { WorkflowEntity } from 'src/engine/core-modules/workflow/entities/workflow.entity';import { type CoreWorkflowVersionDTO } from 'src/engine/core-modules/workflow/dtos/core-workflow-version.dto';+import { CoreWorkflowAccessService } from 'src/engine/core-modules/workflow/services/core-workflow-access.service';import { buildCoreWorkflowVersionLabel } from 'src/engine/core-modules/workflow/utils/build-core-workflow-version-label.util';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';@@ -20,15 +21,34 @@ export class CoreWorkflowVersionListService {private readonly coreWorkflowRepository: WorkspaceScopedRepository<WorkflowEntity>,@InjectDataSource()private readonly coreDataSource: DataSource,+ private readonly coreWorkflowAccessService: CoreWorkflowAccessService,) {}async findManyByWorkspaceWorkflowId({workspaceId,+ userWorkspaceId,workspaceWorkflowId,}: {workspaceId: string;+ userWorkspaceId: string | undefined;workspaceWorkflowId: string;}): Promise<CoreWorkflowVersionDTO[]> {+ const parentCoreWorkflow = await this.coreWorkflowRepository.findOne(+ workspaceId,+ { where: { workspaceWorkflowId }, select: { id: true } },+ );++ if (+ isDefined(parentCoreWorkflow) &&+ !(await this.coreWorkflowAccessService.isCoreWorkflowAccessible({+ workspaceId,+ userWorkspaceId,+ coreWorkflowId: parentCoreWorkflow.id,+ }))+ ) {+ return [];+ }+const coreWorkflowVersions = await this.coreWorkflowVersionRepository.find(workspaceId,{@@ -64,9 +84,11 @@ export class CoreWorkflowVersionListService {async findOneByWorkspaceWorkflowVersionId({workspaceId,+ userWorkspaceId,workspaceWorkflowVersionId,}: {workspaceId: string;+ userWorkspaceId: string | undefined;workspaceWorkflowVersionId: string;}): Promise<CoreWorkflowVersionDTO | null> {const coreWorkflowVersion =@@ -81,15 +103,18 @@ export class CoreWorkflowVersionListService {return this.findOneByCoreWorkflowVersionId({workspaceId,+ userWorkspaceId,coreWorkflowVersionId: coreWorkflowVersion.id,});}async findManyByCoreWorkflowId({workspaceId,+ userWorkspaceId,coreWorkflowId,}: {workspaceId: string;+ userWorkspaceId: string | undefined;coreWorkflowId: string;}): Promise<CoreWorkflowVersionDTO[]> {const coreWorkflow = await this.coreWorkflowRepository.findOne(@@ -104,6 +129,10 @@ export class CoreWorkflowVersionListService {return [];}+ await this.coreWorkflowAccessService.assertCoreWorkflowsAreAccessibleOrThrow(+ { workspaceId, userWorkspaceId, coreWorkflowIds: [coreWorkflowId] },+ );+const coreWorkflowVersions = await this.coreWorkflowVersionRepository.find(workspaceId,{@@ -139,9 +168,11 @@ export class CoreWorkflowVersionListService {async findOneByCoreWorkflowVersionId({workspaceId,+ userWorkspaceId,coreWorkflowVersionId,}: {workspaceId: string;+ userWorkspaceId: string | undefined;coreWorkflowVersionId: string;}): Promise<CoreWorkflowVersionDTO | null> {const coreWorkflowVersion =@@ -153,6 +184,14 @@ export class CoreWorkflowVersionListService {return null;}+ await this.coreWorkflowAccessService.assertCoreWorkflowsAreAccessibleOrThrow(+ {+ workspaceId,+ userWorkspaceId,+ coreWorkflowIds: [coreWorkflowVersion.coreWorkflowId],+ },+ );+const coreWorkflow = await this.coreWorkflowRepository.findOne(workspaceId,{diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-mutation.workspace-service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-mutation.workspace-service.tsindex a6fd26c4ff9..78324f18af7 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-mutation.workspace-service.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-mutation.workspace-service.ts@@ -66,9 +66,11 @@ export class CoreWorkflowVersionMutationWorkspaceService {async createStep({workspaceId,+ userWorkspaceId,input,}: {workspaceId: string;+ userWorkspaceId: string | undefined;input: CreateCoreWorkflowVersionStepInput;}): Promise<WorkflowVersionStepChangesDTO> {const {@@ -84,7 +86,7 @@ export class CoreWorkflowVersionMutationWorkspaceService {const { coreWorkflowVersion, trigger, steps } =await this.coreWorkflowVersionWriteService.getValidatedDraftCoreWorkflowVersion(- { workspaceId, coreWorkflowVersionId },+ { workspaceId, userWorkspaceId, coreWorkflowVersionId },);const { builtStep, additionalCreatedSteps } =@@ -133,16 +135,18 @@ export class CoreWorkflowVersionMutationWorkspaceService {async duplicateStep({workspaceId,+ userWorkspaceId,coreWorkflowVersionId,stepId,}: {workspaceId: string;+ userWorkspaceId: string | undefined;coreWorkflowVersionId: string;stepId: string;}): Promise<WorkflowVersionStepChangesDTO> {const { coreWorkflowVersion, trigger, steps } =await this.coreWorkflowVersionWriteService.getValidatedDraftCoreWorkflowVersion(- { workspaceId, coreWorkflowVersionId },+ { workspaceId, userWorkspaceId, coreWorkflowVersionId },);const stepToDuplicate = steps?.find((step) => step.id === stepId);@@ -189,16 +193,18 @@ export class CoreWorkflowVersionMutationWorkspaceService {async updateStep({workspaceId,+ userWorkspaceId,coreWorkflowVersionId,step,}: {workspaceId: string;+ userWorkspaceId: string | undefined;coreWorkflowVersionId: string;step: WorkflowAction;}): Promise<WorkflowActionDTO> {const { coreWorkflowVersion, trigger, steps } =await this.coreWorkflowVersionWriteService.getValidatedDraftCoreWorkflowVersion(- { workspaceId, coreWorkflowVersionId },+ { workspaceId, userWorkspaceId, coreWorkflowVersionId },);if (!isDefined(steps)) {@@ -290,16 +296,18 @@ export class CoreWorkflowVersionMutationWorkspaceService {async updateTrigger({workspaceId,+ userWorkspaceId,coreWorkflowVersionId,trigger,}: {workspaceId: string;+ userWorkspaceId: string | undefined;coreWorkflowVersionId: string;trigger: WorkflowTrigger;}): Promise<WorkflowVersionTriggerDTO> {const { coreWorkflowVersion, steps } =await this.coreWorkflowVersionWriteService.getValidatedDraftCoreWorkflowVersion(- { workspaceId, coreWorkflowVersionId },+ { workspaceId, userWorkspaceId, coreWorkflowVersionId },);await this.coreWorkflowVersionWriteService.writeContentAndMirror({@@ -315,16 +323,18 @@ export class CoreWorkflowVersionMutationWorkspaceService {async deleteStep({workspaceId,+ userWorkspaceId,coreWorkflowVersionId,stepIdToDelete,}: {workspaceId: string;+ userWorkspaceId: string | undefined;coreWorkflowVersionId: string;stepIdToDelete: string;}): Promise<WorkflowVersionStepChangesDTO> {const { coreWorkflowVersion, trigger, steps } =await this.coreWorkflowVersionWriteService.getValidatedDraftCoreWorkflowVersion(- { workspaceId, coreWorkflowVersionId },+ { workspaceId, userWorkspaceId, coreWorkflowVersionId },);const isDeletingTrigger =@@ -389,12 +399,14 @@ export class CoreWorkflowVersionMutationWorkspaceService {async createEdge({workspaceId,+ userWorkspaceId,coreWorkflowVersionId,source,target,sourceConnectionOptions,}: {workspaceId: string;+ userWorkspaceId: string | undefined;coreWorkflowVersionId: string;source: string;target: string;@@ -405,6 +417,7 @@ export class CoreWorkflowVersionMutationWorkspaceService {const { coreWorkflowVersion, trigger, steps } =await this.getValidatedDraftWithTargetStep({workspaceId,+ userWorkspaceId,coreWorkflowVersionId,target,});@@ -489,12 +502,14 @@ export class CoreWorkflowVersionMutationWorkspaceService {async deleteEdge({workspaceId,+ userWorkspaceId,coreWorkflowVersionId,source,target,sourceConnectionOptions,}: {workspaceId: string;+ userWorkspaceId: string | undefined;coreWorkflowVersionId: string;source: string;target: string;@@ -505,6 +520,7 @@ export class CoreWorkflowVersionMutationWorkspaceService {const { coreWorkflowVersion, trigger, steps } =await this.getValidatedDraftWithTargetStep({workspaceId,+ userWorkspaceId,coreWorkflowVersionId,target,});@@ -598,16 +614,18 @@ export class CoreWorkflowVersionMutationWorkspaceService {async updatePositions({workspaceId,+ userWorkspaceId,coreWorkflowVersionId,positions,}: {workspaceId: string;+ userWorkspaceId: string | undefined;coreWorkflowVersionId: string;positions: WorkflowStepPositionUpdateInput[];}): Promise<void> {const { coreWorkflowVersion, trigger, steps } =await this.coreWorkflowVersionWriteService.getValidatedDraftCoreWorkflowVersion(- { workspaceId, coreWorkflowVersionId },+ { workspaceId, userWorkspaceId, coreWorkflowVersionId },);const triggerPosition = positions.find(@@ -641,16 +659,18 @@ export class CoreWorkflowVersionMutationWorkspaceService {@WithLock('coreWorkflowId')async createDraftFromCoreWorkflowVersion({workspaceId,+ userWorkspaceId,coreWorkflowId,coreWorkflowVersionIdToCopy,}: {workspaceId: string;+ userWorkspaceId: string | undefined;coreWorkflowId: string;coreWorkflowVersionIdToCopy: string;}): Promise<CoreWorkflowVersionDTO> {const { coreWorkflow, workspaceWorkflowId } =await this.coreWorkflowIdResolutionService.resolveWorkspaceWorkflowIdOrThrow(- { workspaceId, coreWorkflowId },+ { workspaceId, userWorkspaceId, coreWorkflowId },);const versionToCopy = await this.coreWorkflowVersionRepository.findOne(@@ -706,6 +726,7 @@ export class CoreWorkflowVersionMutationWorkspaceService {return this.findCoreVersionDTOOrThrow({workspaceId,+ userWorkspaceId,coreWorkflowVersionId: existingDraft.id,});}@@ -729,6 +750,7 @@ export class CoreWorkflowVersionMutationWorkspaceService {return this.findCoreVersionDTOOrThrow({workspaceId,+ userWorkspaceId,coreWorkflowVersionId,});}@@ -780,16 +802,18 @@ export class CoreWorkflowVersionMutationWorkspaceService {private async getValidatedDraftWithTargetStep({workspaceId,+ userWorkspaceId,coreWorkflowVersionId,target,}: {workspaceId: string;+ userWorkspaceId: string | undefined;coreWorkflowVersionId: string;target: string;}) {const validatedDraft =await this.coreWorkflowVersionWriteService.getValidatedDraftCoreWorkflowVersion(- { workspaceId, coreWorkflowVersionId },+ { workspaceId, userWorkspaceId, coreWorkflowVersionId },);const targetStep = validatedDraft.steps?.find((step) => step.id === target);@@ -827,14 +851,17 @@ export class CoreWorkflowVersionMutationWorkspaceService {private async findCoreVersionDTOOrThrow({workspaceId,+ userWorkspaceId,coreWorkflowVersionId,}: {workspaceId: string;+ userWorkspaceId: string | undefined;coreWorkflowVersionId: string;}): Promise<CoreWorkflowVersionDTO> {const coreWorkflowVersion =await this.coreWorkflowVersionListService.findOneByCoreWorkflowVersionId({workspaceId,+ userWorkspaceId,coreWorkflowVersionId,});diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-write.service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-write.service.tsindex ca5f875a186..460c7f04571 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-write.service.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-write.service.ts@@ -11,6 +11,7 @@ import {} from 'src/engine/core-modules/workflow/entities/workflow-version.entity';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 { CoreWorkflowAccessService } from 'src/engine/core-modules/workflow/services/core-workflow-access.service';import { WorkflowVersionCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-version-core-sync.service';import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';@@ -49,6 +50,7 @@ export class CoreWorkflowVersionWriteService {@InjectWorkspaceScopedRepository(WorkflowVersionEntity)private readonly coreWorkflowVersionRepository: WorkspaceScopedRepository<WorkflowVersionEntity>,private readonly workflowVersionCoreSyncService: WorkflowVersionCoreSyncService,+ private readonly coreWorkflowAccessService: CoreWorkflowAccessService,private readonly workflowMetadataReadService: WorkflowMetadataReadService,private readonly workspaceOrmManager: WorkspaceOrmManager,private readonly recordPositionService: RecordPositionService,@@ -56,11 +58,21 @@ export class CoreWorkflowVersionWriteService {async getValidatedDraftCoreWorkflowVersion({workspaceId,+ userWorkspaceId,coreWorkflowVersionId,}: {workspaceId: string;+ userWorkspaceId: string | undefined;coreWorkflowVersionId: string;}): Promise<ValidatedDraftCoreWorkflowVersion> {+ await this.coreWorkflowAccessService.assertCoreWorkflowVersionsAreAccessibleOrThrow(+ {+ workspaceId,+ userWorkspaceId,+ coreWorkflowVersionIds: [coreWorkflowVersionId],+ },+ );+const coreWorkflowVersion =await this.coreWorkflowVersionRepository.findOne(workspaceId, {where: { id: coreWorkflowVersionId },diff --git a/packages/twenty-server/src/engine/core-modules/workflow/utils/__tests__/build-core-workflow-visibility-where.util.spec.ts b/packages/twenty-server/src/engine/core-modules/workflow/utils/__tests__/build-core-workflow-visibility-where.util.spec.tsnew file mode 100644index 00000000000..5b17df34fb5--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/workflow/utils/__tests__/build-core-workflow-visibility-where.util.spec.ts@@ -0,0 +1,100 @@+import { WorkflowVisibility } from 'twenty-shared/types';+import { IsNull } from 'typeorm';++import { buildCoreWorkflowVisibilitySqlPredicate } from 'src/engine/core-modules/workflow/utils/build-core-workflow-visibility-sql-predicate.util';+import { buildCoreWorkflowVisibilityWhere } from 'src/engine/core-modules/workflow/utils/build-core-workflow-visibility-where.util';+import { canChangeCoreWorkflowVisibility } from 'src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility.util';+import { canChangeCoreWorkflowVisibilitySelectExpression } from 'src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility-select-expression.util';++const READER_USER_WORKSPACE_ID = '20202020-0000-0000-0000-000000000001';++describe('buildCoreWorkflowVisibilityWhere', () => {+ it('should let a reader see workspace workflows, their own and ownerless ones', () => {+ expect(+ buildCoreWorkflowVisibilityWhere({+ userWorkspaceId: READER_USER_WORKSPACE_ID,+ }),+ ).toEqual([+ { visibility: WorkflowVisibility.WORKSPACE },+ { createdByUserWorkspaceId: IsNull() },+ { createdByUserWorkspaceId: READER_USER_WORKSPACE_ID },+ ]);+ });++ it('should keep an API key out of everyone private workflows', () => {+ expect(+ buildCoreWorkflowVisibilityWhere({ userWorkspaceId: undefined }),+ ).toEqual([+ { visibility: WorkflowVisibility.WORKSPACE },+ { createdByUserWorkspaceId: IsNull() },+ ]);+ });++ it('should repeat the other conditions in both clauses', () => {+ const where = buildCoreWorkflowVisibilityWhere({+ userWorkspaceId: READER_USER_WORKSPACE_ID,+ applicationId: 'an-application-id',+ });++ expect(where).toHaveLength(3);++ for (const clause of where) {+ expect(clause).toMatchObject({ applicationId: 'an-application-id' });+ }+ });+});++describe('buildCoreWorkflowVisibilitySqlPredicate', () => {+ it('should read as one OR-ed fragment bound to the caller parameter', () => {+ expect(+ buildCoreWorkflowVisibilitySqlPredicate({+ tableAlias: 'c',+ userWorkspaceIdParameter: '$2',+ }),+ ).toBe(+ `(c."visibility" = 'WORKSPACE' OR (c."createdByUserWorkspaceId" IS NULL OR c."createdByUserWorkspaceId" = $2::uuid))`,+ );+ });+});++describe('canChangeCoreWorkflowVisibility', () => {+ it('should allow the creator and anyone when nobody owns it', () => {+ expect(+ canChangeCoreWorkflowVisibility({+ createdByUserWorkspaceId: READER_USER_WORKSPACE_ID,+ userWorkspaceId: READER_USER_WORKSPACE_ID,+ }),+ ).toBe(true);+ expect(+ canChangeCoreWorkflowVisibility({+ createdByUserWorkspaceId: null,+ userWorkspaceId: READER_USER_WORKSPACE_ID,+ }),+ ).toBe(true);+ expect(+ canChangeCoreWorkflowVisibility({+ createdByUserWorkspaceId: 'someone-else',+ userWorkspaceId: READER_USER_WORKSPACE_ID,+ }),+ ).toBe(false);+ expect(+ canChangeCoreWorkflowVisibility({+ createdByUserWorkspaceId: 'someone-else',+ userWorkspaceId: undefined,+ }),+ ).toBe(false);+ });+});++describe('canChangeCoreWorkflowVisibilitySelectExpression', () => {+ it('should never project NULL, which the predicate does for an API key', () => {+ expect(+ canChangeCoreWorkflowVisibilitySelectExpression({+ tableAlias: 'c',+ userWorkspaceIdParameter: '$2',+ }),+ ).toBe(+ `coalesce((c."createdByUserWorkspaceId" IS NULL OR c."createdByUserWorkspaceId" = $2::uuid), false)`,+ );+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/workflow/utils/build-core-workflow-visibility-sql-predicate.util.ts b/packages/twenty-server/src/engine/core-modules/workflow/utils/build-core-workflow-visibility-sql-predicate.util.tsnew file mode 100644index 00000000000..f11968a595c--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/workflow/utils/build-core-workflow-visibility-sql-predicate.util.ts@@ -0,0 +1,14 @@+import { WorkflowVisibility } from 'twenty-shared/types';++import { canChangeCoreWorkflowVisibilitySqlPredicate } from 'src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility-sql-predicate.util';++// The list query is raw SQL on a keyset index, so it needs the same rule as a+// fragment rather than a FindOptionsWhere.+export const buildCoreWorkflowVisibilitySqlPredicate = ({+ tableAlias,+ userWorkspaceIdParameter,+}: {+ tableAlias: string;+ userWorkspaceIdParameter: string;+}): string =>+ `(${tableAlias}."visibility" = '${WorkflowVisibility.WORKSPACE}' OR ${canChangeCoreWorkflowVisibilitySqlPredicate({ tableAlias, userWorkspaceIdParameter })})`;diff --git a/packages/twenty-server/src/engine/core-modules/workflow/utils/build-core-workflow-visibility-where.util.ts b/packages/twenty-server/src/engine/core-modules/workflow/utils/build-core-workflow-visibility-where.util.tsnew file mode 100644index 00000000000..bf1a8bf4961--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/workflow/utils/build-core-workflow-visibility-where.util.ts@@ -0,0 +1,30 @@+import { WorkflowVisibility } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';+import { IsNull, type FindOptionsWhere } from 'typeorm';++import { type WorkflowEntity } from 'src/engine/core-modules/workflow/entities/workflow.entity';++// A workflow is readable when the whole workspace can see it, when the reader+// is the person who made it, or when nobody owns it. That last branch matters:+// the owner FK is ON DELETE SET NULL, so a workflow whose creator left the+// workspace would otherwise be visible to no one and editable by no one while+// still running.+//+// The reader is absent for an API key, which authenticates a workspace rather+// than a person: it reaches everything the workspace shares and nobody's+// private workflow.+//+// The clauses are OR-ed by TypeORM, so any extra condition has to be repeated+// in each of them.+export const buildCoreWorkflowVisibilityWhere = ({+ userWorkspaceId,+ ...where+}: FindOptionsWhere<WorkflowEntity> & {+ userWorkspaceId: string | undefined;+}): FindOptionsWhere<WorkflowEntity>[] => [+ { ...where, visibility: WorkflowVisibility.WORKSPACE },+ { ...where, createdByUserWorkspaceId: IsNull() },+ ...(isDefined(userWorkspaceId)+ ? [{ ...where, createdByUserWorkspaceId: userWorkspaceId }]+ : []),+];diff --git a/packages/twenty-server/src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility-select-expression.util.ts b/packages/twenty-server/src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility-select-expression.util.tsnew file mode 100644index 00000000000..930cbd1c11c--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility-select-expression.util.ts@@ -0,0 +1,11 @@+import { canChangeCoreWorkflowVisibilitySqlPredicate } from 'src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility-sql-predicate.util';++// Selecting the predicate is not the same as filtering on it: an owned+// workflow read by an API key gives `false OR NULL`, which is NULL, and+// canChangeVisibility is a non-nullable GraphQL field. A WHERE clause treats+// that NULL as false already, a projection does not.+export const canChangeCoreWorkflowVisibilitySelectExpression = (parameters: {+ tableAlias: string;+ userWorkspaceIdParameter: string;+}): string =>+ `coalesce(${canChangeCoreWorkflowVisibilitySqlPredicate(parameters)}, false)`;diff --git a/packages/twenty-server/src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility-sql-predicate.util.ts b/packages/twenty-server/src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility-sql-predicate.util.tsnew file mode 100644index 00000000000..49f87dc911e--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility-sql-predicate.util.ts@@ -0,0 +1,11 @@+// The caller binds its own parameter for the reader, which is null for an API+// key — hence the explicit IS NULL rather than a coalesce, which would read a+// null reader as matching a null owner.+export const canChangeCoreWorkflowVisibilitySqlPredicate = ({+ tableAlias,+ userWorkspaceIdParameter,+}: {+ tableAlias: string;+ userWorkspaceIdParameter: string;+}): string =>+ `(${tableAlias}."createdByUserWorkspaceId" IS NULL OR ${tableAlias}."createdByUserWorkspaceId" = ${userWorkspaceIdParameter}::uuid)`;diff --git a/packages/twenty-server/src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility.util.ts b/packages/twenty-server/src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility.util.tsnew file mode 100644index 00000000000..c9e8535d5c7--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility.util.ts@@ -0,0 +1,14 @@+import { isDefined } from 'twenty-shared/utils';++// Whether the reader may hand this workflow to the workspace or keep it to+// themselves: they made it, or nobody did. The read rule in this directory has+// to agree with this about an ownerless workflow.+export const canChangeCoreWorkflowVisibility = ({+ createdByUserWorkspaceId,+ userWorkspaceId,+}: {+ createdByUserWorkspaceId: string | null;+ userWorkspaceId: string | undefined;+}): boolean =>+ !isDefined(createdByUserWorkspaceId) ||+ (isDefined(userWorkspaceId) && createdByUserWorkspaceId === userWorkspaceId);diff --git a/packages/twenty-server/src/engine/core-modules/workflow/workflow-api.module.ts b/packages/twenty-server/src/engine/core-modules/workflow/workflow-api.module.tsindex 18d892870ad..38baff09c01 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/workflow-api.module.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/workflow-api.module.ts@@ -16,6 +16,7 @@ import { WorkflowVersionStepResolver } from 'src/engine/core-modules/workflow/reimport { WorkflowVersionResolver } from 'src/engine/core-modules/workflow/resolvers/workflow-version.resolver';import { RecordPositionModule } from 'src/engine/core-modules/record-position/record-position.module';import { WorkflowEntity } from 'src/engine/core-modules/workflow/entities/workflow.entity';+import { CoreWorkflowAccessModule } from 'src/engine/core-modules/workflow/core-workflow-access.module';import { CoreWorkflowIdResolutionService } from 'src/engine/core-modules/workflow/services/core-workflow-id-resolution.service';import { CoreWorkflowLifecycleWorkspaceService } from 'src/engine/core-modules/workflow/services/core-workflow-lifecycle.workspace-service';import { CoreWorkflowListService } from 'src/engine/core-modules/workflow/services/core-workflow-list.service';@@ -51,6 +52,7 @@ import { WorkflowTriggerModule } from 'src/modules/workflow/workflow-trigger/worCacheLockModule,CacheStorageModule,CommandMenuItemModule,+ CoreWorkflowAccessModule,WorkflowCoreModule,WorkflowTriggerModule,WorkflowBuilderModule,diff --git a/packages/twenty-server/src/engine/metadata-modules/command-menu-item/command-menu-item.module.ts b/packages/twenty-server/src/engine/metadata-modules/command-menu-item/command-menu-item.module.tsindex 8ff52000e23..275bcfbf583 100644--- a/packages/twenty-server/src/engine/metadata-modules/command-menu-item/command-menu-item.module.ts+++ b/packages/twenty-server/src/engine/metadata-modules/command-menu-item/command-menu-item.module.ts@@ -3,6 +3,7 @@ import { Module } from '@nestjs/common';import { ApplicationModule } from 'src/engine/core-modules/application/application.module';import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';import { I18nModule } from 'src/engine/core-modules/i18n/i18n.module';+import { CoreWorkflowAccessModule } from 'src/engine/core-modules/workflow/core-workflow-access.module';import { CommandMenuItemResolver } from 'src/engine/metadata-modules/command-menu-item/command-menu-item.resolver';import { FrontComponentModule } from 'src/engine/metadata-modules/front-component/front-component.module';import { CommandMenuItemService } from 'src/engine/metadata-modules/command-menu-item/command-menu-item.service';@@ -19,6 +20,7 @@ import { ApplicationTranslationCatalogModule } from 'src/engine/metadata-modulesWorkspaceManyOrAllFlatEntityMapsCacheModule,WorkspaceMigrationModule,ApplicationModule,+ CoreWorkflowAccessModule,FlatCommandMenuItemModule,FrontComponentModule,FeatureFlagModule,diff --git a/packages/twenty-server/src/engine/metadata-modules/command-menu-item/command-menu-item.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/command-menu-item/command-menu-item.resolver.tsindex 65d56756fbd..159801f616f 100644--- a/packages/twenty-server/src/engine/metadata-modules/command-menu-item/command-menu-item.resolver.ts+++ b/packages/twenty-server/src/engine/metadata-modules/command-menu-item/command-menu-item.resolver.ts@@ -12,8 +12,10 @@ import { isDefined } from 'twenty-shared/utils';import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';import { type I18nContext } from 'src/engine/core-modules/i18n/types/i18n-context.type';+import { CoreWorkflowAccessService } from 'src/engine/core-modules/workflow/services/core-workflow-access.service';import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';import { type IDataloaders } from 'src/engine/dataloaders/dataloader.interface';+import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';import { AllowSuspendedWorkspace } from 'src/engine/decorators/auth/allow-suspended-workspace.decorator';import { MetadataResolver } from 'src/engine/api/graphql/graphql-config/decorators/metadata-resolver.decorator';@@ -40,6 +42,7 @@ export class CommandMenuItemResolver {constructor(private readonly commandMenuItemService: CommandMenuItemService,private readonly frontComponentService: FrontComponentService,+ private readonly coreWorkflowAccessService: CoreWorkflowAccessService,) {}@ResolveField(() => String)@@ -111,18 +114,42 @@ export class CommandMenuItemResolver {@UseGuards(NoPermissionGuard)@AllowSuspendedWorkspace()async commandMenuItems(+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@AuthWorkspace() workspace: WorkspaceEntity,): Promise<CommandMenuItemDTO[]> {- return await this.commandMenuItemService.findAll(workspace.id);+ return await this.withoutInaccessibleWorkflowItems({+ commandMenuItems: await this.commandMenuItemService.findAll(workspace.id),+ workspaceId: workspace.id,+ userWorkspaceId,+ });}@Query(() => CommandMenuItemDTO, { nullable: true })@UseGuards(NoPermissionGuard)async commandMenuItem(@Args('id', { type: () => UUIDScalarType }) id: string,+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,@AuthWorkspace() workspace: WorkspaceEntity,): Promise<CommandMenuItemDTO | null> {- return await this.commandMenuItemService.findById(id, workspace.id);+ const commandMenuItem = await this.commandMenuItemService.findById(+ id,+ workspace.id,+ );++ if (!isDefined(commandMenuItem)) {+ return null;+ }++ const [accessibleCommandMenuItem] =+ await this.withoutInaccessibleWorkflowItems({+ commandMenuItems: [commandMenuItem],+ workspaceId: workspace.id,+ userWorkspaceId,+ });++ return accessibleCommandMenuItem ?? null;}@Mutation(() => CommandMenuItemDTO)@@ -160,4 +187,34 @@ export class CommandMenuItemResolver {): Promise<CommandMenuItemDTO> {return await this.commandMenuItemService.delete(id, workspace.id);}++ // Activating a manual trigger writes a workspace-wide menu item, so the+ // command menu announces a private workflow by name unless the list answers+ // to the same rule as the workflow itself.+ private async withoutInaccessibleWorkflowItems({+ commandMenuItems,+ workspaceId,+ userWorkspaceId,+ }: {+ commandMenuItems: CommandMenuItemDTO[];+ workspaceId: string;+ userWorkspaceId: string | undefined;+ }): Promise<CommandMenuItemDTO[]> {+ const inaccessibleWorkspaceWorkflowVersionIds =+ await this.coreWorkflowAccessService.findInaccessibleWorkspaceWorkflowVersionIds(+ {+ workspaceId,+ userWorkspaceId,+ workspaceWorkflowVersionIds: commandMenuItems+ .map(({ workflowVersionId }) => workflowVersionId)+ .filter(isDefined),+ },+ );++ return commandMenuItems.filter(+ ({ workflowVersionId }) =>+ !isDefined(workflowVersionId) ||+ !inaccessibleWorkspaceWorkflowVersionIds.has(workflowVersionId),+ );+ }}diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.tsnew file mode 100644index 00000000000..604a06f9fcb--- /dev/null+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts@@ -0,0 +1,628 @@+import { randomUUID } from 'node:crypto';++import request from 'supertest';+import { PermissionFlagType } from 'twenty-shared/constants';+import { WorkflowVisibility } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';++import { createOneRole } from 'test/integration/metadata/suites/role/utils/create-one-role.util';+import { deleteOneRole } from 'test/integration/metadata/suites/role/utils/delete-one-role.util';+import { findOneRoleByLabel } from 'test/integration/metadata/suites/role/utils/find-one-role-by-label.util';+import { updateWorkspaceMemberRole } from 'test/integration/metadata/suites/role/utils/update-workspace-member-role.util';+import { upsertPermissionFlags } from 'test/integration/metadata/suites/role-permission-flag/utils/upsert-permission-flags.util';+import { findCommandMenuItems } from 'test/integration/metadata/suites/command-menu-item/utils/find-command-menu-items.util';+import { pollWorkflowGraphqlRequest } from 'test/integration/graphql/suites/workflow/utils/poll-workflow-graphql-request.util';+import { updateWorkflowVersionTrigger } from 'test/integration/graphql/suites/workflow/utils/update-workflow-version-trigger.util';+import { workflowGraphqlRequest } from 'test/integration/graphql/suites/workflow/utils/workflow-graphql-request.util';++import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';++const client = request(`http://localhost:${APP_PORT}`);++const graphqlRequestAs = (+ accessToken: string,+ query: string,+ variables?: object,+) =>+ client+ .post('/graphql')+ .set('Authorization', `Bearer ${accessToken}`)+ .send({ query, variables });++const asOtherMember = (query: string, variables?: object) =>+ graphqlRequestAs(APPLE_JONY_MEMBER_ACCESS_TOKEN, query, variables);++const asApiKey = (query: string, variables?: object) =>+ graphqlRequestAs(API_KEY_ACCESS_TOKEN, query, variables);++const CORE_WORKFLOW_BY_ID_QUERY = `+ query CoreWorkflowById($coreWorkflowId: UUID!) {+ coreWorkflowById(coreWorkflowId: $coreWorkflowId) {+ id+ visibility+ canChangeVisibility+ }+ }+`;++const CORE_WORKFLOWS_QUERY = `+ query CoreWorkflows {+ coreWorkflows(first: 100) {+ edges {+ node {+ id+ }+ }+ }+ }+`;++const CORE_WORKFLOW_VERSION_QUERY = `+ query CoreWorkflowVersion($workspaceWorkflowVersionId: UUID!) {+ coreWorkflowVersion(+ workspaceWorkflowVersionId: $workspaceWorkflowVersionId+ ) {+ id+ steps+ }+ }+`;++const COMPUTE_STEP_OUTPUT_SCHEMA_MUTATION = `+ mutation ComputeStepOutputSchema($input: ComputeStepOutputSchemaInput!) {+ computeStepOutputSchema(input: $input)+ }+`;++const UPDATE_VISIBILITY_MUTATION = `+ mutation UpdateCoreWorkflowVisibility(+ $input: UpdateCoreWorkflowVisibilityInput!+ ) {+ updateCoreWorkflowVisibility(input: $input) {+ id+ visibility+ }+ }+`;++const LEGACY_RUN_MUTATION = `+ mutation RunWorkflowVersion($input: RunWorkflowVersionInput!) {+ runWorkflowVersion(input: $input) {+ workflowRunId+ }+ }+`;++const CREATE_CORE_WORKFLOW_MUTATION = `+ mutation CreateCoreWorkflow($input: CreateCoreWorkflowInput!) {+ createCoreWorkflow(input: $input) {+ id+ workspaceWorkflowId+ }+ }+`;++const ACTIVATE_VERSION_MUTATION = `+ mutation ActivateWorkflowVersion($workflowVersionId: UUID!) {+ activateWorkflowVersion(workflowVersionId: $workflowVersionId)+ }+`;++const setVisibility = (coreWorkflowId: string, visibility: WorkflowVisibility) =>+ workflowGraphqlRequest(UPDATE_VISIBILITY_MUTATION, {+ input: { coreWorkflowId, visibility },+ });++const listCoreWorkflowIds = async (+ requester: (query: string) => request.Test,+) => {+ const response = await requester(CORE_WORKFLOWS_QUERY);++ expect(response.body.errors).toBeUndefined();++ return response.body.data.coreWorkflows.edges.map(+ ({ node }: { node: { id: string } }) => node.id,+ );+};++describe('core workflow visibility (e2e)', () => {+ let workspaceWorkflowId: string;+ let coreWorkflowId: string;+ let workspaceWorkflowVersionId: string;+ let originalMemberRoleId: string;+ let workflowsRoleId: string;++ beforeAll(async () => {+ // The whole workflow API sits behind SettingsPermissionGuard(WORKFLOWS),+ // which the seeded Member role does not carry, so the second member has to+ // be someone who could reach the workflow if visibility allowed it.+ const memberRole = await findOneRoleByLabel({ label: 'Member' });++ originalMemberRoleId = memberRole.id;++ const { data: createdRole } = await createOneRole({+ expectToFail: false,+ input: {+ label: `Workflows-enabled member ${randomUUID()}`,+ description: 'Member plus the WORKFLOWS permission flag',+ icon: 'IconSettingsAutomation',+ canUpdateAllSettings: false,+ canAccessAllTools: true,+ canReadAllObjectRecords: true,+ canUpdateAllObjectRecords: true,+ canSoftDeleteAllObjectRecords: true,+ canDestroyAllObjectRecords: true,+ canBeAssignedToUsers: true,+ canBeAssignedToAgents: false,+ canBeAssignedToApiKeys: false,+ },+ });++ workflowsRoleId = createdRole.createOneRole.id;++ await upsertPermissionFlags({+ expectToFail: false,+ input: {+ roleId: workflowsRoleId,+ permissionFlagKeys: [PermissionFlagType.WORKFLOWS],+ },+ });++ await updateWorkspaceMemberRole({+ expectToFail: false,+ input: {+ roleId: workflowsRoleId,+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,+ },+ });++ const createResponse = await workflowGraphqlRequest(+ CREATE_CORE_WORKFLOW_MUTATION,+ { input: { name: 'Private Workflow Access' } },+ );++ expect(createResponse.body.errors).toBeUndefined();+ coreWorkflowId = createResponse.body.data.createCoreWorkflow.id;+ workspaceWorkflowId =+ createResponse.body.data.createCoreWorkflow.workspaceWorkflowId;++ const versions = await pollWorkflowGraphqlRequest<+ {+ coreWorkflowVersions: { workspaceWorkflowVersionId: string | null }[];+ },+ { workspaceWorkflowVersionId: string | null }[] | undefined+ >({+ query: `+ query CoreWorkflowVersions($workspaceWorkflowId: UUID!) {+ coreWorkflowVersions(workspaceWorkflowId: $workspaceWorkflowId) {+ workspaceWorkflowVersionId+ }+ }+ `,+ variables: { workspaceWorkflowId },+ extract: (data) => data?.coreWorkflowVersions,+ until: (coreWorkflowVersions) =>+ isDefined(coreWorkflowVersions?.[0]?.workspaceWorkflowVersionId),+ });++ workspaceWorkflowVersionId = versions![0].workspaceWorkflowVersionId!;+ });++ afterAll(async () => {+ if (isDefined(workspaceWorkflowId)) {+ await setVisibility(coreWorkflowId, WorkflowVisibility.WORKSPACE);+ await workflowGraphqlRequest(+ `+ mutation DestroyWorkflow($id: UUID!) {+ destroyWorkflow(id: $id) {+ id+ }+ }+ `,+ { id: workspaceWorkflowId },+ );+ }++ if (isDefined(workflowsRoleId)) {+ await updateWorkspaceMemberRole({+ expectToFail: false,+ input: {+ roleId: originalMemberRoleId,+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,+ },+ });+ await deleteOneRole({+ expectToFail: false,+ input: { idToDelete: workflowsRoleId },+ });+ }+ });++ describe('while the workflow is visible to the workspace', () => {+ it('lets another member read it', async () => {+ const response = await asOtherMember(CORE_WORKFLOW_BY_ID_QUERY, {+ coreWorkflowId,+ });++ expect(response.body.errors).toBeUndefined();+ expect(response.body.data.coreWorkflowById).toMatchObject({+ id: coreWorkflowId,+ visibility: 'WORKSPACE',+ });+ });++ it('tells another member they may not change the creator visibility', async () => {+ const response = await asOtherMember(CORE_WORKFLOW_BY_ID_QUERY, {+ coreWorkflowId,+ });++ expect(response.body.data.coreWorkflowById).toMatchObject({+ canChangeVisibility: false,+ });+ });+ });++ // Workflows predating the visibility column have no owner, and so does one+ // whose creator left the workspace, since the owner FK is ON DELETE SET NULL.+ // Without a claim they would be unreachable by everyone while still running.+ describe('an ownerless workflow', () => {+ let ownerlessWorkspaceWorkflowId: string;+ let ownerlessCoreWorkflowId: string;++ beforeAll(async () => {+ const createResponse = await workflowGraphqlRequest(`+ mutation {+ createWorkflow(data: { name: "Ownerless Workflow" }) {+ id+ }+ }+ `);++ expect(createResponse.body.errors).toBeUndefined();+ ownerlessWorkspaceWorkflowId = createResponse.body.data.createWorkflow.id;++ const coreWorkflow = await pollWorkflowGraphqlRequest<+ { coreWorkflow: { id: string } | null },+ { id: string } | null | undefined+ >({+ query: `+ query CoreWorkflow($workspaceWorkflowId: UUID!) {+ coreWorkflow(workspaceWorkflowId: $workspaceWorkflowId) {+ id+ }+ }+ `,+ variables: { workspaceWorkflowId: ownerlessWorkspaceWorkflowId },+ extract: (data) => data?.coreWorkflow,+ until: isDefined,+ });++ ownerlessCoreWorkflowId = coreWorkflow!.id;+ });++ afterAll(async () => {+ await workflowGraphqlRequest(+ `+ mutation DestroyWorkflow($id: UUID!) {+ destroyWorkflow(id: $id) {+ id+ }+ }+ `,+ { id: ownerlessWorkspaceWorkflowId },+ );+ });++ it('is claimable by any member who can already edit it', async () => {+ const response = await asOtherMember(CORE_WORKFLOW_BY_ID_QUERY, {+ coreWorkflowId: ownerlessCoreWorkflowId,+ });++ expect(response.body.errors).toBeUndefined();+ expect(response.body.data.coreWorkflowById).toMatchObject({+ canChangeVisibility: true,+ });+ });++ it('belongs to whoever claims it first, and only to them', async () => {+ const claim = await asOtherMember(UPDATE_VISIBILITY_MUTATION, {+ input: {+ coreWorkflowId: ownerlessCoreWorkflowId,+ visibility: WorkflowVisibility.WORKSPACE,+ },+ });++ expect(claim.body.errors).toBeUndefined();++ const asCreatorOfNothing = await workflowGraphqlRequest(+ CORE_WORKFLOW_BY_ID_QUERY,+ { coreWorkflowId: ownerlessCoreWorkflowId },+ );++ expect(asCreatorOfNothing.body.data.coreWorkflowById).toMatchObject({+ canChangeVisibility: false,+ });+ });++ // The claim is the UPDATE's own WHERE rather than a preceding read, so this+ // is what keeps two simultaneous claims from both passing.+ it('refuses a second claim even though the workflow is still workspace-visible', async () => {+ const secondClaim = await workflowGraphqlRequest(+ UPDATE_VISIBILITY_MUTATION,+ {+ input: {+ coreWorkflowId: ownerlessCoreWorkflowId,+ visibility: WorkflowVisibility.PRIVATE,+ },+ },+ );++ expect(secondClaim.body.errors).toBeDefined();++ const stillShared = await asOtherMember(CORE_WORKFLOW_BY_ID_QUERY, {+ coreWorkflowId: ownerlessCoreWorkflowId,+ });++ expect(stillShared.body.data.coreWorkflowById).toMatchObject({+ visibility: 'WORKSPACE',+ canChangeVisibility: true,+ });+ });+ });++ describe('once its creator makes it private', () => {+ beforeAll(async () => {+ const response = await setVisibility(+ coreWorkflowId,+ WorkflowVisibility.PRIVATE,+ );++ expect(response.body.errors).toBeUndefined();+ expect(response.body.data.updateCoreWorkflowVisibility).toMatchObject({+ visibility: 'PRIVATE',+ });+ });++ it('still lets its creator read it and change it back', async () => {+ const response = await workflowGraphqlRequest(CORE_WORKFLOW_BY_ID_QUERY, {+ coreWorkflowId,+ });++ expect(response.body.errors).toBeUndefined();+ expect(response.body.data.coreWorkflowById).toMatchObject({+ id: coreWorkflowId,+ visibility: 'PRIVATE',+ canChangeVisibility: true,+ });+ });++ it('refuses to resolve it for another member', async () => {+ const response = await asOtherMember(CORE_WORKFLOW_BY_ID_QUERY, {+ coreWorkflowId,+ });++ expect(response.body.data?.coreWorkflowById ?? null).toBeNull();+ });++ it('keeps it out of the other member list while leaving it in its creator list', async () => {+ expect(await listCoreWorkflowIds(asOtherMember)).not.toContain(+ coreWorkflowId,+ );+ expect(await listCoreWorkflowIds(workflowGraphqlRequest)).toContain(+ coreWorkflowId,+ );+ });++ // The versions carry the whole definition, so reaching one by id has to+ // answer to the same rule as reaching the workflow.+ it('refuses its version to another member', async () => {+ const response = await asOtherMember(CORE_WORKFLOW_VERSION_QUERY, {+ workspaceWorkflowVersionId,+ });++ expect(response.body.data?.coreWorkflowVersion ?? null).toBeNull();+ });++ // The builder resolver reads a version's content straight from its id to+ // compute a schema, so it hands out the whole definition unless it answers+ // to the same rule.+ it('refuses to compute a step output schema from its version for another member', async () => {+ const response = await asOtherMember(+ COMPUTE_STEP_OUTPUT_SCHEMA_MUTATION,+ {+ input: {+ step: { type: 'MANUAL', settings: { outputSchema: {} } },+ workflowVersionId: workspaceWorkflowVersionId,+ },+ },+ );++ expect(response.body.errors).toBeDefined();+ expect(response.body.data?.computeStepOutputSchema ?? null).toBeNull();+ });++ // The legacy resolver is keyed by the workspace mirror's ids and never+ // passes through CoreWorkflowIdResolutionService, so it needs the rule+ // reached from the other side or a held id still launches the workflow.+ it('refuses to run it from the legacy API for another member', async () => {+ const response = await asOtherMember(LEGACY_RUN_MUTATION, {+ input: { workflowVersionId: workspaceWorkflowVersionId },+ });++ expect(response.body.errors).toBeDefined();+ expect(response.body.data?.runWorkflowVersion ?? null).toBeNull();+ });++ // WorkflowTriggerResolver carries no class-level UserAuthGuard, so unlike+ // the core workflow API an API key does reach this mutation, and the rule+ // has to hold for a caller that is a workspace rather than a person.+ it('refuses to activate it for an API key', async () => {+ const response = await asApiKey(ACTIVATE_VERSION_MUTATION, {+ workflowVersionId: workspaceWorkflowVersionId,+ });++ expect(response.body.errors).toBeDefined();+ expect(response.body.data?.activateWorkflowVersion ?? null).toBeNull();+ });++ it('refuses to let another member publish it back to the workspace', async () => {+ const response = await asOtherMember(UPDATE_VISIBILITY_MUTATION, {+ input: {+ coreWorkflowId,+ visibility: WorkflowVisibility.WORKSPACE,+ },+ });++ expect(response.body.errors).toBeDefined();++ const stillPrivate = await workflowGraphqlRequest(+ CORE_WORKFLOW_BY_ID_QUERY,+ { coreWorkflowId },+ );++ expect(stillPrivate.body.data.coreWorkflowById).toMatchObject({+ visibility: 'PRIVATE',+ });+ });+ });++ // Activating a manual trigger writes a workspace-wide command menu item+ // carrying the workflow name, so the command menu is a second way to reach+ // the workflow and has to answer to the same rule.+ describe('a workflow with an active manual trigger', () => {+ let manualWorkspaceWorkflowId: string;+ let manualCoreWorkflowId: string;+ let manualWorkspaceWorkflowVersionId: string;++ const listCommandMenuItemWorkflowVersionIds = async (token: string) => {+ const { data } = await findCommandMenuItems({+ expectToFail: false,+ gqlFields: 'id workflowVersionId',+ input: undefined,+ token,+ });++ return data.commandMenuItems.map(+ ({ workflowVersionId }) => workflowVersionId,+ );+ };++ beforeAll(async () => {+ const createResponse = await workflowGraphqlRequest(+ CREATE_CORE_WORKFLOW_MUTATION,+ { input: { name: 'Manual Trigger Workflow' } },+ );++ expect(createResponse.body.errors).toBeUndefined();+ manualCoreWorkflowId = createResponse.body.data.createCoreWorkflow.id;+ manualWorkspaceWorkflowId =+ createResponse.body.data.createCoreWorkflow.workspaceWorkflowId;++ const versions = await pollWorkflowGraphqlRequest<+ {+ coreWorkflowVersions: { workspaceWorkflowVersionId: string | null }[];+ },+ { workspaceWorkflowVersionId: string | null }[] | undefined+ >({+ query: `+ query CoreWorkflowVersions($workspaceWorkflowId: UUID!) {+ coreWorkflowVersions(workspaceWorkflowId: $workspaceWorkflowId) {+ workspaceWorkflowVersionId+ }+ }+ `,+ variables: { workspaceWorkflowId: manualWorkspaceWorkflowId },+ extract: (data) => data?.coreWorkflowVersions,+ until: (coreWorkflowVersions) =>+ isDefined(coreWorkflowVersions?.[0]?.workspaceWorkflowVersionId),+ });++ manualWorkspaceWorkflowVersionId =+ versions![0].workspaceWorkflowVersionId!;++ await updateWorkflowVersionTrigger({+ workflowVersionId: manualWorkspaceWorkflowVersionId,+ trigger: {+ name: 'Manual Trigger',+ type: 'MANUAL',+ settings: { outputSchema: {} },+ nextStepIds: [],+ position: { x: 0, y: 0 },+ },+ });++ const stepResponse = await workflowGraphqlRequest(+ `+ mutation CreateWorkflowVersionStep(+ $input: CreateWorkflowVersionStepInput!+ ) {+ createWorkflowVersionStep(input: $input) {+ stepsDiff+ }+ }+ `,+ {+ input: {+ workflowVersionId: manualWorkspaceWorkflowVersionId,+ stepType: 'FIND_RECORDS',+ parentStepId: 'trigger',+ position: { x: 200, y: 0 },+ },+ },+ );++ expect(stepResponse.body.errors).toBeUndefined();++ const activateResponse = await workflowGraphqlRequest(+ ACTIVATE_VERSION_MUTATION,+ { workflowVersionId: manualWorkspaceWorkflowVersionId },+ );++ expect(activateResponse.body.errors).toBeUndefined();+ });++ afterAll(async () => {+ if (isDefined(manualWorkspaceWorkflowId)) {+ await setVisibility(manualCoreWorkflowId, WorkflowVisibility.WORKSPACE);+ await workflowGraphqlRequest(+ `+ mutation DestroyWorkflow($id: UUID!) {+ destroyWorkflow(id: $id) {+ id+ }+ }+ `,+ { id: manualWorkspaceWorkflowId },+ );+ }+ });++ it('puts its command menu item in every member command menu', async () => {+ expect(+ await listCommandMenuItemWorkflowVersionIds(+ APPLE_JONY_MEMBER_ACCESS_TOKEN,+ ),+ ).toContain(manualWorkspaceWorkflowVersionId);+ });++ it('takes the item out of the other member command menu once private, and leaves it in its creator one', async () => {+ const response = await setVisibility(+ manualCoreWorkflowId,+ WorkflowVisibility.PRIVATE,+ );++ expect(response.body.errors).toBeUndefined();++ expect(+ await listCommandMenuItemWorkflowVersionIds(+ APPLE_JONY_MEMBER_ACCESS_TOKEN,+ ),+ ).not.toContain(manualWorkspaceWorkflowVersionId);+ expect(+ await listCommandMenuItemWorkflowVersionIds(+ APPLE_JANE_ADMIN_ACCESS_TOKEN,+ ),+ ).toContain(manualWorkspaceWorkflowVersionId);+ });+ });+});diff --git a/packages/twenty-shared/src/types/WorkflowVisibility.ts b/packages/twenty-shared/src/types/WorkflowVisibility.tsnew file mode 100644index 00000000000..90abeff8c7b--- /dev/null+++ b/packages/twenty-shared/src/types/WorkflowVisibility.ts@@ -0,0 +1,4 @@+export enum WorkflowVisibility {+ WORKSPACE = 'WORKSPACE',+ PRIVATE = 'PRIVATE',+}diff --git a/packages/twenty-shared/src/types/index.ts b/packages/twenty-shared/src/types/index.tsindex 6e2dbc4e68b..f5b6dd10398 100644--- a/packages/twenty-shared/src/types/index.ts+++ b/packages/twenty-shared/src/types/index.ts@@ -341,3 +341,4 @@ export { ViewType } from './ViewType';export { ViewVisibility } from './ViewVisibility';export { WebhookSubscriptionChannelType } from './WebhookSubscriptionChannelType';export { WebhookSubscriptionStatus } from './WebhookSubscriptionStatus';+export { WorkflowVisibility } from './WorkflowVisibility';