Skip to content

The open alternative to Salesforce, designed for AI.

refactor: return API-relative paths for CSV export downloads (#26603)

Weiko2eb956dbe7a1
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index d062c2977fe..fe3b5ef6ed6 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -3422,7 +3422,7 @@ type RecordExport {
filename: String!
progress: Int!
errorMessage: String
- downloadUrl: String
+ downloadPath: String
}
type AiChatUsage {
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index e0f15b23b7e..e63720ced2f 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -3010,7 +3010,7 @@ export interface RecordExport {
filename: Scalars['String']
progress: Scalars['Int']
errorMessage?: Scalars['String']
- downloadUrl?: Scalars['String']
+ downloadPath?: Scalars['String']
__typename: 'RecordExport'
}
@@ -6891,7 +6891,7 @@ export interface RecordExportGenqlSelection{
filename?: boolean | number
progress?: boolean | number
errorMessage?: boolean | number
- downloadUrl?: boolean | number
+ downloadPath?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.ts
index ad7d24435e2..a5ced6f14df 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts
@@ -6746,7 +6746,7 @@ export default {
"errorMessage": [
1
],
- "downloadUrl": [
+ "downloadPath": [
1
],
"__typename": [
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index f0bf5d849ad..07bcbad0550 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -5794,7 +5794,7 @@ export type RatioAggregateConfig = {
export type RecordExport = {
__typename?: 'RecordExport';
- downloadUrl?: Maybe<Scalars['String']['output']>;
+ downloadPath?: Maybe<Scalars['String']['output']>;
errorMessage?: Maybe<Scalars['String']['output']>;
filename: Scalars['String']['output'];
id: Scalars['UUID']['output'];
@@ -9278,7 +9278,7 @@ export type ExportRecordsSubscriptionVariables = Exact<{
}>;
-export type ExportRecordsSubscription = { __typename?: 'Subscription', exportRecords: { __typename?: 'RecordExport', id: string, filename: string, progress: number, errorMessage?: string | null, downloadUrl?: string | null } };
+export type ExportRecordsSubscription = { __typename?: 'Subscription', exportRecords: { __typename?: 'RecordExport', id: string, filename: string, progress: number, errorMessage?: string | null, downloadPath?: string | null } };
export type CreateEmailGroupChannelMutationVariables = Exact<{
input: CreateEmailGroupChannelInput;
@@ -10609,7 +10609,7 @@ export const CallRecordingIdForCalendarEventDocument = {"kind":"Document","defin
export const BarChartDataDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"BarChartData"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"BarChartDataInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"barChartData"},"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":"data"}},{"kind":"Field","name":{"kind":"Name","value":"indexBy"}},{"kind":"Field","name":{"kind":"Name","value":"keys"}},{"kind":"Field","name":{"kind":"Name","value":"series"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"label"}}]}},{"kind":"Field","name":{"kind":"Name","value":"xAxisLabel"}},{"kind":"Field","name":{"kind":"Name","value":"yAxisLabel"}},{"kind":"Field","name":{"kind":"Name","value":"showLegend"}},{"kind":"Field","name":{"kind":"Name","value":"showDataLabels"}},{"kind":"Field","name":{"kind":"Name","value":"layout"}},{"kind":"Field","name":{"kind":"Name","value":"groupMode"}},{"kind":"Field","name":{"kind":"Name","value":"hasTooManyGroups"}},{"kind":"Field","name":{"kind":"Name","value":"formattedToRawLookup"}}]}}]}}]} as unknown as DocumentNode<BarChartDataQuery, BarChartDataQueryVariables>;
export const LineChartDataDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"LineChartData"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"LineChartDataInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"lineChartData"},"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":"series"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"data"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"x"}},{"kind":"Field","name":{"kind":"Name","value":"y"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"xAxisLabel"}},{"kind":"Field","name":{"kind":"Name","value":"yAxisLabel"}},{"kind":"Field","name":{"kind":"Name","value":"showLegend"}},{"kind":"Field","name":{"kind":"Name","value":"showDataLabels"}},{"kind":"Field","name":{"kind":"Name","value":"hasTooManyGroups"}},{"kind":"Field","name":{"kind":"Name","value":"formattedToRawLookup"}}]}}]}}]} as unknown as DocumentNode<LineChartDataQuery, LineChartDataQueryVariables>;
export const PieChartDataDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"PieChartData"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"PieChartDataInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"pieChartData"},"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":"data"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"value"}}]}},{"kind":"Field","name":{"kind":"Name","value":"showLegend"}},{"kind":"Field","name":{"kind":"Name","value":"showDataLabels"}},{"kind":"Field","name":{"kind":"Name","value":"showCenterMetric"}},{"kind":"Field","name":{"kind":"Name","value":"hasTooManyGroups"}},{"kind":"Field","name":{"kind":"Name","value":"formattedToRawLookup"}}]}}]}}]} as unknown as DocumentNode<PieChartDataQuery, PieChartDataQueryVariables>;
-export const ExportRecordsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"subscription","name":{"kind":"Name","value":"ExportRecords"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"CreateRecordExportInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"exportRecords"},"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":"filename"}},{"kind":"Field","name":{"kind":"Name","value":"progress"}},{"kind":"Field","name":{"kind":"Name","value":"errorMessage"}},{"kind":"Field","name":{"kind":"Name","value":"downloadUrl"}}]}}]}}]} as unknown as DocumentNode<ExportRecordsSubscription, ExportRecordsSubscriptionVariables>;
+export const ExportRecordsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"subscription","name":{"kind":"Name","value":"ExportRecords"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"CreateRecordExportInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"exportRecords"},"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":"filename"}},{"kind":"Field","name":{"kind":"Name","value":"progress"}},{"kind":"Field","name":{"kind":"Name","value":"errorMessage"}},{"kind":"Field","name":{"kind":"Name","value":"downloadPath"}}]}}]}}]} as unknown as DocumentNode<ExportRecordsSubscription, ExportRecordsSubscriptionVariables>;
export const CreateEmailGroupChannelDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"CreateEmailGroupChannel"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"CreateEmailGroupChannelInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"createEmailGroupChannel"},"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":"messageChannel"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"handle"}},{"kind":"Field","name":{"kind":"Name","value":"visibility"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"isSyncEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"excludeGroupEmails"}},{"kind":"Field","name":{"kind":"Name","value":"contactAutoCreationPolicy"}}]}},{"kind":"Field","name":{"kind":"Name","value":"forwardingAddress"}}]}}]}}]} as unknown as DocumentNode<CreateEmailGroupChannelMutation, CreateEmailGroupChannelMutationVariables>;
export const DeleteConnectedAccountDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"DeleteConnectedAccount"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deleteConnectedAccount"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}}]}}]} as unknown as DocumentNode<DeleteConnectedAccountMutation, DeleteConnectedAccountMutationVariables>;
export const DeleteEmailGroupChannelDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"DeleteEmailGroupChannel"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deleteEmailGroupChannel"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}}]}}]} as unknown as DocumentNode<DeleteEmailGroupChannelMutation, DeleteEmailGroupChannelMutationVariables>;
diff --git a/packages/twenty-front/src/modules/record-export/components/__stories__/RecordExportConnectionEffect.stories.tsx b/packages/twenty-front/src/modules/record-export/components/__stories__/RecordExportConnectionEffect.stories.tsx
index 4eccb457b14..c383269e9aa 100644
--- a/packages/twenty-front/src/modules/record-export/components/__stories__/RecordExportConnectionEffect.stories.tsx
+++ b/packages/twenty-front/src/modules/record-export/components/__stories__/RecordExportConnectionEffect.stories.tsx
@@ -62,7 +62,7 @@ const exportHandler = (finish: 'completed' | 'interrupted' | 'wait') =>
id: 'export',
filename: 'person.csv',
progress,
- downloadUrl:
+ downloadPath:
progress === 100
? '/file/record-export/export?token=token'
: null,
diff --git a/packages/twenty-front/src/modules/record-export/graphql/exportRecords.ts b/packages/twenty-front/src/modules/record-export/graphql/exportRecords.ts
index 88a16cadc9a..34d4f54a36f 100644
--- a/packages/twenty-front/src/modules/record-export/graphql/exportRecords.ts
+++ b/packages/twenty-front/src/modules/record-export/graphql/exportRecords.ts
@@ -7,7 +7,7 @@ export const EXPORT_RECORDS = gql`
filename
progress
errorMessage
- downloadUrl
+ downloadPath
}
}
`;
diff --git a/packages/twenty-front/src/modules/record-export/utils/__tests__/createRecordExportConnection.test.ts b/packages/twenty-front/src/modules/record-export/utils/__tests__/createRecordExportConnection.test.ts
index 0dfe7b5f233..1750ffcc8c8 100644
--- a/packages/twenty-front/src/modules/record-export/utils/__tests__/createRecordExportConnection.test.ts
+++ b/packages/twenty-front/src/modules/record-export/utils/__tests__/createRecordExportConnection.test.ts
@@ -53,7 +53,7 @@ describe('createRecordExportConnection', () => {
expect(click).not.toHaveBeenCalled();
update({
progress: 100,
- downloadUrl: '/file/record-export/export?token=token',
+ downloadPath: '/file/record-export/export?token=token',
});
await expect(finished).resolves.toBeUndefined();
expect(click).toHaveBeenCalledTimes(1);
@@ -64,57 +64,28 @@ describe('createRecordExportConnection', () => {
);
update({
progress: 100,
- downloadUrl: '/file/record-export/export?token=token',
+ downloadPath: '/file/record-export/export?token=token',
});
mockSink.complete();
expect(click).toHaveBeenCalledTimes(1);
expect(mockDispose).toHaveBeenCalledTimes(1);
});
- it.each([
- 'https://workspace.example.test',
- 'https://custom-domain.example.test',
- 'http://localhost:3000',
- 'https://workspace.example.test/twenty',
- 'http://localhost:3000/apps/twenty',
- ])('downloads through the authenticated API at %s', async (serverBaseUrl) => {
- mockServerBaseUrl = serverBaseUrl;
- const click = jest
- .spyOn(HTMLAnchorElement.prototype, 'click')
- .mockImplementation(() => {});
- const finished = createRecordExportConnection().exportRecords({ input });
-
- expect(createClient).toHaveBeenCalledWith(
- expect.objectContaining({
- url: `${serverBaseUrl}/metadata`,
- credentials: 'include',
- }),
- );
- update({
- progress: 100,
- downloadUrl:
- 'https://api.example.test/file/record-export/export?token=signed%2Btoken',
- });
-
- await expect(finished).resolves.toBeUndefined();
- expect(click.mock.instances[0]).toHaveAttribute(
- 'href',
- `${serverBaseUrl}/file/record-export/export?token=signed%2Btoken`,
- );
- expect(click.mock.instances[0]).toHaveAttribute('download', 'person.csv');
- });
-
- it.each([
- 'https://api.example.test/file/record-export/export',
- 'https://api.example.test/twenty/file/record-export/export',
- 'https://api.example.test/canonical/file/record-export/export',
- '/file/record-export/export',
- '/twenty/file/record-export/export',
- 'file/record-export/export',
- ])(
- 'preserves the API base path when downloading %s',
- async (downloadPath) => {
- mockServerBaseUrl = 'https://workspace.example.test/twenty/';
+ it.each(
+ [
+ 'https://workspace.example.test',
+ 'https://custom-domain.example.test',
+ 'http://localhost:3000',
+ 'https://workspace.example.test/twenty',
+ 'http://localhost:3000/apps/twenty',
+ ].flatMap((baseUrl) => [
+ { serverBaseUrl: baseUrl, expectedBaseUrl: baseUrl },
+ { serverBaseUrl: `${baseUrl}/`, expectedBaseUrl: baseUrl },
+ ]),
+ )(
+ 'downloads through the authenticated API at $serverBaseUrl',
+ async ({ serverBaseUrl, expectedBaseUrl }) => {
+ mockServerBaseUrl = serverBaseUrl;
const click = jest
.spyOn(HTMLAnchorElement.prototype, 'click')
.mockImplementation(() => {});
@@ -122,25 +93,48 @@ describe('createRecordExportConnection', () => {
expect(createClient).toHaveBeenCalledWith(
expect.objectContaining({
- url: 'https://workspace.example.test/twenty/metadata',
+ url: `${expectedBaseUrl}/metadata`,
credentials: 'include',
}),
);
update({
progress: 100,
- downloadUrl: `${downloadPath}?token=signed%2Btoken%2Fvalue%3D&expires=123`,
+ downloadPath: '/file/record-export/export?token=signed%2Btoken',
});
await expect(finished).resolves.toBeUndefined();
- expect(click).toHaveBeenCalledTimes(1);
expect(click.mock.instances[0]).toHaveAttribute(
'href',
- 'https://workspace.example.test/twenty/file/record-export/export?token=signed%2Btoken%2Fvalue%3D&expires=123',
+ `${expectedBaseUrl}/file/record-export/export?token=signed%2Btoken`,
);
expect(click.mock.instances[0]).toHaveAttribute('download', 'person.csv');
},
);
+ it.each([
+ '/file/record-export/export',
+ '/downloads/generated/company%20export.csv',
+ ])('uses the server-provided download path %s', async (downloadPath) => {
+ mockServerBaseUrl = 'https://workspace.example.test/twenty/';
+ const click = jest
+ .spyOn(HTMLAnchorElement.prototype, 'click')
+ .mockImplementation(() => {});
+ const finished = createRecordExportConnection().exportRecords({ input });
+
+ update({
+ progress: 100,
+ downloadPath: `${downloadPath}?token=signed%2Btoken%2Fvalue%3D&expires=123`,
+ });
+
+ await expect(finished).resolves.toBeUndefined();
+ expect(click).toHaveBeenCalledTimes(1);
+ expect(click.mock.instances[0]).toHaveAttribute(
+ 'href',
+ `https://workspace.example.test/twenty${downloadPath}?token=signed%2Btoken%2Fvalue%3D&expires=123`,
+ );
+ expect(click.mock.instances[0]).toHaveAttribute('download', 'person.csv');
+ });
+
it('surfaces the server failure and closes the connection', async () => {
const finished = createRecordExportConnection().exportRecords({ input });
update({ errorMessage: 'Export failed' });
@@ -174,7 +168,7 @@ describe('createRecordExportConnection', () => {
await expect(finished).resolves.toBeUndefined();
update({
progress: 100,
- downloadUrl: '/file/record-export/export?token=token',
+ downloadPath: '/file/record-export/export?token=token',
});
expect(click).not.toHaveBeenCalled();
expect(mockDispose).toHaveBeenCalledTimes(1);
diff --git a/packages/twenty-front/src/modules/record-export/utils/createRecordExportConnection.ts b/packages/twenty-front/src/modules/record-export/utils/createRecordExportConnection.ts
index 1f6a34d0d9a..63c33ca71fb 100644
--- a/packages/twenty-front/src/modules/record-export/utils/createRecordExportConnection.ts
+++ b/packages/twenty-front/src/modules/record-export/utils/createRecordExportConnection.ts
@@ -64,17 +64,9 @@ export const createRecordExportConnection = () => {
throw new Error(recordExport.errorMessage);
}
onProgress?.(recordExport.progress);
- if (isDefined(recordExport.downloadUrl)) {
- const { search } = new URL(
- recordExport.downloadUrl,
- serverBaseUrl,
- );
- const downloadUrl = new URL(
- `${serverBaseUrl}/file/record-export/${recordExport.id}`,
- );
- downloadUrl.search = search;
+ if (isDefined(recordExport.downloadPath)) {
const link = document.createElement('a');
- link.href = downloadUrl.toString();
+ link.href = `${serverBaseUrl}${recordExport.downloadPath}`;
link.download = recordExport.filename;
document.body.appendChild(link);
link.click();
diff --git a/packages/twenty-server/src/engine/core-modules/record-export/dtos/record-export.dto.ts b/packages/twenty-server/src/engine/core-modules/record-export/dtos/record-export.dto.ts
index 33004242214..e3cc7d4c348 100644
--- a/packages/twenty-server/src/engine/core-modules/record-export/dtos/record-export.dto.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-export/dtos/record-export.dto.ts
@@ -17,5 +17,5 @@ export class RecordExportDTO {
errorMessage: string | null;
@Field(() => String, { nullable: true })
- downloadUrl?: string;
+ downloadPath?: string;
}
diff --git a/packages/twenty-server/src/engine/core-modules/record-export/services/__tests__/record-export.workspace-service.spec.ts b/packages/twenty-server/src/engine/core-modules/record-export/services/__tests__/record-export.workspace-service.spec.ts
new file mode 100644
index 00000000000..d7cf130b594
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/record-export/services/__tests__/record-export.workspace-service.spec.ts
@@ -0,0 +1,56 @@
+import { Test } from '@nestjs/testing';
+
+import { JwtTokenTypeEnum } from 'src/engine/core-modules/auth/types/jwt-token-type.enum';
+import { JwtWrapperService } from 'src/engine/core-modules/jwt/services/jwt-wrapper.service';
+import { RECORD_EXPORT_DOWNLOAD_TOKEN_TTL_SECONDS } from 'src/engine/core-modules/record-export/constants/record-export.constants';
+import { RecordExportWorkspaceService } from 'src/engine/core-modules/record-export/services/record-export.workspace-service';
+
+describe('RecordExportWorkspaceService', () => {
+ it('returns an API-relative download path with a token bound to the requester', async () => {
+ const jwtWrapperService = {
+ signAsyncOrThrow: jest.fn().mockResolvedValue('signed-token'),
+ };
+ const module = await Test.createTestingModule({
+ providers: [
+ RecordExportWorkspaceService,
+ { provide: JwtWrapperService, useValue: jwtWrapperService },
+ ],
+ })
+ .useMocker(() => ({}))
+ .compile();
+ const service = module.get(RecordExportWorkspaceService);
+ jest.spyOn(service, 'resolveRequester').mockResolvedValue({} as never);
+ jest.spyOn(service, 'assertPermissionsUnchanged').mockResolvedValue();
+ jest.spyOn(service, 'findOrThrow').mockResolvedValue({} as never);
+
+ const recordExport = {
+ id: 'export-id',
+ workspaceId: 'workspace-id',
+ userWorkspaceId: 'user-workspace-id',
+ workspaceMemberId: 'workspace-member-id',
+ requestTokenHash: 'request-token-hash',
+ permissionsHash: 'permissions-hash',
+ filename: 'company.csv',
+ };
+
+ await expect(service.getDownloadPath(recordExport)).resolves.toBe(
+ '/file/record-export/export-id?token=signed-token',
+ );
+ expect(jwtWrapperService.signAsyncOrThrow).toHaveBeenCalledWith(
+ {
+ type: JwtTokenTypeEnum.FILE,
+ purpose: 'record-export',
+ sub: recordExport.workspaceId,
+ workspaceId: recordExport.workspaceId,
+ fileId: recordExport.id,
+ userWorkspaceId: recordExport.userWorkspaceId,
+ workspaceMemberId: recordExport.workspaceMemberId,
+ requestTokenHash: recordExport.requestTokenHash,
+ permissionsHash: recordExport.permissionsHash,
+ filename: recordExport.filename,
+ },
+ { expiresIn: RECORD_EXPORT_DOWNLOAD_TOKEN_TTL_SECONDS },
+ );
+ await module.close();
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/record-export/services/record-export.workspace-service.ts b/packages/twenty-server/src/engine/core-modules/record-export/services/record-export.workspace-service.ts
index 733af389030..ef88b71a0fe 100644
--- a/packages/twenty-server/src/engine/core-modules/record-export/services/record-export.workspace-service.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-export/services/record-export.workspace-service.ts
@@ -54,7 +54,6 @@ import { type RecordExportDownloadTokenJwtPayload } from 'src/engine/core-module
import { type RecordExportParameters } from 'src/engine/core-modules/record-export/types/record-export-parameters.type';
import { type RecordExport } from 'src/engine/core-modules/record-export/types/record-export.type';
import { buildRecordExportColumns } from 'src/engine/core-modules/record-export/utils/build-record-export-columns.util';
-import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
import { UserSessionCookieService } from 'src/engine/core-modules/user-session/services/user-session-cookie.service';
import { hashUserSessionToken } from 'src/engine/core-modules/user-session/utils/hash-user-session-token.util';
import { UserWorkspaceService } from 'src/engine/core-modules/user-workspace/user-workspace.service';
@@ -114,7 +113,6 @@ export class RecordExportWorkspaceService {
private readonly messageQueueService: MessageQueueService,
private readonly fileStorageService: FileStorageService,
private readonly jwtWrapperService: JwtWrapperService,
- private readonly twentyConfigService: TwentyConfigService,
) {}
async stream(input: {
@@ -135,7 +133,7 @@ export class RecordExportWorkspaceService {
if (signal.aborted) {
return;
}
- downloadReady = isDefined(updated.downloadUrl);
+ downloadReady = isDefined(updated.downloadPath);
yield updated;
if (downloadReady || isDefined(updated.errorMessage)) {
return;
@@ -276,7 +274,7 @@ export class RecordExportWorkspaceService {
return {
...update,
progress: 100,
- downloadUrl: await this.getDownloadUrl(recordExport),
+ downloadPath: await this.getDownloadPath(recordExport),
};
}
return update;
@@ -320,7 +318,7 @@ export class RecordExportWorkspaceService {
return file;
}
- async getDownloadUrl(
+ async getDownloadPath(
recordExport: Omit<RecordExport, 'parameters' | 'createdAt'>,
): Promise<string> {
await this.resolveRequester(recordExport);
@@ -342,7 +340,7 @@ export class RecordExportWorkspaceService {
expiresIn: RECORD_EXPORT_DOWNLOAD_TOKEN_TTL_SECONDS,
});
await this.assertPermissionsUnchanged(recordExport);
- return `${this.twentyConfigService.get('SERVER_URL')}/file/record-export/${recordExport.id}?token=${token}`;
+ return `/file/record-export/${recordExport.id}?token=${token}`;
}
async openDownload({
diff --git a/packages/twenty-server/test/integration/record-export/record-export.integration-spec.ts b/packages/twenty-server/test/integration/record-export/record-export.integration-spec.ts
index c76388446d4..dfaef57f28e 100644
--- a/packages/twenty-server/test/integration/record-export/record-export.integration-spec.ts
+++ b/packages/twenty-server/test/integration/record-export/record-export.integration-spec.ts
@@ -100,7 +100,7 @@ describe('record export lifecycle (integration)', () => {
const events = connection.iterate<{ exportRecords: RecordExportDTO }>({
query: `subscription ExportRecords($input: CreateRecordExportInput!) {
exportRecords(input: $input) {
- id filename progress downloadUrl errorMessage
+ id filename progress downloadPath errorMessage
}
}`,
variables: { input: parameters },
@@ -129,8 +129,10 @@ describe('record export lifecycle (integration)', () => {
if (isDefined(recordExport.errorMessage)) {
throw new Error(recordExport.errorMessage ?? 'Export failed');
}
- if (isDefined(recordExport.downloadUrl)) {
- expect(recordExport.downloadUrl).toBeDefined();
+ if (isDefined(recordExport.downloadPath)) {
+ expect(recordExport.downloadPath).toMatch(
+ new RegExp(`^/file/record-export/${recordExport.id}\\?token=.+$`),
+ );
downloadTokens.set(recordExport.id, token);
return recordExport;
}
@@ -145,9 +147,8 @@ describe('record export lifecycle (integration)', () => {
token = downloadTokens.get(recordExport.id) ??
APPLE_JANE_ADMIN_ACCESS_TOKEN,
) => {
- const url = new URL(recordExport.downloadUrl!);
return client
- .get(url.pathname + url.search)
+ .get(recordExport.downloadPath!)
.set(authenticationHeaders(token));
};
const getExport = (id: string) =>
@@ -175,7 +176,10 @@ describe('record export lifecycle (integration)', () => {
getAppProviderByClassName<JwtWrapperService>(
'JwtWrapperService',
).verifyJwtToken(
- new URL(recordExport.downloadUrl!).searchParams.get('token')!,
+ new URL(
+ recordExport.downloadPath!,
+ `http://localhost:${APP_PORT}`,
+ ).searchParams.get('token')!,
);
const isConnected = async ({
workspaceId,
@@ -398,7 +402,7 @@ describe('record export lifecycle (integration)', () => {
it('cancels on a lost SSE connection and allows the next export', async () => {
const { connection, events } = subscribe();
const recordExport = await nextExport(events);
- expect(recordExport.downloadUrl).toBeNull();
+ expect(recordExport.downloadPath).toBeNull();
connection.dispose();
await waitUntil(
async () =>
@@ -430,7 +434,7 @@ describe('record export lifecycle (integration)', () => {
progress = await nextExport(first.events);
}
expect(progress.progress).toBe(99);
- expect(progress.downloadUrl).toBeNull();
+ expect(progress.downloadPath).toBeNull();
const second = subscribe();
await expect(nextExport(second.events)).rejects.toThrow();
} finally {
@@ -616,7 +620,7 @@ describe('record export lifecycle (integration)', () => {
});
const update = await exports.getProgress(recordExport, 'job');
expect(await fileExists(await getExport(ready.id))).toBe(true);
- expect(update.downloadUrl).toBeUndefined();
+ expect(update.downloadPath).toBeUndefined();
expect(update.errorMessage).toContain('interrupted');
expect(update.progress).toBe(expectedProgress);
},
@@ -726,7 +730,10 @@ describe('record export lifecycle (integration)', () => {
it('rejects a download token used for another export and an invalid signature', async () => {
const recordExport = await exportToCompletion();
- const url = new URL(recordExport.downloadUrl!);
+ const url = new URL(
+ recordExport.downloadPath!,
+ `http://localhost:${APP_PORT}`,
+ );
await client
.get(`/file/record-export/${v4()}${url.search}`)
.set(authenticationHeaders(APPLE_JANE_ADMIN_ACCESS_TOKEN))
@@ -825,7 +832,7 @@ describe('record export lifecycle (integration)', () => {
while (!isDefined(recordExport.errorMessage)) {
recordExport = await nextExport(events);
}
- expect(recordExport.downloadUrl).toBeNull();
+ expect(recordExport.downloadPath).toBeNull();
expect(recordExport.progress).toBeLessThan(100);
} finally {
releasePage();
@@ -880,7 +887,7 @@ describe('record export lifecycle (integration)', () => {
while (!isDefined(recordExport.errorMessage)) {
recordExport = await nextExport(events);
}
- expect(recordExport.downloadUrl).toBeNull();
+ expect(recordExport.downloadPath).toBeNull();
expect(partialFilePath).toBeDefined();
expect(pendingFile).toMatchObject({ status: 'PENDING' });
expect(await fileRowExists(pendingFile!)).toBe(false);
@@ -909,7 +916,10 @@ describe('record export lifecycle (integration)', () => {
it('requires the exact requesting token without consuming the file on denied requests', async () => {
const recordExport = await exportToCompletion();
const stored = await getExport(recordExport.id);
- const url = new URL(recordExport.downloadUrl!);
+ const url = new URL(
+ recordExport.downloadPath!,
+ `http://localhost:${APP_PORT}`,
+ );
const requester = await query.resolveRequester(
await authorization(recordExport),
);
@@ -988,7 +998,10 @@ describe('record export lifecycle (integration)', () => {
const token = await jwt.signAsyncOrThrow(payload, {
expiresIn: tokenKind === 'expired-export-token' ? -1 : 60,
});
- const url = new URL(recordExport.downloadUrl!);
+ const url = new URL(
+ recordExport.downloadPath!,
+ `http://localhost:${APP_PORT}`,
+ );
await client
.get(`${url.pathname}?token=${token}`)
.set(authenticationHeaders(APPLE_JANE_ADMIN_ACCESS_TOKEN))
@@ -1059,7 +1072,7 @@ describe('record export lifecycle (integration)', () => {
);
it.each(['access-check', 'token-signing'])(
- 'rejects URL issuance when row permissions change during %s',
+ 'rejects download path issuance when row permissions change during %s',
async (when) => {
const ready = await exportToCompletion(
input,
@@ -1096,7 +1109,7 @@ describe('record export lifecycle (integration)', () => {
});
}
await expect(
- exports.getDownloadUrl({ ...claims, id: stored.id }),
+ exports.getDownloadPath({ ...claims, id: stored.id }),
).rejects.toThrow('Access permissions have changed');
await download(ready).expect(403);
await expect(getExport(stored.id)).rejects.toThrow('Export not found');