From 6a3b1776d82c67a415bfc53123fc00215431f073 Mon Sep 17 00:00:00 2001 From: Kifungo A <45813955+adkif@users.noreply.github.com> Date: Sun, 28 Jan 2024 21:55:22 +0000 Subject: [PATCH 01/17] Feat: create new abstraction to for secured server --- .../src/lib/server/secured-proxy.ts | 96 +++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 packages/desktop-libs/src/lib/server/secured-proxy.ts diff --git a/packages/desktop-libs/src/lib/server/secured-proxy.ts b/packages/desktop-libs/src/lib/server/secured-proxy.ts new file mode 100644 index 00000000000..228050b9b57 --- /dev/null +++ b/packages/desktop-libs/src/lib/server/secured-proxy.ts @@ -0,0 +1,96 @@ +import { IServerConfig, IServerFactory } from '../interfaces'; +import { BaseReverseProxy } from '../decorators'; +import { ISsl } from '@gauzy/contracts'; +import { IpcMainEvent, ipcMain } from 'electron'; +import { IncomingMessage, ServerResponse } from 'http'; +import { ServerOptions } from 'http-proxy'; +import { LOCAL_SERVER_UPDATE_CONFIG } from '../config'; +import { ISslFactory } from '../interfaces/i-server-factory'; +import { SslFactory } from './ssl-factory'; +import { ServerFactory } from './server-factory'; + +export abstract class SecuredProxy extends BaseReverseProxy { + private readonly sslFactory: ISslFactory; + private readonly serverFactory: IServerFactory; + + constructor(public readonly serverConfig: IServerConfig) { + super(serverConfig); + this.sslFactory = new SslFactory(); + this.serverFactory = new ServerFactory(); + this.setupIpcMain(); + } + + public override start(): void { + if (!this.serverConfig.setting.secureProxy.enable) { + return; + } + this.preprocess(); + super.start(); + } + + public override stop(): void { + if (!this.serverConfig.setting.secureProxy.enable || !this.running) { + return; + } + super.stop(); + } + + protected preprocess(): void { + const sslConfig: ISsl = this.sslFactory.createSslConfig(this.serverConfig.setting.secureProxy); + this.kill(); + this.configureProxy(sslConfig); + this.createServerWithSsl(sslConfig); + } + + protected configureProxy(sslConfig: ISsl): void { + this.app.all('*', (req: IncomingMessage, res: ServerResponse) => { + const proxyOptions: ServerOptions = { + changeOrigin: true, + target: { host: 'localhost', port: this.port }, + cookiePathRewrite: { + 'http://localhost:3000/public': `${this.serverConfig.uiHostName}:${this.port}/public` + } + }; + + // Enable secure proxy if configured + if (this.serverConfig.setting.secureProxy.enable) { + proxyOptions.ssl = sslConfig; + proxyOptions.secure = this.serverConfig.setting.secureProxy.secure; + } + + this._proxy.web(req, res, proxyOptions); + }); + } + + protected createServerWithSsl(sslConfig: ISsl): void { + this.server = this.serverFactory.createServer(sslConfig, this.app); + } + + protected setupIpcMain(): void { + ipcMain.removeAllListeners('check_ssl'); + ipcMain.on('check_ssl', (event) => { + this.checkSsl(event); + }); + } + + protected checkSsl(event: IpcMainEvent): void { + try { + const sslConfig = this.sslFactory.createSslConfig(this.serverConfig.setting.secureProxy); + const server = this.serverFactory.createServer(sslConfig, this.app); + + server.on('error', (error) => { + console.error(`Server error: ${error}`); + event.sender.send('check_ssl', { status: false, message: `Server error: ${error}` }); + }); + + server.listen(LOCAL_SERVER_UPDATE_CONFIG.TEST_SSL_PORT, () => { + console.log(`Key and certificate are valid`); + server.close(); + event.sender.send('check_ssl', { status: true, message: `Key and certificate are valid` }); + }); + } catch (error) { + console.error(`Error in SSL configuration: ${error}`); + event.sender.send('check_ssl', { status: false, message: `Error in SSL configuration: ${error}` }); + } + } +} From d33c47cada808f7e9cbcdafaa275fb7d9141ad33 Mon Sep 17 00:00:00 2001 From: RAHUL RATHORE <41804588+rahul-rocket@users.noreply.github.com> Date: Thu, 1 Feb 2024 23:47:19 +0530 Subject: [PATCH 02/17] fix: escape query with parameters for pagination --- .../invoices-received.component.ts | 2 +- .../app/pages/invoices/invoices.component.ts | 4 +- .../proposal-template.component.html | 2 +- .../core/src/core/crud/pagination-params.ts | 32 ++++------ .../core/src/core/crud/pagination.helper.ts | 60 +++++++++++++++++++ .../get-employee-job-statistics.command.ts | 4 +- .../get-employee-job-statistics.handler.ts | 47 ++++++++++----- .../core/src/employee/employee.controller.ts | 4 +- .../core/src/employee/employee.service.ts | 4 +- 9 files changed, 113 insertions(+), 46 deletions(-) create mode 100644 packages/core/src/core/crud/pagination.helper.ts diff --git a/apps/gauzy/src/app/pages/invoices/invoices-received/invoices-received.component.ts b/apps/gauzy/src/app/pages/invoices/invoices-received/invoices-received.component.ts index 1e15c4b6fcf..9a7d4eaedc6 100644 --- a/apps/gauzy/src/app/pages/invoices/invoices-received/invoices-received.component.ts +++ b/apps/gauzy/src/app/pages/invoices/invoices-received/invoices-received.component.ts @@ -201,7 +201,7 @@ export class InvoicesReceivedComponent extends PaginationFilterBaseComponent imp where: { sentTo: organizationId, tenantId, - isEstimate: this.isEstimate === true ? 1 : 0, + isEstimate: this.isEstimate, invoiceDate: { startDate: toUTC(startDate).format('YYYY-MM-DD HH:mm:ss'), endDate: toUTC(endDate).format('YYYY-MM-DD HH:mm:ss') diff --git a/apps/gauzy/src/app/pages/invoices/invoices.component.ts b/apps/gauzy/src/app/pages/invoices/invoices.component.ts index 6760379b588..6296998b735 100644 --- a/apps/gauzy/src/app/pages/invoices/invoices.component.ts +++ b/apps/gauzy/src/app/pages/invoices/invoices.component.ts @@ -765,8 +765,8 @@ export class InvoicesComponent extends PaginationFilterBaseComponent implements where: { organizationId, tenantId, - isEstimate: this.isEstimate === true ? 1 : 0, - isArchived: this.includeArchived === true ? 1 : 0, + isEstimate: this.isEstimate, + isArchived: this.includeArchived, invoiceDate: { startDate: toUTC(startDate).format('YYYY-MM-DD HH:mm:ss'), endDate: toUTC(endDate).format('YYYY-MM-DD HH:mm:ss'), diff --git a/apps/gauzy/src/app/pages/jobs/proposal-template/proposal-template/proposal-template.component.html b/apps/gauzy/src/app/pages/jobs/proposal-template/proposal-template/proposal-template.component.html index 3ad8f408b0f..593b9aa667c 100644 --- a/apps/gauzy/src/app/pages/jobs/proposal-template/proposal-template/proposal-template.component.html +++ b/apps/gauzy/src/app/pages/jobs/proposal-template/proposal-template/proposal-template.component.html @@ -127,7 +127,7 @@

style="cursor: pointer" [settings]="smartTableSettings" [source]="smartTableSource" - (userRowSelect)="selectItem($event)" + (userRowSelect)="selectProposalTemplate($event)" >
diff --git a/packages/core/src/core/crud/pagination-params.ts b/packages/core/src/core/crud/pagination-params.ts index 685e6614707..fb4ded005a9 100644 --- a/packages/core/src/core/crud/pagination-params.ts +++ b/packages/core/src/core/crud/pagination-params.ts @@ -4,10 +4,11 @@ import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; import { FindOptionsOrder, FindOptionsRelations, FindOptionsSelect, FindOptionsWhere } from 'typeorm'; -import { Transform, TransformFnParams, Type } from 'class-transformer'; +import { Transform, TransformFnParams, Type, plainToClass } from 'class-transformer'; import { IsNotEmpty, IsOptional, Max, Min, ValidateNested } from 'class-validator'; -import { isClassInstance, isObject, parseToBoolean } from '@gauzy/common'; +import { parseToBoolean } from '@gauzy/common'; import { TenantOrganizationBaseDTO } from './../../core/dto'; +import { SimpleObjectLiteral, convertNativeParameters, parseObject } from './pagination.helper'; /** * Specifies what columns should be retrieved. @@ -45,6 +46,7 @@ export class OptionParams extends OptionsRelations { @IsNotEmpty() @ValidateNested({ each: true }) @Type(() => TenantOrganizationBaseDTO) + @Transform(({ value }: TransformFnParams) => value ? escapeQueryWithParameters(value) : {}) readonly where: FindOptionsWhere; /** @@ -81,22 +83,14 @@ export class PaginationParams extends OptionParams { } /** - * Parse object to specific type - * - * @param source - * @returns + * Function to escape query parameters and convert to DTO class. + * @param nativeParameters - The original query parameters. + * @returns {TenantOrganizationBaseDTO} - The escaped and converted query parameters as a DTO instance. */ -export function parseObject(source: Object, callback: Function) { - if (isObject(source)) { - for (const key in source) { - if (isObject(source[key])) { - if (!isClassInstance(source[key])) { - parseObject(source[key], callback); - } - } else { - Object.assign(source, { [key]: callback(source[key]) }) - } - } - } - return source; +export function escapeQueryWithParameters(nativeParameters: SimpleObjectLiteral): TenantOrganizationBaseDTO { + // Convert native parameters based on the database connection type + const builtParameters: SimpleObjectLiteral = convertNativeParameters(nativeParameters); + + // Convert to DTO class using class-transformer's plainToClass + return plainToClass(TenantOrganizationBaseDTO, builtParameters, { enableImplicitConversion: true }); } diff --git a/packages/core/src/core/crud/pagination.helper.ts b/packages/core/src/core/crud/pagination.helper.ts new file mode 100644 index 00000000000..a7f4e1ae515 --- /dev/null +++ b/packages/core/src/core/crud/pagination.helper.ts @@ -0,0 +1,60 @@ +import { isClassInstance, isObject } from "@gauzy/common"; + +/** + * Interface of the simple literal object with any string keys. + */ +export interface SimpleObjectLiteral { + [key: string]: any; +} + +/** + * Parses the given value and converts it to a boolean using JSON.parse. + * + * @param value - The value to be parsed. + * @returns {boolean} - The boolean representation of the parsed value. + */ +export const parseBool = (value: any): boolean => Boolean(JSON.parse(value)); + +/** + * Converts native parameters based on the database connection type. + * + * @param parameters - The parameters to be converted. + * @returns {any} - The converted parameters based on the database connection type. + */ +export const convertNativeParameters = (parameters: any): any => { + try { + // Mapping boolean values to their numeric representation + if (typeof parameters === "object" && parameters !== null) { + // Recursively convert nested objects + return Object.keys(parameters).reduce((acc, key) => { + acc[key] = convertNativeParameters(parameters[key]); + return acc; + }, {} as SimpleObjectLiteral); + } else { + return parseBool(parameters); + } + } catch (error) { + return parameters; + } +}; + +/** + * Parse object to specific type + * + * @param source + * @returns + */ +export function parseObject(source: Object, callback: Function) { + if (isObject(source)) { + for (const key in source) { + if (isObject(source[key])) { + if (!isClassInstance(source[key])) { + parseObject(source[key], callback); + } + } else { + Object.assign(source, { [key]: callback(source[key]) }) + } + } + } + return source; +} diff --git a/packages/core/src/employee/commands/get-employee-job-statistics.command.ts b/packages/core/src/employee/commands/get-employee-job-statistics.command.ts index a16421098ba..06af227e9a6 100644 --- a/packages/core/src/employee/commands/get-employee-job-statistics.command.ts +++ b/packages/core/src/employee/commands/get-employee-job-statistics.command.ts @@ -6,6 +6,6 @@ export class GetEmployeeJobStatisticsCommand implements ICommand { static readonly type = '[EmployeeJobStatistics] Get'; constructor( - public readonly request: PaginationParams - ) {} + public readonly options: PaginationParams + ) { } } diff --git a/packages/core/src/employee/commands/handlers/get-employee-job-statistics.handler.ts b/packages/core/src/employee/commands/handlers/get-employee-job-statistics.handler.ts index c6ab01b40b9..e3e367975dd 100644 --- a/packages/core/src/employee/commands/handlers/get-employee-job-statistics.handler.ts +++ b/packages/core/src/employee/commands/handlers/get-employee-job-statistics.handler.ts @@ -1,35 +1,50 @@ import { CommandHandler, ICommandHandler } from '@nestjs/cqrs'; import { GauzyAIService } from '@gauzy/integration-ai'; import { IEmployee, IPagination } from '@gauzy/contracts'; -import { indexBy } from 'underscore'; import { EmployeeService } from '../../employee.service'; import { GetEmployeeJobStatisticsCommand } from '../get-employee-job-statistics.command'; @CommandHandler(GetEmployeeJobStatisticsCommand) -export class GetEmployeeJobStatisticsHandler - implements ICommandHandler { +export class GetEmployeeJobStatisticsHandler implements ICommandHandler { + /** + * + * @param employeeService + * @param gauzyAIService + */ constructor( private readonly employeeService: EmployeeService, private readonly gauzyAIService: GauzyAIService ) { } + /** + * Executes the GetEmployeeJobStatisticsCommand to fetch paginated employee data + * and augment it with additional statistics. + * + * @param command - The command containing options for pagination. + * @returns A Promise resolving to an IPagination with augmented data. + */ public async execute(command: GetEmployeeJobStatisticsCommand): Promise> { - const { request } = command; + const { options } = command; - let { items, total } = await this.employeeService.paginate(request); - const employeesStatistics = await this.gauzyAIService.getEmployeesStatistics(); - const employeesStatisticsById = indexBy( - employeesStatistics, - 'employeeId' + // Use Promise.all for concurrent requests + const [paginationResult, employeesStatistics] = await Promise.all([ + this.employeeService.paginate(options), + this.gauzyAIService.getEmployeesStatistics() + ]); + + let { items, total } = paginationResult; + + // Create a map for faster lookup + const employeesStatisticsById = new Map( + employeesStatistics.map((statistic: any) => [statistic.employeeId, statistic]) ); - items = items.map((employee) => { - const employeesStatistic = employeesStatisticsById[employee.id]; - return { - ...employee, - ...employeesStatistic - }; - }); + // Combine mappings into a single map function + items = items.map((employee: IEmployee) => ({ + ...employee, + ...employeesStatisticsById.get(employee.id) || {} // Use empty object if not found + })); + return { items, total }; } } diff --git a/packages/core/src/employee/employee.controller.ts b/packages/core/src/employee/employee.controller.ts index beaf695a53a..4c39ce0d440 100644 --- a/packages/core/src/employee/employee.controller.ts +++ b/packages/core/src/employee/employee.controller.ts @@ -211,9 +211,9 @@ export class EmployeeController extends CrudController { @Get('pagination') @UsePipes(new ValidationPipe({ transform: true })) async pagination( - @Query() options: PaginationParams + @Query() params: PaginationParams ): Promise> { - return await this.employeeService.pagination(options); + return await this.employeeService.pagination(params); } /** diff --git a/packages/core/src/employee/employee.service.ts b/packages/core/src/employee/employee.service.ts index a0a2ede635b..31b0bf4ce6a 100644 --- a/packages/core/src/employee/employee.service.ts +++ b/packages/core/src/employee/employee.service.ts @@ -216,15 +216,13 @@ export class EmployeeService extends TenantAwareCrudService { ); // Additional conditions based on the provided 'where' object if (isNotEmpty(where)) { - const parseBool = (value: any) => Boolean(JSON.parse(value)); - // Apply conditions for specific fields in the Employee entity qb.andWhere( new Brackets((web: WhereExpressionBuilder) => { const fields = ['isActive', 'isArchived', 'isTrackingEnabled', 'allowScreenshotCapture']; fields.forEach((key: string) => { if (key in where) { - web.andWhere(p(`${qb.alias}.${key} = :${key}`), { [key]: parseBool(where[key]) }); + web.andWhere(p(`${qb.alias}.${key} = :${key}`), { [key]: where[key] }); } }); }) From ab9781f5a99f3481262e0fa95854b5545bd12af9 Mon Sep 17 00:00:00 2001 From: Kifungo A <45813955+adkif@users.noreply.github.com> Date: Thu, 1 Feb 2024 21:39:14 +0000 Subject: [PATCH 03/17] feat: Add SSL factory interface and implementation Added IServerFactory interface with createServer method for SSL configuration, as well as SslFactory class implementation. Also, updated SSL component with new button functionality for SSL checking and hiding. Introduces better SSL configuration and management. No associated issues. --- .../src/lib/interfaces/i-ssl-factory.ts | 7 +++++ .../src/lib/server/ssl-factory.ts | 17 +++++++++++ .../src/lib/settings/ssl/ssl.component.html | 22 +++++++++++++- .../src/lib/settings/ssl/ssl.component.ts | 30 +++++++++++++++++++ 4 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 packages/desktop-libs/src/lib/interfaces/i-ssl-factory.ts create mode 100644 packages/desktop-libs/src/lib/server/ssl-factory.ts diff --git a/packages/desktop-libs/src/lib/interfaces/i-ssl-factory.ts b/packages/desktop-libs/src/lib/interfaces/i-ssl-factory.ts new file mode 100644 index 00000000000..380d537bbc8 --- /dev/null +++ b/packages/desktop-libs/src/lib/interfaces/i-ssl-factory.ts @@ -0,0 +1,7 @@ +import { ISsl } from '@gauzy/contracts'; +import { Express } from 'express'; +import { Server } from 'http'; + +export interface IServerFactory { + createServer(sslConfig: ISsl, app: Express): Server; +} diff --git a/packages/desktop-libs/src/lib/server/ssl-factory.ts b/packages/desktop-libs/src/lib/server/ssl-factory.ts new file mode 100644 index 00000000000..75b80724ec5 --- /dev/null +++ b/packages/desktop-libs/src/lib/server/ssl-factory.ts @@ -0,0 +1,17 @@ +import * as fs from 'fs'; +import { IProxyConfig, ISsl } from '@gauzy/contracts'; +import { ISslFactory } from '../interfaces/i-server-factory'; + +export class SslFactory implements ISslFactory { + public createSslConfig(config: IProxyConfig): ISsl { + try { + return { + key: fs.readFileSync(config.ssl.key, 'utf8'), + cert: fs.readFileSync(config.ssl.cert, 'utf8') + }; + } catch (error) { + console.error('ERROR: Reading SSL configuration:', error); + throw error; + } + } +} diff --git a/packages/desktop-ui-lib/src/lib/settings/ssl/ssl.component.html b/packages/desktop-ui-lib/src/lib/settings/ssl/ssl.component.html index 11b66c85bbc..87fbb81c3d3 100644 --- a/packages/desktop-ui-lib/src/lib/settings/ssl/ssl.component.html +++ b/packages/desktop-ui-lib/src/lib/settings/ssl/ssl.component.html @@ -73,7 +73,7 @@
-
+
@@ -86,6 +86,26 @@
+
+
+ +
+
+ +
+ {{ (isValid$ | async)?.message }} +
+
+
diff --git a/packages/desktop-ui-lib/src/lib/settings/ssl/ssl.component.ts b/packages/desktop-ui-lib/src/lib/settings/ssl/ssl.component.ts index 7083604f9ed..a248ff4e4c8 100644 --- a/packages/desktop-ui-lib/src/lib/settings/ssl/ssl.component.ts +++ b/packages/desktop-ui-lib/src/lib/settings/ssl/ssl.component.ts @@ -1,6 +1,12 @@ import { Component, EventEmitter, Input, NgZone, OnInit, Output } from '@angular/core'; import { ElectronService } from '@gauzy/desktop-ui-lib'; import { IProxyConfig } from '@gauzy/contracts'; +import { BehaviorSubject } from 'rxjs'; + +interface ICheckSslResponse { + status: boolean; + message: string; +} @Component({ selector: 'gauzy-ssl', @@ -8,12 +14,19 @@ import { IProxyConfig } from '@gauzy/contracts'; styleUrls: ['./ssl.component.scss'] }) export class SslComponent implements OnInit { + public isCheckSsl$: BehaviorSubject; + public isValid$: BehaviorSubject; + public isHidden$: BehaviorSubject; private _config: IProxyConfig; + @Output() public update: EventEmitter; constructor(private readonly electronService: ElectronService, private readonly ngZone: NgZone) { this.update = new EventEmitter(); + this.isCheckSsl$ = new BehaviorSubject(false); + this.isHidden$ = new BehaviorSubject(true); + this.isValid$ = new BehaviorSubject({ status: true, message: '' }); } ngOnInit(): void { @@ -22,6 +35,14 @@ export class SslComponent implements OnInit { this.config = config?.secureProxy; }) ); + + this.electronService.ipcRenderer.on('check_ssl', (event, response: ICheckSslResponse) => + this.ngZone.run(() => { + this.isValid$.next(response); + this.isHidden$.next(false); + this.isCheckSsl$.next(false); + }) + ); } public get config(): IProxyConfig { @@ -42,4 +63,13 @@ export class SslComponent implements OnInit { public save(event: string): void { this.electronService.ipcRenderer.send('save_encrypted_file', event); } + + public checkSsl(): void { + this.isCheckSsl$.next(true); + this.electronService.ipcRenderer.send('check_ssl'); + } + + public onHide(): void { + this.isHidden$.next(true); + } } From 5e432b1096f04bb91e7b33adce01a18a544502c1 Mon Sep 17 00:00:00 2001 From: Kifungo A <45813955+adkif@users.noreply.github.com> Date: Thu, 1 Feb 2024 21:40:38 +0000 Subject: [PATCH 04/17] refactor: server process initialization and error handling Restructured server process initialization for improved error handling and added error logging in the UI server. Extracted server process creation and preparation to separate factory classes. This enhances code organization and maintainability. Introduced a new `ServerManager` class to handle server processes. --- apps/server/src/preload/desktop-server-api.ts | 162 ++++++++++-------- apps/server/src/preload/desktop-server-ui.ts | 85 +++++---- apps/server/src/preload/loginPage.ts | 12 -- apps/server/src/preload/server-manager.ts | 17 ++ apps/server/src/preload/static-file-server.ts | 54 ++++++ apps/server/src/preload/ui-server.ts | 32 ++-- 6 files changed, 226 insertions(+), 136 deletions(-) delete mode 100644 apps/server/src/preload/loginPage.ts create mode 100644 apps/server/src/preload/server-manager.ts create mode 100644 apps/server/src/preload/static-file-server.ts diff --git a/apps/server/src/preload/desktop-server-api.ts b/apps/server/src/preload/desktop-server-api.ts index 9dbfb1650a2..e9852e2d10a 100644 --- a/apps/server/src/preload/desktop-server-api.ts +++ b/apps/server/src/preload/desktop-server-api.ts @@ -1,85 +1,99 @@ -import { fork } from 'child_process'; +import { fork, ChildProcessWithoutNullStreams } from 'child_process'; import { LocalStore } from '@gauzy/desktop-libs'; -export interface IEnvApi { - IS_ELECTRON: string, - DB_PATH: string, - DB_TYPE: string, - DB_HOST: string, - DB_PORT: string, - DB_NAME: string, - DB_USER: string, - DB_PASS: string, - API_PORT: string, - API_HOST: string, - API_BASE_URL: string +interface IEnvApi { + IS_ELECTRON: string; + DB_PATH: string; + DB_TYPE: string; + DB_HOST?: string; + DB_PORT?: string; + DB_NAME?: string; + DB_USER?: string; + DB_PASS?: string; + API_PORT: string; + API_HOST: string; + API_BASE_URL: string; } +class ApiServerProcessFactory { + public static createApiServerProcess(): ChildProcessWithoutNullStreams { + try { + const { apiPath, db, dbName, dbPassword, dbUsername, dbPort, port, dbPath, dbHost, apiBaseUrl, apiHost } = + this.prepareServerApi(); -const runServerApi = () => { - const { apiPath, db, dbName, dbPassword, dbUsername, dbPort, port, dbPath, dbHost, apiBaseUrl, apiHost } = prepareServerApi(); - const apiEnv: IEnvApi = { - IS_ELECTRON: 'true', - DB_PATH: dbPath, - DB_TYPE: db, - DB_HOST: dbHost, - DB_PORT: String(dbPort), - DB_NAME: dbName, - DB_USER: dbUsername, - DB_PASS: dbPassword, - API_PORT: String(port), - API_HOST: apiHost, - API_BASE_URL: apiBaseUrl - } - const uiService = fork(apiPath, { - silent: true, detached: true, env: { - ...process.env, - IS_ELECTRON: apiEnv.IS_ELECTRON - }}); - uiService.stdout.on('data', (data) => { - console.log('SERVER API STATE LOGS -> ', data.toString()); - uiService.unref(); - process.exit(0); - }); + const apiEnv: IEnvApi = { + IS_ELECTRON: 'true', + DB_PATH: dbPath, + DB_TYPE: db, + DB_HOST: dbHost || '', + DB_PORT: dbPort ? String(dbPort) : '', + DB_NAME: dbName || '', + DB_USER: dbUsername || '', + DB_PASS: dbPassword || '', + API_PORT: String(port), + API_HOST: apiHost, + API_BASE_URL: apiBaseUrl + }; + + const uiService = fork(apiPath, { + silent: true, + detached: true, + env: { + ...process.env, + ...apiEnv + } + }); + + uiService.stdout.on('data', (data) => { + console.log('SERVER API STATE LOGS -> ', data.toString()); + uiService.unref(); + process.exit(0); + }); + + return uiService; + } catch (error) { + console.error('[CRITICAL::ERROR]: Running API server failed:', error); + } + } + + private static prepareServerApi(): { + apiPath: string; + db: string; + dbPort: number | null; + dbName: string | null; + dbUsername: string | null; + dbPassword: string | null; + port: number; + dbPath: string; + dbHost: string | null; + apiBaseUrl: string; + apiHost: string; + } { + const { port, db, apiPath, dbPath, postgres, apiBaseUrl } = LocalStore.getStore('configs'); + + return { + apiPath, + db, + dbPort: postgres?.dbPort || null, + dbName: postgres?.dbName || null, + dbPassword: postgres?.dbPassword || null, + dbUsername: postgres?.dbUsername || null, + dbHost: postgres?.dbHost || null, + port, + dbPath, + apiBaseUrl, + apiHost: '0.0.0.0' + }; + } } -const prepareServerApi = (): { - apiPath: string, - db: string, - dbPort: number | null, - dbName: string | null, - dbUsername: string | null, - dbPassword: string | null, - port: number, - dbPath: string, - dbHost: string | null, - apiBaseUrl: string, - apiHost: string -} => { - const { - port, - db, - apiPath, - dbPath, - postgres, - apiBaseUrl - } = LocalStore.getStore('configs'); - return { - apiPath, - db, - dbPort: postgres?.dbPort || null, - dbName: postgres?.dbName || null, - dbPassword: postgres?.dbPassword || null, - dbUsername: postgres?.dbUsername || null, - dbHost: postgres?.dbHost || null, - port, - dbPath, - apiBaseUrl, - apiHost: '0.0.0.0' - }; +class App { + public static main(): void { + ApiServerProcessFactory.createApiServerProcess(); + } } export default function () { - console.log('Before Run Api Server'); - runServerApi(); + console.log('Before running API Server'); + App.main(); } diff --git a/apps/server/src/preload/desktop-server-ui.ts b/apps/server/src/preload/desktop-server-ui.ts index c703e9c4565..6acb4fa0ea2 100644 --- a/apps/server/src/preload/desktop-server-ui.ts +++ b/apps/server/src/preload/desktop-server-ui.ts @@ -1,38 +1,59 @@ -import { spawn } from 'child_process'; +import { spawn, ChildProcessWithoutNullStreams } from 'child_process'; import path from 'path'; import { app } from 'electron'; import os from 'os'; -const appPath = app.getPath('userData'); - -const runServerUI = () => { - try { - const { uiPath } = prepareServerUi(); - console.log('ui path', uiPath); - const uiService = spawn(uiPath, { detached: true}); - uiService.stdout.on('data', (data) => { - console.log('SERVER UI STATE LOGS -> ', data.toString()); - }); - } catch (error) { - console.log('error on runserverui', error); - } + +class ServerProcessFactory { + public static createUiServerProcess(): ChildProcessWithoutNullStreams { + const appPath = app.getPath('userData'); + const uiPath = this.prepareServerUi(appPath); + console.log('UI Path:', uiPath); + + const uiService = spawn(uiPath, { detached: true, stdio: 'pipe' }); + + uiService.stdout.on('data', (data) => { + console.log('SERVER UI STATE LOGS -> ', data.toString()); + }); + + uiService.stderr.on('data', (data) => { + console.error('SERVER UI ERROR LOGS -> ', data.toString()); + }); + + uiService.on('error', (error) => { + console.error('Failed to start UI server:', error); + }); + + uiService.on('exit', (code, signal) => { + console.log(`UI server exited with code ${code} and signal ${signal}`); + }); + + return uiService; + } + + private static prepareServerUi(appPath: string): string { + let appName = ''; + switch (os.platform()) { + case 'win32': + appName = `${process.env.NAME}.exe`; + break; + case 'darwin': + appName = process.env.NAME || ''; + break; + default: + break; + } + return path.join(appPath, appName); + } } -const prepareServerUi = (): { - uiPath: string -} => { - let appName:string = ''; - switch (os.platform()) { - case 'win32': - appName = `${process.env.NAME}.exe`; - break; - case 'darwin': - appName = process.env.NAME; - break; - default: - break; - } - return { - uiPath: path.join(appPath, appName) - }; +class App { + public static main(): void { + try { + ServerProcessFactory.createUiServerProcess(); + } catch (error) { + console.error('[CRITICAL::ERROR]: Starting server:', error); + } + } } -runServerUI(); + +App.main(); diff --git a/apps/server/src/preload/loginPage.ts b/apps/server/src/preload/loginPage.ts deleted file mode 100644 index 5c0b94f1647..00000000000 --- a/apps/server/src/preload/loginPage.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { ipcRenderer } from 'electron'; - -ipcRenderer.on('hide_register', () => { - const waitElement = setInterval(() => { - try { - document - .querySelector('[aria-label="Register"]') - .setAttribute('style', 'display: none'); - clearInterval(waitElement); - } catch (error) {} - }); -}); diff --git a/apps/server/src/preload/server-manager.ts b/apps/server/src/preload/server-manager.ts new file mode 100644 index 00000000000..3530fe015b2 --- /dev/null +++ b/apps/server/src/preload/server-manager.ts @@ -0,0 +1,17 @@ +import { StaticFileServer } from './static-file-server'; + +export class ServerManager { + private staticFileServer: StaticFileServer; + + public constructor() { + this.staticFileServer = StaticFileServer.getInstance(); + } + + public runServer(port: number) { + try { + this.staticFileServer.startServer(port); + } catch (error) { + console.error('[CRITICAL::ERROR]: Starting server:', error); + } + } +} diff --git a/apps/server/src/preload/static-file-server.ts b/apps/server/src/preload/static-file-server.ts new file mode 100644 index 00000000000..100b550a2ec --- /dev/null +++ b/apps/server/src/preload/static-file-server.ts @@ -0,0 +1,54 @@ +import http from 'http'; +import path from 'path'; +import { parse } from 'url'; +import { Server as NodeStaticServer } from 'node-static'; +import { IncomingMessage, ServerResponse } from 'http'; + +export class StaticFileServer { + private static instance: StaticFileServer; + private fileServer: NodeStaticServer; + private isPackaged: boolean; + private dirUi: string; + + private constructor() { + this.isPackaged = process.env.isPackaged === 'true'; + this.dirUi = this.isPackaged + ? path.join(__dirname, '..', '..', 'data', 'ui') + : path.join(__dirname, '..', 'data', 'ui'); + this.fileServer = new NodeStaticServer(this.dirUi); + } + + public serveFile(req: IncomingMessage, res: ServerResponse): void { + this.fileServer.serve(req, res, (err: any | null, result: any) => { + if (err) { + console.error(`Error serving ${req.url} - ${err.message}`); + res.writeHead(err.status || 500, err.headers || {}); + res.end(); + } else { + console.log('UI server started'); + console.log(JSON.stringify(parse(req.url || '', true).query)); + } + }); + } + + public startServer(port: number): void { + const server = http.createServer((req, res) => this.serveFile(req, res)); + + server.on('listening', () => { + console.log(`Listening on port ${port}`); + }); + + server.on('error', (error: Error) => { + console.error(`[CRITICAL::ERROR]: Server error: ${error}`); + }); + + server.listen(port, '0.0.0.0'); + } + + public static getInstance(): StaticFileServer { + if (!StaticFileServer.instance) { + StaticFileServer.instance = new StaticFileServer(); + } + return StaticFileServer.instance; + } +} diff --git a/apps/server/src/preload/ui-server.ts b/apps/server/src/preload/ui-server.ts index 993a3c259dc..426260968b4 100644 --- a/apps/server/src/preload/ui-server.ts +++ b/apps/server/src/preload/ui-server.ts @@ -1,22 +1,18 @@ +import { ServerManager } from './server-manager'; -import http from 'http'; -import path from 'path'; -const serverStatic = require('node-static'); -const dirUi = process.env.isPackaged === 'true' ? path.join(__dirname, '..', '..', 'data', 'ui') : path.join(__dirname, '..', 'data', 'ui'); -const file = new(serverStatic.Server)(dirUi); -const url = require('url'); -console.log('server started'); +class App { + public static main(): void { + try { + const portUi = process.env.UI_PORT ? Number(process.env.UI_PORT) : 4200; + const serverManager = new ServerManager(); -async function runServer() { - const portUi = process.env.uiPort ? Number(process.env.uiPort) : 4200; - http.createServer(function (req, res) { - file.serve(req, res); - console.log('server ui started'); - console.log(url.parse(req.url, true).query); - }).listen(portUi, '0.0.0.0', () => { - console.log(`listen ui on port ${portUi}`); - }) - return true; + serverManager.runServer(portUi); + + } catch (error) { + console.error('[CRITICAL::ERROR]: Starting server:', error); + } + } } -runServer(); +// Call the function to start the server when this module is executed +App.main(); From c9d2afa8eb6c7bc1edeb3a6c871d8001c0e5c40c Mon Sep 17 00:00:00 2001 From: Kifungo A <45813955+adkif@users.noreply.github.com> Date: Thu, 1 Feb 2024 21:41:56 +0000 Subject: [PATCH 05/17] refactor: local server and SSL port configuration Add a new SSL test port and refactor default UI host to handle Windows platform. --- .../lib/config/local-server-update-config.ts | 3 +- .../src/lib/config/server-config.ts | 37 +++++++++---------- 2 files changed, 19 insertions(+), 21 deletions(-) diff --git a/packages/desktop-libs/src/lib/config/local-server-update-config.ts b/packages/desktop-libs/src/lib/config/local-server-update-config.ts index 913828dbe06..4ee584dcae2 100644 --- a/packages/desktop-libs/src/lib/config/local-server-update-config.ts +++ b/packages/desktop-libs/src/lib/config/local-server-update-config.ts @@ -1,4 +1,5 @@ export const LOCAL_SERVER_UPDATE_CONFIG = { FOLDER_PATH: '/', - PORT: 11999 + PORT: 11999, + TEST_SSL_PORT: 11998 }; diff --git a/packages/desktop-libs/src/lib/config/server-config.ts b/packages/desktop-libs/src/lib/config/server-config.ts index 556127e9b06..7c8883970f9 100644 --- a/packages/desktop-libs/src/lib/config/server-config.ts +++ b/packages/desktop-libs/src/lib/config/server-config.ts @@ -27,9 +27,7 @@ export class ServerConfig implements IServerConfig { const regex = /api:\s*['"]((https?:\/\/[^'"]+))['"]/g; const match = regex.exec(fileContent); // Replace all occurrences of the URL with the new one - return match - ? fileContent.replace(regex, `api: '${newUrl}'`) - : this._initialConfig(newUrl, fileContent); + return match ? fileContent.replace(regex, `api: '${newUrl}'`) : this._initialConfig(newUrl, fileContent); } private _removeDuplicates(text: string): string { @@ -37,13 +35,10 @@ export class ServerConfig implements IServerConfig { const scriptRegex = /(