From b4617936340af79f5c18b2161aa367ecc0e2df6e Mon Sep 17 00:00:00 2001 From: Ruslan Konviser Date: Fri, 15 Dec 2023 23:24:41 +0100 Subject: [PATCH 1/2] chore: more env vars / configs updates --- .env.compose | 5 +- .env.demo.compose | 5 +- .env.docker | 5 +- .env.local | 5 +- .env.sample | 5 +- apps/api/src/plugin-config.ts | 2 +- packages/config/src/database.ts | 2 +- .../src/environments/environment.prod.ts | 4 +- .../config/src/environments/environment.ts | 3 +- .../config/src/environments/ienvironment.ts | 1 + packages/core/src/app.module.ts | 63 ++++---- packages/core/src/bootstrap/index.ts | 7 +- .../context/request-context.middleware.ts | 15 +- .../core/src/core/context/request-context.ts | 134 +++++++++--------- .../gauzy-ai/integration-ai.middleware.ts | 120 ++++++++-------- .../integration/github/github.middleware.ts | 106 +++++++------- .../throttler/throttler-behind-proxy.guard.ts | 4 - 17 files changed, 260 insertions(+), 226 deletions(-) diff --git a/.env.compose b/.env.compose index 79fa53ac2ff..c60fb38a51d 100644 --- a/.env.compose +++ b/.env.compose @@ -64,7 +64,7 @@ DB_NAME=gauzy DB_USER=postgres DB_PASS=gauzy_password DB_LOGGING=all -DB_POOL_SIZE=20 +DB_POOL_SIZE=40 DB_CONNECTION_TIMEOUT=1000 DB_SLOW_QUERY_LOGGING_TIMEOUT=3000 @@ -89,8 +89,9 @@ MAGIC_CODE_EXPIRATION_TIME=600 TEAM_JOIN_REQUEST_EXPIRATION_TIME=86400 # Rate Limiting +THROTTLE_ENABLED=true THROTTLE_TTL=60 -THROTTLE_LIMIT=300 +THROTTLE_LIMIT=10000 # Twitter OAuth Configuration TWITTER_CLIENT_ID=XXXXXXX diff --git a/.env.demo.compose b/.env.demo.compose index d88f72b4e39..1a1dc59f55e 100644 --- a/.env.demo.compose +++ b/.env.demo.compose @@ -65,7 +65,7 @@ DB_NAME=gauzy DB_USER=postgres DB_PASS=gauzy_password DB_LOGGING=all -DB_POOL_SIZE=20 +DB_POOL_SIZE=40 DB_CONNECTION_TIMEOUT=1000 DB_SLOW_QUERY_LOGGING_TIMEOUT=3000 @@ -90,8 +90,9 @@ MAGIC_CODE_EXPIRATION_TIME=600 TEAM_JOIN_REQUEST_EXPIRATION_TIME=86400 # Rate Limiting +THROTTLE_ENABLED=true THROTTLE_TTL=60 -THROTTLE_LIMIT=300 +THROTTLE_LIMIT=10000 # Twitter OAuth Configuration TWITTER_CLIENT_ID=XXXXXXX diff --git a/.env.docker b/.env.docker index 50b69614ebc..6cfc404c3a1 100644 --- a/.env.docker +++ b/.env.docker @@ -63,7 +63,7 @@ DB_NAME=gauzy DB_USER=postgres DB_PASS=root DB_LOGGING=all -DB_POOL_SIZE=20 +DB_POOL_SIZE=40 DB_CONNECTION_TIMEOUT=1000 DB_SLOW_QUERY_LOGGING_TIMEOUT=3000 @@ -88,8 +88,9 @@ MAGIC_CODE_EXPIRATION_TIME=600 TEAM_JOIN_REQUEST_EXPIRATION_TIME=86400 # Rate Limiting +THROTTLE_ENABLED=true THROTTLE_TTL=60 -THROTTLE_LIMIT=300 +THROTTLE_LIMIT=10000 # Twitter OAuth Configuration TWITTER_CLIENT_ID=XXXXXXX diff --git a/.env.local b/.env.local index 8002404db84..9143c1b3831 100644 --- a/.env.local +++ b/.env.local @@ -63,7 +63,7 @@ DB_NAME=gauzy DB_USER=postgres DB_PASS=root DB_LOGGING=all -DB_POOL_SIZE=20 +DB_POOL_SIZE=40 DB_CONNECTION_TIMEOUT=1000 DB_SLOW_QUERY_LOGGING_TIMEOUT=3000 @@ -88,8 +88,9 @@ MAGIC_CODE_EXPIRATION_TIME=600 TEAM_JOIN_REQUEST_EXPIRATION_TIME=86400 # Rate Limiting +THROTTLE_ENABLED=true THROTTLE_TTL=60 -THROTTLE_LIMIT=300 +THROTTLE_LIMIT=10000 # Twitter OAuth Configuration TWITTER_CLIENT_ID= diff --git a/.env.sample b/.env.sample index ee31a7f2431..dd9589dbb67 100644 --- a/.env.sample +++ b/.env.sample @@ -47,7 +47,7 @@ DB_TYPE=better-sqlite3 # DB_USER=postgres # DB_PASS=root # DB_LOGGING=all -# DB_POOL_SIZE=20 +# DB_POOL_SIZE=40 # DB_CONNECTION_TIMEOUT=1000 # DB_SLOW_QUERY_LOGGING_TIMEOUT=3000 @@ -72,8 +72,9 @@ MAGIC_CODE_EXPIRATION_TIME=600 TEAM_JOIN_REQUEST_EXPIRATION_TIME=86400 # Rate Limiting +THROTTLE_ENABLED=true THROTTLE_TTL=60 -THROTTLE_LIMIT=300 +THROTTLE_LIMIT=10000 # Twitter OAuth Configuration TWITTER_CLIENT_ID=XXXXXXX diff --git a/apps/api/src/plugin-config.ts b/apps/api/src/plugin-config.ts index 4b3ec540c44..36231b235fd 100644 --- a/apps/api/src/plugin-config.ts +++ b/apps/api/src/plugin-config.ts @@ -108,7 +108,7 @@ function getDbConfig(): DataSourceOptions { // See https://typeorm.io/data-source-options#common-data-source-options extra: { // based on https://node-postgres.com/api/pool max connection pool size - max: process.env.DB_POOL_SIZE || 20, + max: process.env.DB_POOL_SIZE || 40, // connection timeout connectionTimeoutMillis: process.env.DB_CONNECTION_TIMEOUT ? parseInt(process.env.DB_CONNECTION_TIMEOUT) diff --git a/packages/config/src/database.ts b/packages/config/src/database.ts index 2ef9e696b27..b400e2a0a69 100644 --- a/packages/config/src/database.ts +++ b/packages/config/src/database.ts @@ -59,7 +59,7 @@ switch (dbType) { // See https://typeorm.io/data-source-options#common-data-source-options extra: { // based on https://node-postgres.com/api/pool max connection pool size - max: process.env.DB_POOL_SIZE || 20, + max: process.env.DB_POOL_SIZE || 40, // connection timeout connectionTimeoutMillis: process.env.DB_CONNECTION_TIMEOUT ? parseInt(process.env.DB_CONNECTION_TIMEOUT) diff --git a/packages/config/src/environments/environment.prod.ts b/packages/config/src/environments/environment.prod.ts index 700fe9b3866..8f630250399 100644 --- a/packages/config/src/environments/environment.prod.ts +++ b/packages/config/src/environments/environment.prod.ts @@ -51,8 +51,8 @@ export const environment: IEnvironment = { /** * Throttler (Rate Limiting) Options */ - THROTTLE_TTL: parseInt(process.env.THROTTLE_TTL) || 60, // 60ms - THROTTLE_LIMIT: parseInt(process.env.THROTTLE_LIMIT) || 3000, + THROTTLE_TTL: parseInt(process.env.THROTTLE_TTL) || 60, // now it's 60 seconds, but in future versions of Throttle going to be 60ms! + THROTTLE_LIMIT: parseInt(process.env.THROTTLE_LIMIT) || 10000, /** * Jitsu Server Configuration diff --git a/packages/config/src/environments/environment.ts b/packages/config/src/environments/environment.ts index d0366549ce4..5f324c052b0 100644 --- a/packages/config/src/environments/environment.ts +++ b/packages/config/src/environments/environment.ts @@ -56,7 +56,8 @@ export const environment: IEnvironment = { * Throttler (Rate Limiting) Options */ THROTTLE_TTL: parseInt(process.env.THROTTLE_TTL) || 60, // now it's 60 seconds, but in future versions of Throttle going to be 60ms! - THROTTLE_LIMIT: parseInt(process.env.THROTTLE_LIMIT) || 3000, + THROTTLE_LIMIT: parseInt(process.env.THROTTLE_LIMIT) || 10000, + THROTTLE_ENABLED: process.env.THROTTLE_ENABLED == 'true', /** * Jitsu Server Configuration diff --git a/packages/config/src/environments/ienvironment.ts b/packages/config/src/environments/ienvironment.ts index fa70dc98a9e..f61d22b6f78 100644 --- a/packages/config/src/environments/ienvironment.ts +++ b/packages/config/src/environments/ienvironment.ts @@ -90,6 +90,7 @@ export interface IEnvironment { /** * Throttler (Rate Limiting) Options */ + THROTTLE_ENABLED?: boolean; THROTTLE_TTL?: number; THROTTLE_LIMIT?: number; diff --git a/packages/core/src/app.module.ts b/packages/core/src/app.module.ts index 0ee9627b2a2..ad88e9676ef 100644 --- a/packages/core/src/app.module.ts +++ b/packages/core/src/app.module.ts @@ -237,7 +237,8 @@ if (environment.sentry && environment.sentry.dsn) { // Probot Configuration ProbotModule.forRoot({ isGlobal: true, - path: 'integration/github/webhook', // Webhook URL in GitHub will be: https://api.gauzy.co/api/integration/github/webhook + // Webhook URL in GitHub will be: https://api.gauzy.co/api/integration/github/webhook + path: 'integration/github/webhook', config: { /** Client Configuration */ clientId: github.clientId, @@ -267,14 +268,18 @@ if (environment.sentry && environment.sentry.dsn) { echoEvents: jitsu.echoEvents } }), - ThrottlerModule.forRootAsync({ - inject: [ConfigService], - useFactory: (config: ConfigService): ThrottlerModuleOptions => - ({ - ttl: config.get('THROTTLE_TTL'), - limit: config.get('THROTTLE_LIMIT') - } as ThrottlerModuleOptions) - }), + ...(environment.THROTTLE_ENABLED + ? [ + ThrottlerModule.forRootAsync({ + inject: [ConfigService], + useFactory: (config: ConfigService): ThrottlerModuleOptions => + ({ + ttl: config.get('THROTTLE_TTL'), + limit: config.get('THROTTLE_LIMIT') + } as ThrottlerModuleOptions) + }) + ] + : []), CoreModule, AuthModule, UserModule, @@ -403,26 +408,34 @@ if (environment.sentry && environment.sentry.dsn) { controllers: [AppController], providers: [ AppService, - { - provide: APP_GUARD, - useClass: ThrottlerBehindProxyGuard - }, + ...(environment.THROTTLE_ENABLED + ? [ + { + provide: APP_GUARD, + useClass: ThrottlerBehindProxyGuard + } + ] + : []), { provide: APP_INTERCEPTOR, useClass: TransformInterceptor }, - { - provide: APP_INTERCEPTOR, - useFactory: () => - new SentryInterceptor({ - filters: [ - { - type: HttpException, - filter: (exception: HttpException) => 500 > exception.getStatus() // Only report 500 errors - } - ] - }) - } + ...(environment.sentry && environment.sentry.dsn + ? [ + { + provide: APP_INTERCEPTOR, + useFactory: () => + new SentryInterceptor({ + filters: [ + { + type: HttpException, + filter: (exception: HttpException) => 500 > exception.getStatus() // Only report 500 errors + } + ] + }) + } + ] + : []) ], exports: [] }) diff --git a/packages/core/src/bootstrap/index.ts b/packages/core/src/bootstrap/index.ts index 72e2703d62a..b22715d91fc 100644 --- a/packages/core/src/bootstrap/index.ts +++ b/packages/core/src/bootstrap/index.ts @@ -69,16 +69,19 @@ export async function bootstrap(pluginConfig?: Partial): Promise< 'Authorization, Language, Tenant-Id, Organization-Id, X-Requested-With, X-Auth-Token, X-HTTP-Method-Override, Content-Type, Content-Language, Accept, Accept-Language, Observe' }); - // TODO: enable csurf + // TODO: enable csurf is not good idea because it was depricated. + // Maybe review https://github.com/Psifi-Solutions/csrf-csrf as alternative? // As explained on the csurf middleware page https://github.com/expressjs/csurf#csurf, // the csurf module requires either a session middleware or cookie-parser to be initialized first. // app.use(csurf()); + // We use sessions for Passport Auth app.use( expressSession({ secret: env.EXPRESS_SESSION_SECRET, - resave: true, + resave: true, // we use this because Memory store does not support 'touch' method saveUninitialized: true + // cookie: { secure: true } // TODO }) ); diff --git a/packages/core/src/core/context/request-context.middleware.ts b/packages/core/src/core/context/request-context.middleware.ts index 35fb2cb7014..aeec852141b 100644 --- a/packages/core/src/core/context/request-context.middleware.ts +++ b/packages/core/src/core/context/request-context.middleware.ts @@ -8,16 +8,21 @@ import { Request, Response, NextFunction } from 'express'; import { RequestContext } from './request-context'; +// There are few alternatives to 'cls-hooked', see: +// https://docs.nestjs.com/recipes/async-local-storage +// https://github.com/papooch/nestjs-cls + @Injectable() export class RequestContextMiddleware implements NestMiddleware { - use( - req: Request, - res: Response, - next: NextFunction - ) { + use(req: Request, res: Response, next: NextFunction) { const requestContext = new RequestContext(req, res); const session = cls.getNamespace(RequestContext.name) || cls.createNamespace(RequestContext.name); + // Note: this is "session" created by "cls-hooked" lib code, + // not related to express "session" storage at all! + // Also, session.run essentially creates unique context for each + // request so all data is isolated without any potential conflicts + // for concurrent requests session.run(async () => { session.set(RequestContext.name, requestContext); next(); diff --git a/packages/core/src/core/context/request-context.ts b/packages/core/src/core/context/request-context.ts index 241b7586351..658d37babfc 100644 --- a/packages/core/src/core/context/request-context.ts +++ b/packages/core/src/core/context/request-context.ts @@ -5,12 +5,7 @@ import { HttpException, HttpStatus } from '@nestjs/common'; import * as cls from 'cls-hooked'; import { Request, Response } from 'express'; -import { - IUser, - PermissionsEnum, - LanguagesEnum, - RolesEnum -} from '@gauzy/contracts'; +import { IUser, PermissionsEnum, LanguagesEnum, RolesEnum } from '@gauzy/contracts'; import { ExtractJwt } from 'passport-jwt'; import { JsonWebTokenError, verify } from 'jsonwebtoken'; import { environment as env } from '@gauzy/config'; @@ -56,28 +51,34 @@ export class RequestContext { } static currentUserId(): string { - const user: IUser = RequestContext.currentUser(); - if (user) { - return user.id; + try { + const user: IUser = RequestContext.currentUser(); + if (user) { + return user.id; + } + return null; + } catch (error) { + return null; } - return null; } static currentRoleId(): string { - const user: IUser = RequestContext.currentUser(); - if (user) { - return user.roleId; + try { + const user: IUser = RequestContext.currentUser(); + if (user) { + return user.roleId; + } + return null; + } catch (error) { + return null; } - return null; } static currentEmployeeId(): string { try { const user: IUser = RequestContext.currentUser(); if (isNotEmpty(user)) { - if (!RequestContext.hasPermission( - PermissionsEnum.CHANGE_SELECTED_EMPLOYEE - )) { + if (!RequestContext.hasPermission(PermissionsEnum.CHANGE_SELECTED_EMPLOYEE)) { return user.employeeId; } } @@ -106,10 +107,7 @@ export class RequestContext { return null; } - static hasPermission( - permission: PermissionsEnum, - throwError?: boolean - ): boolean { + static hasPermission(permission: PermissionsEnum, throwError?: boolean): boolean { return this.hasPermissions([permission], throwError); } @@ -129,72 +127,70 @@ export class RequestContext { return lang; } - static hasPermissions( - findPermissions: PermissionsEnum[], - throwError?: boolean - ): boolean { + static hasPermissions(findPermissions: PermissionsEnum[], throwError?: boolean): boolean { const requestContext = RequestContext.currentRequestContext(); if (requestContext) { - // tslint:disable-next-line - const token = ExtractJwt.fromAuthHeaderAsBearerToken()( - requestContext.request as any - ); - - if (token) { - const { permissions } = verify(token, env.JWT_SECRET) as { - id: string; - permissions: PermissionsEnum[]; - }; - if (permissions) { - const found = permissions.filter( - (value) => findPermissions.indexOf(value) >= 0 - ); - - if (found.length === findPermissions.length) { - return true; + try { + // tslint:disable-next-line + const token = ExtractJwt.fromAuthHeaderAsBearerToken()(requestContext.request as any); + + if (token) { + const { permissions } = verify(token, env.JWT_SECRET) as { + id: string; + permissions: PermissionsEnum[]; + }; + if (permissions) { + const found = permissions.filter((value) => findPermissions.indexOf(value) >= 0); + + if (found.length === findPermissions.length) { + return true; + } + } else { + return false; } - } else { - return false; } + } catch (error) { + // Do nothing here, we throw below anyway if needed + console.log(error); } } if (throwError) { throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED); } + return false; } - static hasAnyPermission( - findPermissions: PermissionsEnum[], - throwError?: boolean - ): boolean { + static hasAnyPermission(findPermissions: PermissionsEnum[], throwError?: boolean): boolean { const requestContext = RequestContext.currentRequestContext(); if (requestContext) { - // tslint:disable-next-line - const token = ExtractJwt.fromAuthHeaderAsBearerToken()( - requestContext.request as any - ); - - if (token) { - const { permissions } = verify(token, env.JWT_SECRET) as { - id: string; - permissions: PermissionsEnum[]; - }; - const found = permissions.filter( - (value) => findPermissions.indexOf(value) >= 0 - ); - if (found.length > 0) { - return true; + try { + // tslint:disable-next-line + const token = ExtractJwt.fromAuthHeaderAsBearerToken()(requestContext.request as any); + + if (token) { + const { permissions } = verify(token, env.JWT_SECRET) as { + id: string; + permissions: PermissionsEnum[]; + }; + const found = permissions.filter((value) => findPermissions.indexOf(value) >= 0); + if (found.length > 0) { + return true; + } } + } catch (error) { + // Do nothing here, we throw below anyway if needed + console.log(error); } } if (throwError) { throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED); } + return false; } @@ -202,15 +198,19 @@ export class RequestContext { const requestContext = RequestContext.currentRequestContext(); if (requestContext) { - // tslint:disable-next-line - return ExtractJwt.fromAuthHeaderAsBearerToken()( - requestContext.request as any - ); + try { + // tslint:disable-next-line + return ExtractJwt.fromAuthHeaderAsBearerToken()(requestContext.request as any); + } catch (error) { + // Do nothing here, we throw below anyway if needed + console.log(error); + } } if (throwError) { throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED); } + return null; } diff --git a/packages/core/src/integration/gauzy-ai/integration-ai.middleware.ts b/packages/core/src/integration/gauzy-ai/integration-ai.middleware.ts index 849052b928e..f558902c487 100644 --- a/packages/core/src/integration/gauzy-ai/integration-ai.middleware.ts +++ b/packages/core/src/integration/gauzy-ai/integration-ai.middleware.ts @@ -8,75 +8,77 @@ import { IntegrationTenantService } from 'integration-tenant/integration-tenant. @Injectable() export class IntegrationAIMiddleware implements NestMiddleware { + private logging: boolean = true; - private logging: boolean = true; + constructor( + private readonly integrationTenantService: IntegrationTenantService, + private readonly requestConfigProvider: RequestConfigProvider + ) {} - constructor( - private readonly integrationTenantService: IntegrationTenantService, - private readonly requestConfigProvider: RequestConfigProvider, - ) { } + async use(request: Request, _response: Response, next: NextFunction) { + // Extract tenant and organization IDs from request headers and body + const tenantId = request.header('tenant-id') || request.body?.tenantId; + const organizationId = request.header('organization-id') || request.body?.organizationId; - async use( - request: Request, - _response: Response, - next: NextFunction - ) { - // Extract tenant and organization IDs from request headers and body - const tenantId = request.header('tenant-id') || request.body?.tenantId; - const organizationId = request.header('organization-id') || request.body?.organizationId; + if (this.logging) { + // Log tenant and organization IDs + console.log('Auth Tenant-ID Header: %s', tenantId); + console.log('Auth Organization-ID Header: %s', organizationId); + } - if (this.logging) { - // Log tenant and organization IDs - console.log('Auth Tenant-ID Header: %s', tenantId); - console.log('Auth Organization-ID Header: %s', organizationId); - } + // Initialize custom headers + request.headers['X-APP-ID'] = null; + request.headers['X-API-KEY'] = null; - // Initialize custom headers - request.headers['X-APP-ID'] = null; - request.headers['X-API-KEY'] = null; + try { + // Check if tenant and organization IDs are not empty + if (isNotEmpty(tenantId) && isNotEmpty(organizationId)) { + // Fetch integration settings from the service + const { settings = [] } = await this.integrationTenantService.getIntegrationTenantSettings({ + tenantId, + organizationId, + name: IntegrationEnum.GAUZY_AI + }); - try { - // Check if tenant and organization IDs are not empty - if (isNotEmpty(tenantId) && isNotEmpty(organizationId)) { - // Fetch integration settings from the service - const { settings = [] } = await this.integrationTenantService.getIntegrationTenantSettings({ - tenantId, - organizationId, - name: IntegrationEnum.GAUZY_AI - }); - // Convert settings array to an object - const { apiKey, apiSecret, openAiApiSecretKey } = arrayToObject(settings, 'settingsName', 'settingsValue'); + if (settings && settings.length > 0) { + // Convert settings array to an object + const { apiKey, apiSecret, openAiApiSecretKey } = arrayToObject( + settings, + 'settingsName', + 'settingsValue' + ); - if (this.logging) { - console.log('AI Integration API Key: %s', apiKey); - console.log('AI Integration API Secret: %s', apiSecret); - } + if (this.logging) { + console.log('AI Integration API Key: %s', apiKey); + console.log('AI Integration API Secret: %s', apiSecret); + } - if (apiKey && apiSecret) { - // Update custom headers and request configuration with API key and secret - request.headers['X-APP-ID'] = apiKey; - request.headers['X-API-KEY'] = apiSecret; + if (apiKey && apiSecret) { + // Update custom headers and request configuration with API key and secret + request.headers['X-APP-ID'] = apiKey; + request.headers['X-API-KEY'] = apiSecret; - if (isNotEmpty(openAiApiSecretKey)) { - request.headers['X-OPENAI-SECRET-KEY'] = openAiApiSecretKey; - } + if (isNotEmpty(openAiApiSecretKey)) { + request.headers['X-OPENAI-SECRET-KEY'] = openAiApiSecretKey; + } - if (this.logging) { - console.log('AI Integration Config Settings: %s', { apiKey, apiSecret }); - } + if (this.logging) { + console.log('AI Integration Config Settings: %s', { apiKey, apiSecret }); + } - this.requestConfigProvider.setConfig({ - apiKey, - apiSecret, - ...(isNotEmpty(openAiApiSecretKey) && { openAiApiSecretKey }), - }); - } - } - } catch (error) { - console.log('Error while getting AI integration settings: %s', error?.message); - } + this.requestConfigProvider.setConfig({ + apiKey, + apiSecret, + ...(isNotEmpty(openAiApiSecretKey) && { openAiApiSecretKey }) + }); + } + } + } + } catch (error) { + console.log('Error while getting AI integration settings: %s', error?.message); + } - // Continue to the next middleware or route handler - next(); - } + // Continue to the next middleware or route handler + next(); + } } diff --git a/packages/core/src/integration/github/github.middleware.ts b/packages/core/src/integration/github/github.middleware.ts index 47d0a869a08..7cb6e23ecda 100644 --- a/packages/core/src/integration/github/github.middleware.ts +++ b/packages/core/src/integration/github/github.middleware.ts @@ -7,58 +7,66 @@ import { IntegrationTenantService } from 'integration-tenant/integration-tenant. @Injectable() export class GithubMiddleware implements NestMiddleware { + constructor(private readonly _integrationTenantService: IntegrationTenantService) {} - constructor( - private readonly _integrationTenantService: IntegrationTenantService, - ) { } + async use(request: Request, _response: Response, next: NextFunction) { + try { + const integrationId = request.params['integrationId']; - async use( - request: Request, - _response: Response, - next: NextFunction - ) { - try { - const integrationId = request.params['integrationId']; - const queryParameters = request.query; + if (integrationId) { + const queryParameters = request.query; - const tenantId = queryParameters.tenantId ? queryParameters.tenantId.toString() : request.header('Tenant-Id'); - const organizationId = queryParameters.organizationId ? queryParameters.organizationId.toString() : request.header('Organization-Id'); + const tenantId = queryParameters.tenantId + ? queryParameters.tenantId.toString() + : request.header('Tenant-Id'); + const organizationId = queryParameters.organizationId + ? queryParameters.organizationId.toString() + : request.header('Organization-Id'); - // Check if tenant and organization IDs are not empty - if (isNotEmpty(tenantId) && isNotEmpty(organizationId)) { - try { - // Fetch integration settings from the service - const { settings = [] } = await this._integrationTenantService.findOneByIdString(integrationId, { - where: { - tenantId, - organizationId, - isActive: true, - isArchived: false, - integration: { - isActive: true, - isArchived: false, - } - }, - relations: { - settings: true - } - }); - /** Create an 'integration' object and assign properties to it. */ - request['integration'] = new Object({ - // Assign properties to the integration object - id: integrationId, - name: IntegrationEnum.GITHUB, - // Convert the 'settings' array to an object using the 'settingsName' and 'settingsValue' properties - settings: arrayToObject(settings, 'settingsName', 'settingsValue') - }); - } catch (error) { } - } - } catch (error) { - console.log(`Error while getting integration (${IntegrationEnum.GITHUB}) tenant inside middleware: %s`, error?.message); - console.log(request.path, request.url); - } + // Check if tenant and organization IDs are not empty + if (isNotEmpty(tenantId) && isNotEmpty(organizationId)) { + try { + // Fetch integration settings from the service + const { settings = [] } = await this._integrationTenantService.findOneByIdString( + integrationId, + { + where: { + tenantId, + organizationId, + isActive: true, + isArchived: false, + integration: { + isActive: true, + isArchived: false + } + }, + relations: { + settings: true + } + } + ); + /** Create an 'integration' object and assign properties to it. */ + request['integration'] = new Object({ + // Assign properties to the integration object + id: integrationId, + name: IntegrationEnum.GITHUB, + // Convert the 'settings' array to an object using the 'settingsName' and 'settingsValue' properties + settings: arrayToObject(settings, 'settingsName', 'settingsValue') + }); + } catch (error) { + console.log('Error while getting AI integration settings: %s', error?.message); + } + } + } + } catch (error) { + console.log( + `Error while getting integration (${IntegrationEnum.GITHUB}) tenant inside middleware: %s`, + error?.message + ); + console.log(request.path, request.url); + } - // Continue to the next middleware or route handler - next(); - } + // Continue to the next middleware or route handler + next(); + } } diff --git a/packages/core/src/throttler/throttler-behind-proxy.guard.ts b/packages/core/src/throttler/throttler-behind-proxy.guard.ts index 09505b91c75..72c5d851451 100644 --- a/packages/core/src/throttler/throttler-behind-proxy.guard.ts +++ b/packages/core/src/throttler/throttler-behind-proxy.guard.ts @@ -9,10 +9,6 @@ export class ThrottlerBehindProxyGuard extends ThrottlerGuard { // Handle Cloudflare proxy if (req.headers && req.headers['cf-connecting-ip']) { - if (!environment.production) { - console.log(`Cloudflare cf-connecting-ip: ${req.headers['cf-connecting-ip']}`); - } - if (req.headers['cf-connecting-ip'].split(', ').length) { var first = req.headers['cf-connecting-ip'].split(', '); tracker = first[0]; From a7ac14cdb4ae904cfc54fd13af511e19e47ab365 Mon Sep 17 00:00:00 2001 From: Ruslan Konviser Date: Fri, 15 Dec 2023 23:25:30 +0100 Subject: [PATCH 2/2] chore: switch to standard GitHub runners for now --- .github/workflows/desktop-app-prod.yml | 2 +- .github/workflows/desktop-app-stage.yml | 2 +- .github/workflows/desktop-timer-app-prod.yml | 2 +- .github/workflows/desktop-timer-app-stage.yml | 2 +- .github/workflows/server-prod.yml | 2 +- .github/workflows/server-stage.yml | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/desktop-app-prod.yml b/.github/workflows/desktop-app-prod.yml index 1ba7e299167..749e9c9b3b8 100644 --- a/.github/workflows/desktop-app-prod.yml +++ b/.github/workflows/desktop-app-prod.yml @@ -129,7 +129,7 @@ jobs: strategy: matrix: - os: [windows-latest-l] + os: [windows-latest] steps: - name: Check out Git repository diff --git a/.github/workflows/desktop-app-stage.yml b/.github/workflows/desktop-app-stage.yml index 052590ca517..7c8b9fcbbca 100644 --- a/.github/workflows/desktop-app-stage.yml +++ b/.github/workflows/desktop-app-stage.yml @@ -129,7 +129,7 @@ jobs: strategy: matrix: - os: [windows-latest-l] + os: [windows-latest] steps: - name: Check out Git repository diff --git a/.github/workflows/desktop-timer-app-prod.yml b/.github/workflows/desktop-timer-app-prod.yml index 824167a08e0..9b3890f6655 100644 --- a/.github/workflows/desktop-timer-app-prod.yml +++ b/.github/workflows/desktop-timer-app-prod.yml @@ -141,7 +141,7 @@ jobs: strategy: matrix: - os: [windows-latest-l] + os: [windows-latest] steps: - name: Check out Git repository diff --git a/.github/workflows/desktop-timer-app-stage.yml b/.github/workflows/desktop-timer-app-stage.yml index d6f2bd7dd45..20c1788b640 100644 --- a/.github/workflows/desktop-timer-app-stage.yml +++ b/.github/workflows/desktop-timer-app-stage.yml @@ -141,7 +141,7 @@ jobs: strategy: matrix: - os: [windows-latest-l] + os: [windows-latest] steps: - name: Check out Git repository diff --git a/.github/workflows/server-prod.yml b/.github/workflows/server-prod.yml index e8fa6e99e56..cbd259c7dbc 100644 --- a/.github/workflows/server-prod.yml +++ b/.github/workflows/server-prod.yml @@ -129,7 +129,7 @@ jobs: strategy: matrix: - os: [windows-latest-l] + os: [windows-latest] steps: - name: Check out Git repository diff --git a/.github/workflows/server-stage.yml b/.github/workflows/server-stage.yml index be95e88ca17..557df814606 100644 --- a/.github/workflows/server-stage.yml +++ b/.github/workflows/server-stage.yml @@ -129,7 +129,7 @@ jobs: strategy: matrix: - os: [windows-latest-l] + os: [windows-latest] steps: - name: Check out Git repository