thrilled-be-core
Version:
Core Express backend package with middleware, logging, security, and base application setup
420 lines • 16.5 kB
TypeScript
import type { CorsOptions } from 'cors';
import type { Environment as BeTypesEnvironment, SecurityConfig, JWTConfig, BcryptConfig, SessionConfig } from 'thrilled-be-types';
export type { Environment } from 'thrilled-be-types';
export interface ValidationConfig extends PluginConfig {
/**
* Whether validation is enabled - defaults to true
* This can be used to disable validation globally.
* If set to false, no validation will be performed.
* If set to true, validation will be performed according to the specified configuration.
* Defaults to true.
*/
enabled?: boolean;
/**
* Whether to enable XSS protection middleware.
* This middleware helps to prevent cross-site scripting attacks by sanitizing user input.
* Defaults to true.
*/
enableXSSProtection?: boolean;
/**
* Whether to enable SQL injection protection middleware.
* This middleware helps to prevent SQL injection attacks by sanitizing user input.
* It can be used to validate and sanitize SQL queries to prevent malicious input.
* Defaults to true.
*/
enableSQLInjectionProtection?: boolean;
/**
* Global validation configuration
* This can include options for enabling/disabling validation, soft validation,
* and additional options for validation libraries.
* - `enabled`: Whether global validation is enabled. Defaults to true.
* - `soft`: Whether to perform soft validation, which allows unknown fields. Defaults to false.
* - `options`: Additional options for validation libraries, such as Joi or Yup.
* Defaults to an empty object.
* This configuration can be used to apply validation rules globally across the application.
* It can be used to enforce validation rules for request bodies, query parameters, and URL parameters.
* If set to false, no global validation will be applied.
* If set to true, global validation will be applied according to the specified options.
* Defaults to true.
*/
globalValidation?: {
enabled: boolean;
soft?: boolean;
options?: Record<string, unknown>;
};
/**
* Global sanitization configuration
* This can include options for sanitizing request bodies, query parameters, and URL parameters.
* - `body`: Sanitization rules for request bodies.
* - `query`: Sanitization rules for query parameters.
* - `params`: Sanitization rules for URL parameters.
* This configuration can be used to apply sanitization rules globally across the application.
* It can be used to sanitize user input to prevent XSS attacks, SQL injection,
* and other security vulnerabilities.
* If not specified, no global sanitization will be applied.
* If specified, sanitization will be applied according to the provided rules.
* Defaults to an empty object.
*/
globalSanitization?: {
body?: Record<string, unknown>;
query?: Record<string, unknown>;
params?: Record<string, unknown>;
};
/**
* Custom validators
* This can include custom validation functions that can be used to validate specific fields or data structures.
* - `customValidators`: A record of custom validation functions where the key is the name of the validator
* and the value is a function that takes a value and returns a promise
* that resolves to an object with `isValid` and `errors` properties.
* This configuration can be used to define custom validation logic that is not covered by the built-in validation libraries.
* Custom validators can be used to validate complex data structures, perform asynchronous validation,
* or implement custom validation logic that is specific to the application.
* If not specified, no custom validators will be applied.
* If specified, custom validators will be applied according to the provided functions.
* Each custom validator function should return a promise that resolves to an object with the following structure:
* - `isValid`: A boolean indicating whether the validation passed.
* - `errors`: An array of error messages if the validation failed, or an empty array if it passed.
* Defaults to an empty object.
*/
customValidators?: Record<string, (value: unknown) => Promise<{
isValid: boolean;
errors: unknown[];
}>>;
/**
* Content Security Policy (CSP) configuration
* This can include options for enabling/disabling CSP, and specifying directives for the CSP.
* - `enabled`: Whether to enable Content Security Policy. Defaults to false.
* - `directives`: A record of CSP directives where the key is the directive name
* and the value is an array of strings representing the allowed sources for that directive.
* This configuration can be used to apply a Content Security Policy to the application,
* which helps to prevent cross-site scripting (XSS) attacks and other code injection attacks.
* If not specified, no Content Security Policy will be applied.
* If specified, a Content Security Policy will be applied according to the provided directives.
* Each directive can include sources such as 'self', 'none', 'unsafe-inline',
* 'unsafe-eval', and specific URLs or domains.
* For example, a directive for script sources might look like:
* ```json
* "script-src": ["'self'", "'unsafe-inline'", "https://example.com"]
* ```
* This would allow scripts to be loaded from the same origin, inline scripts,
* and scripts from 'https://example.com'.
* Defaults to an empty object.
*/
csp?: {
enabled: boolean;
directives?: Record<string, string[]>;
};
}
export interface AppLoggingConfig {
/**
* The logging level to use.
* Can be 'debug', 'info', 'warn', 'error', or 'fatal'.
* Defaults to 'info'.
*/
level?: string;
/**
* The directory where logs will be stored.
* If not specified, logs may be written to the console or a default location.
*/
dir?: string;
/**
* The format of the logs.
* Can be 'json' for structured logging or 'simple' for plain text.
*/
format?: 'json' | 'simple';
/**
* Whether to enable HTTP request logging.
* If true, logs will include details of incoming HTTP requests.
*/
httpLogging?: boolean;
/**
* Maximum number of log files to keep.
* If set, logs will be rotated and this many files will be kept.
*/
maxFiles?: number;
/**
* Whether to include a correlation ID in logs.
* If true, a unique ID will be generated for each request and included in the logs.
*/
correlationId?: boolean;
}
export interface RateLimitConfig {
/**
* The time window for which requests are counted.
* This is specified in milliseconds.
* For example, 15 minutes would be 15 * 60 * 1000.
*/
windowMs?: number;
/**
* The maximum number of requests allowed within the specified time window.
* If this limit is exceeded, further requests will be rejected.
*/
max?: number;
/**
* The message to return when the rate limit is exceeded.
* This can be a string or an object.
* If not specified, a default message will be used.
*/
message?: string;
/**
* Whether to include rate limit information in the response headers.
* If true, headers like `X-RateLimit-Limit`, `X-RateLimit-Remaining`, and `X-RateLimit-Reset` will be included.
*/
standardHeaders?: boolean;
/**
* Whether to include legacy rate limit headers.
* If true, headers like `X-RateLimit-Limit`, `X-RateLimit-Remaining`, and `X-RateLimit-Reset` will be included.
* This is for compatibility with older clients that expect these headers.
*/
legacyHeaders?: boolean;
/**
* Whether to skip the rate limit for certain requests.
* This can be a function that takes the request object and returns true if the request should be skipped.
*/
skip?: (req: unknown) => boolean;
/**
* A function to generate a unique key for each request.
* This is used to identify the client making the request.
* If not specified, the default key generator will be used, which typically uses the client's IP address.
*/
keyGenerator?: (req: unknown) => string;
/**
* A function to handle the case when the rate limit is reached.
* This can be used to log the event, send an email, or perform any other action.
* The function receives the request and response objects, as well as the rate limit options.
*/
onLimitReached?: (req: unknown, res: unknown, options: RateLimitConfig) => void;
}
export interface CorsConfig extends CorsOptions {
/**
* Whether to allow credentials in CORS requests.
* If true, cookies and HTTP authentication will be included in CORS requests.
*/
[key: string]: unknown;
}
export interface HelmetConfig {
contentSecurityPolicy?: boolean | Record<string, unknown>;
crossOriginEmbedderPolicy?: boolean;
crossOriginOpenerPolicy?: boolean;
crossOriginResourcePolicy?: boolean | Record<string, unknown>;
dnsPrefetchControl?: boolean;
frameguard?: boolean | Record<string, unknown>;
hidePoweredBy?: boolean;
hsts?: boolean | Record<string, unknown>;
ieNoOpen?: boolean;
noSniff?: boolean;
originAgentCluster?: boolean;
permittedCrossDomainPolicies?: boolean | Record<string, unknown>;
referrerPolicy?: boolean | Record<string, unknown>;
xssFilter?: boolean;
}
export interface AppConfig {
/**
* The name of the application.
* This is used for logging and identification purposes.
*/
name?: string;
/**
* The port on which the application will run.
* Defaults to 3000 if not specified.
*/
port?: number;
/**
* The host on which the application will run.
* Defaults to 'localhost' if not specified.
*/
host?: string;
/**
* The environment in which the application is running.
* Can be 'development', 'production', or 'test'.
* Defaults to 'development' if not specified.
*/
env?: string;
/**
* The environment type for the application.
* This is used to determine the configuration and behavior of the application.
* Defaults to 'development' if not specified.
*/
environment?: BeTypesEnvironment;
/**
* Whether the application is running in production mode.
* If true, the application will use production configurations.
* Defaults to false if not specified.
*/
trustProxy?: boolean | string | number | string[] | ((ip: string, hopIndex: number) => boolean);
/**
* The logging configuration for the application.
* This includes settings for log level, directory, format, and more.
*/
logging?: AppLoggingConfig;
/**
* The database configuration for the application.
* This includes settings for the database type, host, port, username, password, and database name.
*/
cors?: CorsConfig;
/**
* The security configuration for the application.
* This includes settings for JWT, bcrypt, session management, and other security-related options.
*/
rateLimit?: RateLimitConfig;
/**
* The rate limiting configuration for the application.
* This includes settings for the rate limit window, maximum requests, and other options.
*/
helmet?: HelmetConfig;
/**
* The helmet configuration for the application.
* This includes security headers and other security-related options.
*/
security?: SecurityConfig;
/**
* The validation configuration for the application.
* This includes settings for input validation, sanitization, and security measures.
* It can include options for enabling/disabling validation, XSS protection, SQL injection protection,
* global validation settings, custom validators, and Content Security Policy (CSP) configuration.
*/
validation?: ValidationConfig;
/**
* The session configuration for the application.
* This includes settings for session management, such as session store, secret, and cookie options.
*/
timeout?: number;
/**
* The timeout configuration for the application.
* This includes settings for request timeouts, idle timeouts, and other timeout-related options.
*/
gracefulShutdown?: {
/**
* Whether graceful shutdown is enabled.
* If true, the application will handle shutdown signals gracefully.
* Defaults to false if not specified.
*/
enabled?: boolean;
/**
* The timeout for graceful shutdown.
* This is the maximum time allowed for the application to complete ongoing requests before shutting down.
* Defaults to 5000 milliseconds (5 seconds) if not specified.
*/
timeout?: number;
/**
* The signals to listen for graceful shutdown.
* This can include signals like 'SIGINT', 'SIGTERM', etc.
* If not specified, the application will listen for the default signals.
* Defaults to ['SIGINT', 'SIGTERM'] if not specified.
*/
signals?: string[];
};
metrics?: {
/**
* Whether metrics collection is enabled.
* If true, the application will expose metrics endpoints for monitoring.
* Defaults to false if not specified.
*/
enabled?: boolean;
/**
* The endpoint for metrics collection.
* This is the URL path that will be used to collect metrics from the application.
* Defaults to '/metrics' if not specified.
*/
endpoint?: string;
};
health?: {
/**
* Whether health checks are enabled.
* If true, the application will expose a health check endpoint.
* Defaults to false if not specified.
*/
enabled?: boolean;
/**
* The endpoint for health checks.
* This is the URL path that will be used to check the health of the application.
* Defaults to '/health' if not specified.
*/
endpoint?: string;
};
}
export interface PluginConfig {
/**
* A unique identifier for the plugin.
* This is used to identify the plugin within the application.
* It can be a string or a number.
* If not specified, the plugin will not be registered.
*/
[key: string]: unknown;
}
export interface PluginDependency {
name: string;
version?: string;
optional?: boolean;
}
export interface PluginMetadata {
name: string;
version: string;
description?: string;
author?: string;
dependencies?: PluginDependency[];
tags?: string[];
}
export interface HealthCheckOptions {
enabled?: boolean;
endpoint?: string;
checks?: Record<string, () => Promise<HealthCheckResult>>;
timeout?: number;
interval?: number;
}
export interface HealthCheckResult {
status: 'healthy' | 'unhealthy';
message?: string;
data?: Record<string, unknown>;
}
export interface HealthCheckStatus {
status: 'healthy' | 'unhealthy';
timestamp: string;
checks: Record<string, HealthCheckResult>;
uptime: number;
}
export interface GracefulShutdownOptions {
enabled?: boolean;
timeout?: number;
signals?: string[];
cleanup?: (() => Promise<void>)[];
}
export declare enum HttpStatusCodes {
OK = 200,
CREATED = 201,
NO_CONTENT = 204,
BAD_REQUEST = 400,
UNAUTHORIZED = 401,
FORBIDDEN = 403,
NOT_FOUND = 404,
CONFLICT = 409,
UNPROCESSABLE_ENTITY = 422,
INTERNAL_SERVER_ERROR = 500,
SERVICE_UNAVAILABLE = 503
}
export interface ApiResponse<T> {
success: boolean;
message: string;
data?: T;
meta?: {
count?: number;
total?: number;
page?: number;
limit?: number;
[key: string]: unknown;
};
errors?: ApiError[];
statusCode: HttpStatusCodes;
}
export interface ApiError {
message: string;
code?: string;
field?: string;
}
export interface PaginationOptions {
page: number;
limit: number;
total?: number;
}
export type { SecurityConfig, JWTConfig, BcryptConfig, SessionConfig };
//# sourceMappingURL=index.d.ts.map