Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions backend/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import { PersonalTableSettingsModule } from './entities/table-settings/personal-
import { SavedDbQueryModule } from './entities/visualizations/saved-db-query/saved-db-query.module.js';
import { DashboardModule } from './entities/visualizations/dashboard/dashboards.module.js';
import { DashboardWidgetModule } from './entities/visualizations/dashboard-widget/dashboard-widget.module.js';
import { SelfHostedOperationsModule } from './selfhosted-operations/selhosted-operations.module.js';

Copilot AI Feb 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The import path contains a typo - "selhosted-operations.module.js" should be "selfhosted-operations.module.js" (missing the 'f'). This needs to be corrected along with the actual filename.

Suggested change
import { SelfHostedOperationsModule } from './selfhosted-operations/selhosted-operations.module.js';
import { SelfHostedOperationsModule } from './selfhosted-operations/selfhosted-operations.module.js';

Copilot uses AI. Check for mistakes.

@Module({
imports: [
Expand Down Expand Up @@ -98,6 +99,7 @@ import { DashboardWidgetModule } from './entities/visualizations/dashboard-widge
SavedDbQueryModule,
DashboardModule,
DashboardWidgetModule,
SelfHostedOperationsModule.register(),
],
controllers: [AppController],
providers: [
Expand Down
3 changes: 3 additions & 0 deletions backend/src/common/data-injection.tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,4 +202,7 @@ export enum UseCaseType {
CREATE_DASHBOARD_WIDGET = 'CREATE_DASHBOARD_WIDGET',
UPDATE_DASHBOARD_WIDGET = 'UPDATE_DASHBOARD_WIDGET',
DELETE_DASHBOARD_WIDGET = 'DELETE_DASHBOARD_WIDGET',

IS_CONFIGURED = 'IS_CONFIGURED',
CREATE_INITIAL_USER = 'CREATE_INITIAL_USER',
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export class AiChatMessageEntity {
@ManyToOne(
() => UserAiChatEntity,
(ai_chat) => ai_chat.messages,
{ onDelete: 'CASCADE' },
)
@JoinColumn({ name: 'ai_chat_id' })
ai_chat: Relation<UserAiChatEntity>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export class UserAiChatEntity {
@ManyToOne(
() => UserEntity,
(user) => user.ai_chats,
{ onDelete: 'CASCADE' },
)
@JoinColumn({ name: 'user_id' })
user: Relation<UserEntity>;
Expand Down
1 change: 1 addition & 0 deletions backend/src/entities/connection/connection.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,7 @@ export class ConnectionEntity {
@ManyToOne(
(_) => CompanyInfoEntity,
(company) => company.connections,
{ onDelete: 'CASCADE' },
)
@JoinTable()
company: Relation<CompanyInfoEntity>;
Expand Down
2 changes: 2 additions & 0 deletions backend/src/exceptions/text/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -382,4 +382,6 @@ export const Messages = {
SECRET_DELETED_SUCCESSFULLY: 'Secret deleted successfully',
USER_NOT_FOUND_OR_NOT_IN_COMPANY: 'User not found or not associated with a company',
PERSONAL_TABLE_SETTINGS_NOT_FOUND: 'Personal table settings with this parameters not found',
SELF_HOSTED_ALREADY_CONFIGURED: 'Instance is already configured',
ENDPOINT_NOT_AVAILABLE_IN_THIS_MODE: 'This endpoint is not available in the current mode',
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { MigrationInterface, QueryRunner } from 'typeorm';

export class AddedCascadeOptionToAiChatEntities1770043047971 implements MigrationInterface {
name = 'AddedCascadeOptionToAiChatEntities1770043047971';

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "ai_chat_message" DROP CONSTRAINT "FK_03bc49058afd5262d6a503bf123"`);
await queryRunner.query(`ALTER TABLE "user_ai_chat" DROP CONSTRAINT "FK_0f95dbd767d42e637345636cb5d"`);
await queryRunner.query(
`ALTER TABLE "ai_chat_message" ADD CONSTRAINT "FK_03bc49058afd5262d6a503bf123" FOREIGN KEY ("ai_chat_id") REFERENCES "user_ai_chat"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "user_ai_chat" ADD CONSTRAINT "FK_0f95dbd767d42e637345636cb5d" FOREIGN KEY ("user_id") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "user_ai_chat" DROP CONSTRAINT "FK_0f95dbd767d42e637345636cb5d"`);
await queryRunner.query(`ALTER TABLE "ai_chat_message" DROP CONSTRAINT "FK_03bc49058afd5262d6a503bf123"`);
await queryRunner.query(
`ALTER TABLE "user_ai_chat" ADD CONSTRAINT "FK_0f95dbd767d42e637345636cb5d" FOREIGN KEY ("user_id") REFERENCES "user"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "ai_chat_message" ADD CONSTRAINT "FK_03bc49058afd5262d6a503bf123" FOREIGN KEY ("ai_chat_id") REFERENCES "user_ai_chat"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { MigrationInterface, QueryRunner } from 'typeorm';

export class AddCascadeOptionToConnectionEntity1770045005400 implements MigrationInterface {
name = 'AddCascadeOptionToConnectionEntity1770045005400';

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "connection" DROP CONSTRAINT "FK_3c56723750fad39864878239cf4"`);
await queryRunner.query(
`ALTER TABLE "connection" ADD CONSTRAINT "FK_3c56723750fad39864878239cf4" FOREIGN KEY ("companyId") REFERENCES "company_info"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "connection" DROP CONSTRAINT "FK_3c56723750fad39864878239cf4"`);
await queryRunner.query(
`ALTER TABLE "connection" ADD CONSTRAINT "FK_3c56723750fad39864878239cf4" FOREIGN KEY ("companyId") REFERENCES "company_info"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export class CreateInitialUserDs {
email: string;
password: string;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsEmail, IsNotEmpty, IsString, MaxLength, MinLength } from 'class-validator';

export class CreateInitialUserDto {
@ApiProperty({ description: 'User email' })
@IsNotEmpty()
@IsString()
@IsEmail()
readonly email: string;

@ApiProperty({ description: 'Admin user password' })
@IsNotEmpty()
@IsString()
@MinLength(8)
@MaxLength(255)
readonly password: string;
Comment on lines +14 to +16

Copilot AI Feb 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The password validation for the initial admin user only uses @minlength(8) and @maxlength(255), but doesn't enforce password strength requirements. Other password operations in the codebase (password reset at backend/src/entities/user/dto/password.dto.ts:9-15, password change at backend/src/entities/user/application/data-structures/change-usual-user-password.ds.ts:15-21) use @IsStrongPassword with requirements for minLowercase, minUppercase, minNumbers. Since this creates the first admin account with full system access, consider using the same @IsStrongPassword validation for better security.

Copilot uses AI. Check for mistakes.
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { ApiProperty } from '@nestjs/swagger';

Copilot AI Feb 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The directory name "responce-objects" contains a typo - it should be "response-objects" (correct spelling). The codebase consistently uses "response-objects" elsewhere (e.g., backend/src/entities/ai/ai-conversation-history/application/response-objects/user-ai-chat.ro.js, backend/src/entities/table-filters/application/response-objects/created-table-filters.ro.js). This deviation from the established convention needs to be corrected.

Copilot uses AI. Check for mistakes.

export class IsConfiguredRo {
@ApiProperty({ example: true, description: 'Indicates whether the self-hosted instance is configured' })
public isConfigured: boolean;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { BadRequestException, Inject, Injectable } from '@nestjs/common';
import AbstractUseCase from '../../../common/abstract-use.case.js';
import { IGlobalDatabaseContext } from '../../../common/application/global-database-context.interface.js';
import { BaseType } from '../../../common/data-injection.tokens.js';
import { SimpleFoundUserInfoDs } from '../../../entities/user/dto/found-user.dto.js';
import { ICreateInitialUserUseCase } from './selfhosted-use-cases.interfaces.js';
import { CreateInitialUserDs } from '../data-structures/create-initial-user.ds.js';
import { isSaaS } from '../../../helpers/app/is-saas.js';
import { Messages } from '../../../exceptions/text/messages.js';
import { RegisterUserDs } from '../../../entities/user/application/data-structures/register-user-ds.js';
import { UserRoleEnum } from '../../../entities/user/enums/user-role.enum.js';
import { buildRegisteringUser } from '../../../entities/user/utils/build-registering-user.util.js';
import { CompanyInfoEntity } from '../../../entities/company-info/company-info.entity.js';
import { Encryptor } from '../../../helpers/encryption/encryptor.js';
import { buildSimpleUserInfoDs } from '../../../entities/user/utils/build-created-user.ds.js';

@Injectable()
export class CreateInitialUserUseCase
extends AbstractUseCase<CreateInitialUserDs, SimpleFoundUserInfoDs>
implements ICreateInitialUserUseCase
{
constructor(
@Inject(BaseType.GLOBAL_DB_CONTEXT)
protected _dbContext: IGlobalDatabaseContext,
) {
super();
}

protected async implementation(inputData: CreateInitialUserDs): Promise<SimpleFoundUserInfoDs> {
if (isSaaS()) {
throw new BadRequestException(Messages.ENDPOINT_NOT_AVAILABLE_IN_THIS_MODE);
}

const userCount = await this._dbContext.userRepository.count();
if (userCount > 0) {
throw new BadRequestException(Messages.SELF_HOSTED_ALREADY_CONFIGURED);
}

const { email, password } = inputData;
const registerUserData: RegisterUserDs = {
email: email,
password: password,
isActive: true,
gclidValue: null,
name: 'Admin',
role: UserRoleEnum.ADMIN,
};

const savedUser = await this._dbContext.userRepository.saveUserEntity(buildRegisteringUser(registerUserData));

const newCompanyInfo = new CompanyInfoEntity();
newCompanyInfo.id = Encryptor.generateUUID();
const savedCompanyInfo = await this._dbContext.companyInfoRepository.save(newCompanyInfo);

savedUser.company = savedCompanyInfo;
const finalUser = await this._dbContext.userRepository.saveUserEntity(savedUser);

return buildSimpleUserInfoDs(finalUser);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { Inject, Injectable } from '@nestjs/common';
import AbstractUseCase from '../../../common/abstract-use.case.js';
import { IGlobalDatabaseContext } from '../../../common/application/global-database-context.interface.js';
import { BaseType } from '../../../common/data-injection.tokens.js';
import { IsConfiguredRo } from '../responce-objects/is-configured.ro.js';

Copilot AI Feb 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The import path contains a typo - "responce-objects" should be "response-objects" (correct spelling). Update this import path once the directory name is corrected to match the codebase convention.

Suggested change
import { IsConfiguredRo } from '../responce-objects/is-configured.ro.js';
import { IsConfiguredRo } from '../response-objects/is-configured.ro.js';

Copilot uses AI. Check for mistakes.
import { IIsConfiguredUseCase } from './selfhosted-use-cases.interfaces.js';
import { isSaaS } from '../../../helpers/app/is-saas.js';

@Injectable()
export class IsConfiguredUseCase extends AbstractUseCase<void, IsConfiguredRo> implements IIsConfiguredUseCase {
constructor(
@Inject(BaseType.GLOBAL_DB_CONTEXT)
protected _dbContext: IGlobalDatabaseContext,
) {
super();
}

protected async implementation(): Promise<IsConfiguredRo> {
if (isSaaS()) {
return { isConfigured: true };
}
const userCount = await this._dbContext.userRepository.count();
return { isConfigured: userCount > 0 };
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { InTransactionEnum } from '../../../enums/index.js';
import { SimpleFoundUserInfoDs } from '../../../entities/user/dto/found-user.dto.js';
import { IsConfiguredRo } from '../responce-objects/is-configured.ro.js';

Copilot AI Feb 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The import path contains a typo - "responce-objects" should be "response-objects" (correct spelling). Update this import path once the directory name is corrected to match the codebase convention.

Suggested change
import { IsConfiguredRo } from '../responce-objects/is-configured.ro.js';
import { IsConfiguredRo } from '../response-objects/is-configured.ro.js';

Copilot uses AI. Check for mistakes.
import { CreateInitialUserDs } from '../data-structures/create-initial-user.ds.js';

export interface IIsConfiguredUseCase {
execute(inputData: undefined, inTransaction: InTransactionEnum): Promise<IsConfiguredRo>;
}

export interface ICreateInitialUserUseCase {
execute(inputData: CreateInitialUserDs, inTransaction: InTransactionEnum): Promise<SimpleFoundUserInfoDs>;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { Body, Controller, Get, HttpStatus, Inject, Post, UseInterceptors } from '@nestjs/common';
import { ApiBody, ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { SentryInterceptor } from '../interceptors/index.js';
import { IsConfiguredRo } from './application/responce-objects/is-configured.ro.js';

Copilot AI Feb 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The import path contains a typo - "responce-objects" should be "response-objects" (correct spelling). Update this import path once the directory name is corrected to match the codebase convention.

Suggested change
import { IsConfiguredRo } from './application/responce-objects/is-configured.ro.js';
import { IsConfiguredRo } from './application/response-objects/is-configured.ro.js';

Copilot uses AI. Check for mistakes.
import { CreateInitialUserDto } from './application/dto/create-initial-admin-user.dto.js';
import { SimpleFoundUserInfoDs } from '../entities/user/dto/found-user.dto.js';
import { UseCaseType } from '../common/data-injection.tokens.js';
import {
IIsConfiguredUseCase,
ICreateInitialUserUseCase,
} from './application/use-cases/selfhosted-use-cases.interfaces.js';
import { InTransactionEnum } from '../enums/index.js';

@UseInterceptors(SentryInterceptor)
@Controller('selfhosted')
@ApiTags('Selfhosted Operations')
export class SelfHostedOperationsController {
constructor(
@Inject(UseCaseType.IS_CONFIGURED)
private readonly isConfiguredUseCase: IIsConfiguredUseCase,
@Inject(UseCaseType.CREATE_INITIAL_USER)
private readonly createInitialUserUseCase: ICreateInitialUserUseCase,
) {}

@Get('/is-configured')
@ApiOperation({ summary: 'Check if self-hosted instance is configured' })
@ApiResponse({
status: HttpStatus.OK,
description: 'Returns whether the instance is configured',
type: IsConfiguredRo,
})
public async isConfigured(): Promise<IsConfiguredRo> {
return await this.isConfiguredUseCase.execute(undefined, InTransactionEnum.OFF);
}

@Post('/initial-user')
@ApiOperation({ summary: 'Create initial user for self-hosted instance' })
@ApiBody({ type: CreateInitialUserDto })
@ApiResponse({
status: HttpStatus.CREATED,
description: 'Initial user created successfully',
type: SimpleFoundUserInfoDs,
})
@ApiResponse({
status: HttpStatus.BAD_REQUEST,
description: 'Instance already configured or endpoint not available in SaaS mode',
})
public async createInitialUser(@Body() createInitialUserDto: CreateInitialUserDto): Promise<SimpleFoundUserInfoDs> {
return await this.createInitialUserUseCase.execute(createInitialUserDto, InTransactionEnum.OFF);

Copilot AI Feb 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Creating the initial user involves multiple database operations (creating a user, creating a company, and linking them). This critical operation should use InTransactionEnum.ON instead of InTransactionEnum.OFF to ensure atomicity. If any step fails (e.g., company creation fails after user creation), without a transaction you could end up with an orphan user entity and inconsistent database state. This pattern is used for other multi-step create operations in the codebase (e.g., backend/src/entities/connection/connection.controller.ts:285).

Suggested change
return await this.createInitialUserUseCase.execute(createInitialUserDto, InTransactionEnum.OFF);
return await this.createInitialUserUseCase.execute(createInitialUserDto, InTransactionEnum.ON);

Copilot uses AI. Check for mistakes.
}
}
45 changes: 45 additions & 0 deletions backend/src/selfhosted-operations/selhosted-operations.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { DynamicModule, Module } from '@nestjs/common';

Copilot AI Feb 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The filename "selhosted-operations.module.ts" contains a typo - it should be "selfhosted-operations.module.ts" (missing the 'f'). This inconsistency with the module class name SelfHostedOperationsModule and the directory name selfhosted-operations should be corrected.

Copilot uses AI. Check for mistakes.
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserEntity } from '../entities/user/user.entity.js';
import { CompanyInfoEntity } from '../entities/company-info/company-info.entity.js';
import { SelfHostedOperationsController } from './selfhosted-operations.controller.js';
import { GlobalDatabaseContext } from '../common/application/global-database-context.js';
import { BaseType, UseCaseType } from '../common/data-injection.tokens.js';
import { IsConfiguredUseCase } from './application/use-cases/is-configured.use.case.js';
import { CreateInitialUserUseCase } from './application/use-cases/create-initial-user.use.case.js';
import { isSaaS } from '../helpers/app/is-saas.js';

@Module({})
export class SelfHostedOperationsModule {
static register(): DynamicModule {
if (isSaaS()) {
// Return empty module in SaaS mode
return {
module: SelfHostedOperationsModule,
imports: [],
controllers: [],
providers: [],
};
}

return {
module: SelfHostedOperationsModule,
imports: [TypeOrmModule.forFeature([UserEntity, CompanyInfoEntity])],
controllers: [SelfHostedOperationsController],
providers: [
{
provide: BaseType.GLOBAL_DB_CONTEXT,
useClass: GlobalDatabaseContext,
},
{
provide: UseCaseType.IS_CONFIGURED,
useClass: IsConfiguredUseCase,
},
{
provide: UseCaseType.CREATE_INITIAL_USER,
useClass: CreateInitialUserUseCase,
},
],
};
}
}
Loading
Loading