Skip to content

The open alternative to Salesforce, designed for AI.

Allow development application on top of owned application (#25267)

martmullc30828516744
diff --git a/packages/twenty-docs/developers/extend/apps/config/application.mdx b/packages/twenty-docs/developers/extend/apps/config/application.mdx
index e767be1a9ee..371265a8c4c 100644
--- a/packages/twenty-docs/developers/extend/apps/config/application.mdx
+++ b/packages/twenty-docs/developers/extend/apps/config/application.mdx
@@ -32,7 +32,7 @@ export default defineApplication({
```
Notes:
-- `universalIdentifier` fields are deterministic IDs you own. Generate them once and keep them stable across syncs.
+- `universalIdentifier` fields are deterministic IDs you own. Generate them once and keep them stable across syncs. The application's own `universalIdentifier` is unique across the whole instance and is bound to the workspace that owns its registration, so only that workspace can sync the app — see [Registration ownership](/developers/extend/apps/operations/publishing#registration-ownership).
- `applicationVariables` accept an optional `label` — a user-friendly name displayed in the app's settings page instead of the raw variable key.
- `applicationVariables` become environment variables for your functions and front components. In logic functions (server-side), they are available as `process.env.VARIABLE_NAME`. In front components, use `getApplicationVariable('VARIABLE_NAME')` from `twenty-sdk/front-component`. Variables marked with `isSecret: true` are only injected into logic functions. Front components receive only non-secret variables.
- The default role is detected automatically from the role file marked with [`defineApplicationRole()`](/developers/extend/apps/config/roles) — you do not need to reference it from `defineApplication()`.
diff --git a/packages/twenty-docs/developers/extend/apps/getting-started/quick-start.mdx b/packages/twenty-docs/developers/extend/apps/getting-started/quick-start.mdx
index 7f7ade4f4fd..175d3ab9bc4 100644
--- a/packages/twenty-docs/developers/extend/apps/getting-started/quick-start.mdx
+++ b/packages/twenty-docs/developers/extend/apps/getting-started/quick-start.mdx
@@ -118,6 +118,10 @@ yarn twenty apply # show the plan, then apply it
All modes need an authenticated remote. See [Syncing & recovery](/developers/extend/apps/operations/sync-and-recovery#previewing-changes-plan) for more on `plan`.
+<Note>
+All three modes require your workspace to own the app's registration. The sync is refused when the `universalIdentifier` from your app config is registered to another workspace, or to no workspace yet — apps imported from the marketplace catalog start unowned and have to be claimed first. See [Registration ownership](/developers/extend/apps/operations/publishing#registration-ownership).
+</Note>
+
<Note>
`yarn twenty dev --once` and `yarn twenty dev --once --dry-run` are deprecated aliases for `yarn twenty apply` and `yarn twenty plan`.
</Note>
diff --git a/packages/twenty-docs/developers/extend/apps/operations/publishing.mdx b/packages/twenty-docs/developers/extend/apps/operations/publishing.mdx
index a03d1acea6f..61a1cd83f80 100644
--- a/packages/twenty-docs/developers/extend/apps/operations/publishing.mdx
+++ b/packages/twenty-docs/developers/extend/apps/operations/publishing.mdx
@@ -13,6 +13,24 @@ Once your app is [built and tested locally](/developers/extend/apps/getting-star
Both paths start from the same **build** step.
+## Registration ownership
+
+Publishing an app creates an **application registration**: the app's identity on the instance, shared by every workspace that installs it. It holds the app's marketplace entry, its OAuth client, and its server-side state — the `serverVariables` an operator configures and the `server`-scoped entries of the [key-value store](/developers/extend/apps/logic/key-value-store).
+
+A `universalIdentifier` is unique across the whole instance and a registration belongs to at most one workspace (its owner) — or none until it is claimed — so installing an app and developing one are two different rights:
+
+| Action | Requirement |
+|--------|-------------|
+| Installing an app | The app is listed on the marketplace, pre-installed by the operator, or its registration belongs to your workspace. |
+| Developing an app (`yarn twenty dev`, `apply`, `plan`) | The registration belongs to your workspace. |
+
+Syncing code and a manifest under an identifier is a claim of authorship, so being able to install an app never grants the right to publish code under its identity. A workspace that is not the owner is refused, whether the app is listed, pre-installed, or private.
+
+Two situations lead to that refusal:
+
+- **The identifier belongs to another workspace.** Change the `universalIdentifier` in your app config, which is the usual answer when you forked someone else's app. If you need to keep the identifier, the owning workspace has to transfer the registration to yours.
+- **The identifier belongs to no workspace.** Apps imported by the marketplace catalog sync start unowned. Claim yours through npm trusted publishing before developing on it.
+
## Building your app
Run the build command to compile your app and generate a distribution-ready `manifest.json`:
diff --git a/packages/twenty-docs/developers/extend/apps/operations/sync-and-recovery.mdx b/packages/twenty-docs/developers/extend/apps/operations/sync-and-recovery.mdx
index c38f1cdcb8a..5abda50f810 100644
--- a/packages/twenty-docs/developers/extend/apps/operations/sync-and-recovery.mdx
+++ b/packages/twenty-docs/developers/extend/apps/operations/sync-and-recovery.mdx
@@ -123,6 +123,7 @@ The server serializes syncs per workspace to prevent this, but you should still
When something goes wrong, the metadata diff and named errors let you place the failure:
- **Manifest build error** — the CLI fails before syncing (`MANIFEST_BUILD_FAILED`, `TYPECHECK_FAILED`); fix your app source.
+- **Registration ownership error** — the sync is refused because the app's `universalIdentifier` belongs to another workspace, or to no workspace at all; see [Registration ownership](/developers/extend/apps/operations/publishing#registration-ownership).
- **Sync / migration error** — the build succeeds but applying the diff fails, naming the entity and `universalIdentifier`; fix the conflicting metadata.
- **Dependencies size error** — the sync or install fails because the app's production `dependencies` are too large to install as a runtime layer (`LOGIC_FUNCTION_DEPENDENCIES_SIZE_EXCEEDED`); move packages your logic functions do not import at runtime (UI libraries, dev tooling) to `devDependencies`.
- **App code runtime error** — the sync succeeds but your logic functions or components misbehave at runtime; check [function logs](/developers/extend/apps/operations/cli).
diff --git a/packages/twenty-sdk/src/cli/operations/dev-once.ts b/packages/twenty-sdk/src/cli/operations/dev-once.ts
index 02401ac63dc..55541c4890b 100644
--- a/packages/twenty-sdk/src/cli/operations/dev-once.ts
+++ b/packages/twenty-sdk/src/cli/operations/dev-once.ts
@@ -25,6 +25,7 @@ import {
} from '@/cli/utilities/dev/orchestrator/steps/format-sync-actions-plan';
import { formatManifestValidationErrors } from '@/cli/utilities/error/format-manifest-validation-errors';
import { getSyncErrorRecoveryHint } from '@/cli/utilities/error/get-sync-error-recovery-hint';
+import { getGraphQLErrorMessage } from '@/cli/utilities/error/parse-server-error';
import { serializeError } from '@/cli/utilities/error/serialize-error';
import { FileUploader } from '@/cli/utilities/file/file-uploader';
import { runSafe } from '@/cli/utilities/run-safe';
@@ -309,7 +310,9 @@ const innerAppDevOnce = async (
success: false,
error: {
code: APP_ERROR_CODES.SYNC_FAILED,
- message: `Failed to install development application: ${serializeError(createDevAppResult.error)}`,
+ message:
+ getGraphQLErrorMessage(createDevAppResult.error) ??
+ `Failed to install development application: ${serializeError(createDevAppResult.error)}`,
},
};
}
diff --git a/packages/twenty-sdk/src/cli/utilities/dev/orchestrator/dev-mode-orchestrator.ts b/packages/twenty-sdk/src/cli/utilities/dev/orchestrator/dev-mode-orchestrator.ts
index b64830f3e92..0ed14f00153 100644
--- a/packages/twenty-sdk/src/cli/utilities/dev/orchestrator/dev-mode-orchestrator.ts
+++ b/packages/twenty-sdk/src/cli/utilities/dev/orchestrator/dev-mode-orchestrator.ts
@@ -14,6 +14,7 @@ import {
} from '@/cli/utilities/dev/orchestrator/steps/start-watchers-orchestrator-step';
import { SyncApplicationOrchestratorStep } from '@/cli/utilities/dev/orchestrator/steps/sync-application-orchestrator-step';
import { UploadFilesOrchestratorStep } from '@/cli/utilities/dev/orchestrator/steps/upload-files-orchestrator-step';
+import { getGraphQLErrorMessage } from '@/cli/utilities/error/parse-server-error';
import { serializeError } from '@/cli/utilities/error/serialize-error';
import { emptyDir, ensureDir } from '@/cli/utilities/file/fs-utils';
import path from 'path';
@@ -288,9 +289,13 @@ export class DevModeOrchestrator {
});
if (!createResult.success || !createResult.data) {
+ const serverMessage = createResult.success
+ ? undefined
+ : getGraphQLErrorMessage(createResult.error);
+
this.state.applyStepEvents([
{
- message: 'Failed to install development application',
+ message: serverMessage ?? 'Failed to install development application',
status: 'error',
},
{ message: JSON.stringify(createResult, null, 2), status: 'error' },
diff --git a/packages/twenty-sdk/src/cli/utilities/error/parse-server-error.ts b/packages/twenty-sdk/src/cli/utilities/error/parse-server-error.ts
index 5014dfd1b9f..7821f333674 100644
--- a/packages/twenty-sdk/src/cli/utilities/error/parse-server-error.ts
+++ b/packages/twenty-sdk/src/cli/utilities/error/parse-server-error.ts
@@ -1,3 +1,4 @@
+import { isNonEmptyString } from '@sniptt/guards';
import { isPlainObject } from 'twenty-shared/utils';
type GraphQLErrorEntry = {
@@ -29,6 +30,12 @@ export const getGraphQLErrorSubCode = (error: unknown): string | undefined => {
return asGraphQLErrorEntry(error)?.extensions?.subCode;
};
+export const getGraphQLErrorMessage = (error: unknown): string | undefined => {
+ const message = asGraphQLErrorEntry(error)?.message;
+
+ return isNonEmptyString(message) ? message : undefined;
+};
+
export const hasGraphQLErrorSubCode = (
error: unknown,
subCode: string,
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-development/application-development.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-development/application-development.service.ts
index 0e9754db5ce..5eb7d9e477e 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-development/application-development.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-development/application-development.service.ts
@@ -29,6 +29,7 @@ import { FileStorageService } from 'src/engine/core-modules/file-storage/service
import { validateFilePath } from 'src/engine/core-modules/file-storage/utils/validate-file-path.util';
import { type FileDTO } from 'src/engine/core-modules/file/dtos/file.dto';
import { streamToBuffer } from 'src/utils/stream-to-buffer';
+import { type ApplicationRegistrationEntity } from 'src/engine/core-modules/application/application-registration/application-registration.entity';
const APP_SYNC_LOCK_OPTIONS = { ttl: 60_000, ms: 500, maxRetries: 120 };
@@ -59,8 +60,11 @@ export class ApplicationDevelopmentService {
}): Promise<DevelopmentApplicationDTO> {
await this.throttlePerApplication(universalIdentifier, workspaceId);
- const applicationRegistrationId =
- await this.findApplicationRegistrationId(universalIdentifier);
+ const applicationRegistration =
+ await this.findOwnedApplicationRegistrationOrThrow({
+ universalIdentifier,
+ workspaceId,
+ });
const existing = await this.applicationService.findByUniversalIdentifier({
universalIdentifier,
@@ -79,7 +83,7 @@ export class ApplicationDevelopmentService {
name,
sourcePath: universalIdentifier,
sourceType: ApplicationRegistrationSourceType.LOCAL,
- applicationRegistrationId,
+ applicationRegistrationId: applicationRegistration.id,
workspaceId,
});
@@ -124,6 +128,11 @@ export class ApplicationDevelopmentService {
);
}
+ await this.findOwnedApplicationRegistrationOrThrow({
+ universalIdentifier: manifest.application.universalIdentifier,
+ workspaceId,
+ });
+
if (dryRun === true) {
const { workspaceMigration } =
await this.applicationSyncService.synchronizeFromManifest({
@@ -220,9 +229,11 @@ export class ApplicationDevelopmentService {
workspaceId: string,
inferDeletionFromMissingEntities: boolean,
): Promise<WorkspaceMigrationDTO> {
- const applicationRegistrationId = await this.findApplicationRegistrationId(
- manifest.application.universalIdentifier,
- );
+ const applicationRegistration =
+ await this.findOwnedApplicationRegistrationOrThrow({
+ universalIdentifier: manifest.application.universalIdentifier,
+ workspaceId,
+ });
const application = await this.applicationService.findByUniversalIdentifier(
{
@@ -242,13 +253,13 @@ export class ApplicationDevelopmentService {
await this.applicationManifestApplyService.applyManifestToWorkspace({
workspaceId,
manifest,
- applicationRegistrationId,
+ applicationRegistrationId: applicationRegistration.id,
application,
inferDeletionFromMissingEntities,
});
await this.syncRegistrationMetadata(
- applicationRegistrationId,
+ applicationRegistration.id,
manifest,
workspaceId,
);
@@ -272,11 +283,15 @@ export class ApplicationDevelopmentService {
);
}
- private async findApplicationRegistrationId(
- universalIdentifier: string,
- ): Promise<string> {
+ private async findOwnedApplicationRegistrationOrThrow({
+ universalIdentifier,
+ workspaceId,
+ }: {
+ universalIdentifier: string;
+ workspaceId: string;
+ }): Promise<ApplicationRegistrationEntity> {
const existingRegistration =
- await this.applicationRegistrationService.findOneByUniversalIdentifier(
+ await this.applicationRegistrationService.findOneByUniversalIdentifierGlobal(
universalIdentifier,
);
@@ -287,7 +302,16 @@ export class ApplicationDevelopmentService {
);
}
- return existingRegistration.id;
+ if (existingRegistration.ownerWorkspaceId !== workspaceId) {
+ throw new ApplicationException(
+ !isDefined(existingRegistration.ownerWorkspaceId)
+ ? `"${universalIdentifier}" is registered on this instance but claimed by no workspace. Claim its ownership before developing on it.`
+ : `"${universalIdentifier}" is registered to another workspace. Change the universalIdentifier in your manifest, or transfer the registration from the owning workspace.`,
+ ApplicationExceptionCode.FORBIDDEN,
+ );
+ }
+
+ return existingRegistration;
}
private async syncRegistrationMetadata(
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-marketplace/marketplace-catalog-sync.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-marketplace/marketplace-catalog-sync.service.ts
index 485a57c7abc..1de8839d225 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-marketplace/marketplace-catalog-sync.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-marketplace/marketplace-catalog-sync.service.ts
@@ -47,7 +47,7 @@ export class MarketplaceCatalogSyncService {
fetchedManifest.application.universalIdentifier;
const previousVersion = (
- await this.applicationRegistrationService.findOneByUniversalIdentifier(
+ await this.applicationRegistrationService.findOneByUniversalIdentifierGlobal(
universalIdentifier,
)
)?.latestAvailableVersion;
@@ -62,7 +62,7 @@ export class MarketplaceCatalogSyncService {
});
const registration =
- await this.applicationRegistrationService.findOneByUniversalIdentifier(
+ await this.applicationRegistrationService.findOneByUniversalIdentifierGlobal(
universalIdentifier,
);
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-marketplace/marketplace-query.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-marketplace/marketplace-query.service.ts
index 6e270846e29..46e0f8ac017 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-marketplace/marketplace-query.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-marketplace/marketplace-query.service.ts
@@ -66,7 +66,7 @@ export class MarketplaceQueryService {
universalIdentifier: string,
): Promise<ApplicationRegistrationEntity> {
const registration =
- await this.applicationRegistrationService.findOneByUniversalIdentifier(
+ await this.applicationRegistrationService.findOneByUniversalIdentifierGlobal(
universalIdentifier,
);
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/__tests__/oauth-discovery.controller.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/__tests__/oauth-discovery.controller.spec.ts
index f288f131649..38a089c8c61 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/__tests__/oauth-discovery.controller.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/__tests__/oauth-discovery.controller.spec.ts
@@ -37,7 +37,7 @@ describe('OAuthDiscoveryController', () => {
},
{
provide: ApplicationRegistrationService,
- useValue: { findOneByUniversalIdentifier: jest.fn() },
+ useValue: { findOneByUniversalIdentifierGlobal: jest.fn() },
},
],
}).compile();
@@ -93,7 +93,7 @@ describe('OAuthDiscoveryController', () => {
},
{
provide: ApplicationRegistrationService,
- useValue: { findOneByUniversalIdentifier: jest.fn() },
+ useValue: { findOneByUniversalIdentifierGlobal: jest.fn() },
},
],
}).compile();
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/oauth-discovery.controller.ts b/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/oauth-discovery.controller.ts
index 9709eb596eb..84e00ad25a8 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/oauth-discovery.controller.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/oauth-discovery.controller.ts
@@ -39,7 +39,7 @@ export class OAuthDiscoveryController {
: `${authorizeBase}/authorize?iss=${encodeURIComponent(issuer)}`;
const cliRegistration =
- await this.applicationRegistrationService.findOneByUniversalIdentifier(
+ await this.applicationRegistrationService.findOneByUniversalIdentifierGlobal(
TWENTY_CLI_APPLICATION_REGISTRATION.universalIdentifier,
);
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration.resolver.ts b/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration.resolver.ts
index 4a02d4d5a30..1b7cbc412f4 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration.resolver.ts
@@ -91,7 +91,7 @@ export class ApplicationRegistrationResolver {
async findApplicationRegistrationByUniversalIdentifier(
@Args('universalIdentifier') universalIdentifier: string,
): Promise<ApplicationRegistrationEntity | null> {
- return this.applicationRegistrationService.findOneByUniversalIdentifier(
+ return this.applicationRegistrationService.findOneByUniversalIdentifierGlobal(
universalIdentifier,
);
}
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration.service.ts
index c15129f7f41..25bb27b0d2d 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration.service.ts
@@ -481,7 +481,7 @@ export class ApplicationRegistrationService {
};
}
- async findOneByUniversalIdentifier(
+ async findOneByUniversalIdentifierGlobal(
universalIdentifier: string,
): Promise<ApplicationRegistrationEntity | null> {
return this.applicationRegistrationRepository.findOne({
@@ -500,7 +500,7 @@ export class ApplicationRegistrationService {
const universalIdentifier = input.universalIdentifier ?? v4();
const existingByUid =
- await this.findOneByUniversalIdentifier(universalIdentifier);
+ await this.findOneByUniversalIdentifierGlobal(universalIdentifier);
if (existingByUid) {
throw new ApplicationRegistrationException(
@@ -779,7 +779,7 @@ export class ApplicationRegistrationService {
| 'manifest'
>,
): Promise<void> {
- const existing = await this.findOneByUniversalIdentifier(
+ const existing = await this.findOneByUniversalIdentifierGlobal(
params.universalIdentifier,
);
@@ -912,7 +912,7 @@ export class ApplicationRegistrationService {
}
async createCliRegistrationIfNotExists(): Promise<ApplicationRegistrationEntity | null> {
- const existing = await this.findOneByUniversalIdentifier(
+ const existing = await this.findOneByUniversalIdentifierGlobal(
TWENTY_CLI_APPLICATION_REGISTRATION.universalIdentifier,
);
diff --git a/packages/twenty-server/src/engine/core-modules/onboarding/jobs/install-onboarding-apps.job.spec.ts b/packages/twenty-server/src/engine/core-modules/onboarding/jobs/install-onboarding-apps.job.spec.ts
index e5a71e6595c..1ac774e47ca 100644
--- a/packages/twenty-server/src/engine/core-modules/onboarding/jobs/install-onboarding-apps.job.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/onboarding/jobs/install-onboarding-apps.job.spec.ts
@@ -27,7 +27,7 @@ describe('InstallOnboardingAppsJob', () => {
{
provide: ApplicationRegistrationService,
useValue: {
- findOneByUniversalIdentifier: jest.fn(),
+ findOneByUniversalIdentifierGlobal: jest.fn(),
},
},
{
@@ -62,7 +62,10 @@ describe('InstallOnboardingAppsJob', () => {
it('should credit the reward for every requested app and install them', async () => {
jest
- .spyOn(applicationRegistrationService, 'findOneByUniversalIdentifier')
+ .spyOn(
+ applicationRegistrationService,
+ 'findOneByUniversalIdentifierGlobal',
+ )
.mockImplementation(async (universalIdentifier) =>
buildRegistration(`registration-${universalIdentifier}`),
);
@@ -86,7 +89,10 @@ describe('InstallOnboardingAppsJob', () => {
it('should credit only once an install has succeeded', async () => {
jest
- .spyOn(applicationRegistrationService, 'findOneByUniversalIdentifier')
+ .spyOn(
+ applicationRegistrationService,
+ 'findOneByUniversalIdentifierGlobal',
+ )
.mockImplementation(async (universalIdentifier) =>
buildRegistration(`registration-${universalIdentifier}`),
);
@@ -110,7 +116,10 @@ describe('InstallOnboardingAppsJob', () => {
it('should not credit again when a failed run is relaunched', async () => {
jest
- .spyOn(applicationRegistrationService, 'findOneByUniversalIdentifier')
+ .spyOn(
+ applicationRegistrationService,
+ 'findOneByUniversalIdentifierGlobal',
+ )
.mockResolvedValue(null);
await job.handle({
@@ -129,7 +138,10 @@ describe('InstallOnboardingAppsJob', () => {
it('should not credit when every install fails', async () => {
jest
- .spyOn(applicationRegistrationService, 'findOneByUniversalIdentifier')
+ .spyOn(
+ applicationRegistrationService,
+ 'findOneByUniversalIdentifierGlobal',
+ )
.mockImplementation(async (universalIdentifier) =>
buildRegistration(`registration-${universalIdentifier}`),
);
@@ -150,7 +162,10 @@ describe('InstallOnboardingAppsJob', () => {
it('should credit only the apps that were actually installed when a registration cannot be found', async () => {
jest
- .spyOn(applicationRegistrationService, 'findOneByUniversalIdentifier')
+ .spyOn(
+ applicationRegistrationService,
+ 'findOneByUniversalIdentifierGlobal',
+ )
.mockImplementation(async (universalIdentifier) =>
universalIdentifier === callRecorderId
? null
@@ -176,7 +191,10 @@ describe('InstallOnboardingAppsJob', () => {
it('should clear every step to go back to once the apps are scheduled', async () => {
jest
- .spyOn(applicationRegistrationService, 'findOneByUniversalIdentifier')
+ .spyOn(
+ applicationRegistrationService,
+ 'findOneByUniversalIdentifierGlobal',
+ )
.mockResolvedValue(buildRegistration('registration-id'));
jest
.spyOn(applicationInstallService, 'installApplication')
@@ -195,7 +213,10 @@ describe('InstallOnboardingAppsJob', () => {
it('should keep the steps to go back to when every install failed', async () => {
jest
- .spyOn(applicationRegistrationService, 'findOneByUniversalIdentifier')
+ .spyOn(
+ applicationRegistrationService,
+ 'findOneByUniversalIdentifierGlobal',
+ )
.mockResolvedValue(null);
await job.handle({
@@ -211,7 +232,10 @@ describe('InstallOnboardingAppsJob', () => {
it('should clear the steps to go back to when only some installs succeeded', async () => {
jest
- .spyOn(applicationRegistrationService, 'findOneByUniversalIdentifier')
+ .spyOn(
+ applicationRegistrationService,
+ 'findOneByUniversalIdentifierGlobal',
+ )
.mockImplementation(async (universalIdentifier) =>
universalIdentifier === callRecorderId
? buildRegistration('registration-id')
@@ -234,7 +258,10 @@ describe('InstallOnboardingAppsJob', () => {
it('should still install when the job was enqueued before it carried a user', async () => {
jest
- .spyOn(applicationRegistrationService, 'findOneByUniversalIdentifier')
+ .spyOn(
+ applicationRegistrationService,
+ 'findOneByUniversalIdentifierGlobal',
+ )
.mockResolvedValue(buildRegistration('registration-id'));
jest
.spyOn(applicationInstallService, 'installApplication')
diff --git a/packages/twenty-server/src/engine/core-modules/onboarding/jobs/install-onboarding-apps.job.ts b/packages/twenty-server/src/engine/core-modules/onboarding/jobs/install-onboarding-apps.job.ts
index e930755de4f..c6ff45e965d 100644
--- a/packages/twenty-server/src/engine/core-modules/onboarding/jobs/install-onboarding-apps.job.ts
+++ b/packages/twenty-server/src/engine/core-modules/onboarding/jobs/install-onboarding-apps.job.ts
@@ -67,7 +67,7 @@ export class InstallOnboardingAppsJob {
}): Promise<boolean> {
try {
const registration =
- await this.applicationRegistrationService.findOneByUniversalIdentifier(
+ await this.applicationRegistrationService.findOneByUniversalIdentifierGlobal(
universalIdentifier,
);
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/catalog-synced-app-dev-mode.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/catalog-synced-app-dev-mode.integration-spec.ts
index 2994a30df12..1fafe74ad75 100644
--- a/packages/twenty-server/test/integration/metadata/suites/application/catalog-synced-app-dev-mode.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/application/catalog-synced-app-dev-mode.integration-spec.ts
@@ -3,17 +3,18 @@ import crypto from 'crypto';
import request from 'supertest';
import { buildBaseManifest } from 'test/integration/metadata/suites/application/utils/build-base-manifest.util';
import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
import { syncApplication } from 'test/integration/metadata/suites/application/utils/sync-application.util';
import { uploadApplicationFile } from 'test/integration/metadata/suites/application/utils/upload-application-file.util';
import { type DataSource } from 'typeorm';
// A published npm app lands on an instance through the marketplace catalog
-// sync as an instance-global, unowned registration (sourceType 'npm'). A dev
-// iterating locally on that app with `twenty app dev` must be able to sync it
-// into their own workspace without claiming ownership, without rotating the
-// shared OAuth client secret, and without mutating the shared registration
-// (which would delist the app from the marketplace for every workspace and
-// fight with the catalog sync cron).
+// sync as an instance-global, unowned registration (sourceType 'npm').
+// Uploading code under an application identity is an authorship claim, so dev
+// mode requires ownership of the registration. Once the workspace owns it, the
+// dev sync must still leave the shared registration untouched, without
+// rotating the shared OAuth client secret and without delisting the app from
+// the marketplace for every workspace or fighting with the catalog sync cron.
describe('CLI dev mode on a catalog-synced (npm) app', () => {
const baseUrl = `http://localhost:${APP_PORT}`;
@@ -106,7 +107,26 @@ describe('CLI dev mode on a catalog-synced (npm) app', () => {
expect(res.body.errors[0].message).toContain('not found');
});
- it('lets a workspace dev-sync the app and mint a dev token without claiming ownership or touching the shared registration', async () => {
+ it('refuses dev mode while no workspace owns the registration', async () => {
+ const res = await gqlRequest(
+ `mutation CreateDevApp($universalIdentifier: String!, $name: String!) {
+ createDevelopmentApplication(universalIdentifier: $universalIdentifier, name: $name) {
+ id
+ }
+ }`,
+ { universalIdentifier, name: 'Published Catalog App (dev)' },
+ ).expect(200);
+
+ expect(res.body.errors).toBeDefined();
+ expect(res.body.errors[0].message).toContain('claimed by no workspace');
+ });
+
+ it('lets a workspace dev-sync the app and mint a dev token once it owns the registration, without touching the shared registration', async () => {
+ await ds.query(
+ `UPDATE core."applicationRegistration" SET "workspaceId" = $1 WHERE id = $2`,
+ [SEED_APPLE_WORKSPACE_ID, registrationId],
+ );
+
const createDevAppRes = await gqlRequest(
`mutation CreateDevApp($universalIdentifier: String!, $name: String!) {
createDevelopmentApplication(universalIdentifier: $universalIdentifier, name: $name) {
@@ -154,13 +174,11 @@ describe('CLI dev mode on a catalog-synced (npm) app', () => {
expect(syncRes.errors).toBeUndefined();
- // The shared registration is untouched: still npm-sourced, unowned,
- // listed in the marketplace catalog, and carrying the published name and
- // manifest.
+ // The shared registration is untouched: still npm-sourced, still listed in
+ // the marketplace catalog, and carrying the published name and manifest.
const registrationRow = await fetchRegistrationRow();
expect(registrationRow.sourceType).toBe('npm');
- expect(registrationRow.workspaceId).toBeNull();
expect(registrationRow.name).toBe('Published Catalog App');
expect(registrationRow.isListed).toBe(true);
expect(registrationRow.manifest).toEqual({
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/dev-mode-foreign-registration.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/dev-mode-foreign-registration.integration-spec.ts
new file mode 100644
index 00000000000..5c9a9490fee
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/application/dev-mode-foreign-registration.integration-spec.ts
@@ -0,0 +1,105 @@
+import crypto from 'crypto';
+
+import request from 'supertest';
+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import { type DataSource } from 'typeorm';
+
+import { SEED_YCOMBINATOR_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+
+describe('CLI dev mode on a registration owned by another workspace', () => {
+ const baseUrl = `http://localhost:${APP_PORT}`;
+
+ const foreignWorkspaceId = SEED_YCOMBINATOR_WORKSPACE_ID;
+
+ let ds: DataSource;
+
+ const gqlRequest = (query: string, variables?: Record<string, unknown>) =>
+ request(baseUrl)
+ .post('/metadata')
+ .set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)
+ .send({ query, variables });
+
+ const createDevelopmentApplication = (universalIdentifier: string) =>
+ gqlRequest(
+ `mutation CreateDevApp($universalIdentifier: String!, $name: String!) {
+ createDevelopmentApplication(universalIdentifier: $universalIdentifier, name: $name) {
+ id
+ }
+ }`,
+ { universalIdentifier, name: 'Stolen App' },
+ ).expect(200);
+
+ const seedForeignRegistration = async ({
+ universalIdentifier,
+ isListed,
+ isPreInstalled,
+ }: {
+ universalIdentifier: string;
+ isListed: boolean;
+ isPreInstalled: boolean;
+ }) => {
+ await ds.query(
+ `INSERT INTO core."applicationRegistration"
+ (id, "universalIdentifier", name, "oAuthClientId", "oAuthRedirectUris",
+ "oAuthScopes", "workspaceId", "sourceType", "isListed", "isPreInstalled")
+ VALUES ($1, $2, $3, $4, $5, $6, $7, 'tarball', $8, $9)`,
+ [
+ crypto.randomUUID(),
+ universalIdentifier,
+ 'Victim Internal App',
+ crypto.randomUUID(),
+ [],
+ [],
+ foreignWorkspaceId,
+ isListed,
+ isPreInstalled,
+ ],
+ );
+ };
+
+ beforeAll(() => {
+ jest.useRealTimers();
+ ds = global.testDataSource;
+ });
+
+ afterAll(() => {
+ jest.useFakeTimers();
+ });
+
+ it.each([
+ { label: 'unlisted', isListed: false, isPreInstalled: false },
+ {
+ label: 'listed on the marketplace',
+ isListed: true,
+ isPreInstalled: false,
+ },
+ {
+ label: 'pre-installed by the operator',
+ isListed: false,
+ isPreInstalled: true,
+ },
+ ])(
+ 'refuses to create a development application on a $label foreign registration',
+ async ({ isListed, isPreInstalled }) => {
+ const universalIdentifier = crypto.randomUUID();
+
+ await seedForeignRegistration({
+ universalIdentifier,
+ isListed,
+ isPreInstalled,
+ });
+
+ try {
+ const res = await createDevelopmentApplication(universalIdentifier);
+
+ expect(res.body.errors).toBeDefined();
+ expect(res.body.errors[0].message).toContain('another workspace');
+ expect(res.body.data?.createDevelopmentApplication).toBeFalsy();
+ } finally {
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: universalIdentifier,
+ });
+ }
+ },
+ );
+});