Spaces:
Sleeping
Sleeping
Download src/main.ts from jinksQspider/openWa: direct link, hf CLI and curl.
- Browser
- Download file 6.51 kB
-
https://huggingface.co/spaces/jinksQspider/openWa/resolve/main/src/main.ts
- Command line
-
hf download hf://spaces/jinksQspider/openWa/src/main.ts
-
curl -L -o main.ts https://huggingface.co/spaces/jinksQspider/openWa/resolve/main/src/main.ts
6.51 kB
| import { NestFactory } from '@nestjs/core'; | |
| import { ValidationPipe } from '@nestjs/common'; | |
| import { SwaggerModule } from '@nestjs/swagger'; | |
| import helmet from 'helmet'; | |
| import { AppModule } from './app.module'; | |
| import { ShutdownService } from './common/services/shutdown.service'; | |
| import { createSwaggerConfig } from './config/swagger.config'; | |
| import { resolveCorsPolicy, isSwaggerEnabled, resolveBodyLimit } from './config/bootstrap-security'; | |
| import { BullBoardAuthMiddleware } from './common/security/bull-board-auth.middleware'; | |
| import { AuthService } from './modules/auth/auth.service'; | |
| import { Request, Response, NextFunction, json, urlencoded } from 'express'; | |
| import * as dotenv from 'dotenv'; | |
| import * as fs from 'fs'; | |
| import * as path from 'path'; | |
| // Configuration loading order (later sources do NOT override earlier ones): | |
| // 1. Process env (Docker, shell, systemd) — highest priority | |
| // 2. .env (project-level overrides committed/managed by the user) | |
| // 3. data/.env.generated (Dashboard-managed config; created on first run) | |
| // | |
| // Rationale: explicit env vars from the host/orchestrator must always win | |
| // so that operators can override the Dashboard-saved config without having | |
| // to edit data/.env.generated by hand. | |
| const generatedEnvPath = path.resolve(process.cwd(), 'data', '.env.generated'); | |
| const userEnvPath = path.resolve(process.cwd(), '.env'); | |
| // Ensure data directory exists | |
| const dataDir = path.dirname(generatedEnvPath); | |
| if (!fs.existsSync(dataDir)) { | |
| fs.mkdirSync(dataDir, { recursive: true }); | |
| } | |
| // 2. User-managed .env (does not override real process env) | |
| if (fs.existsSync(userEnvPath)) { | |
| console.log('[Bootstrap] Loading .env from:', userEnvPath); | |
| dotenv.config({ path: userEnvPath, override: false }); | |
| } | |
| // 3. Dashboard-saved config (does not override .env or process env) | |
| if (fs.existsSync(generatedEnvPath)) { | |
| console.log('[Bootstrap] Loading saved configuration from:', generatedEnvPath); | |
| dotenv.config({ path: generatedEnvPath, override: false }); | |
| } else { | |
| console.log('[Bootstrap] First run detected, creating default configuration...'); | |
| // Create minimal .env.generated with sensible defaults | |
| const minimalConfig = `# OpenWA Configuration | |
| # Generated automatically on first run | |
| # Edit via Dashboard > Infrastructure or modify this file directly. | |
| # Note: values in process env or project .env take precedence over this file. | |
| # Database (SQLite - no external service required) | |
| DATABASE_TYPE=sqlite | |
| POSTGRES_BUILTIN=false | |
| # Redis & Queue (disabled by default) | |
| REDIS_ENABLED=false | |
| REDIS_BUILTIN=false | |
| QUEUE_ENABLED=false | |
| # Storage (Local filesystem) | |
| STORAGE_TYPE=local | |
| MINIO_BUILTIN=false | |
| STORAGE_PATH=./data/media | |
| # Docker Profiles: none (minimal setup) | |
| `; | |
| fs.writeFileSync(generatedEnvPath, minimalConfig); | |
| console.log('[Bootstrap] Created default configuration at:', generatedEnvPath); | |
| dotenv.config({ path: generatedEnvPath, override: false }); | |
| } | |
| async function bootstrap() { | |
| // Disable Nest's default body parser so we can set an explicit size cap below. | |
| const app = await NestFactory.create(AppModule, { bodyParser: false }); | |
| // Cap request body size (DoS hardening). Media sends carry base64 in the JSON body, | |
| // so the default is generous; tune with BODY_SIZE_LIMIT. | |
| const bodyLimit = resolveBodyLimit(process.env.BODY_SIZE_LIMIT); | |
| app.use(json({ limit: bodyLimit })); | |
| app.use(urlencoded({ extended: true, limit: bodyLimit })); | |
| // Enable shutdown hooks for graceful shutdown | |
| app.enableShutdownHooks(); | |
| // Wire up graceful shutdown service | |
| const shutdownService = app.get(ShutdownService); | |
| shutdownService.setShutdownCallback(async () => { | |
| await app.close(); | |
| }); | |
| // Enhanced Security Headers (Phase 3 Security Audit) | |
| app.use( | |
| helmet({ | |
| contentSecurityPolicy: { | |
| directives: { | |
| defaultSrc: ["'self'"], | |
| styleSrc: ["'self'", "'unsafe-inline'"], | |
| scriptSrc: ["'self'"], | |
| imgSrc: ["'self'", 'data:', 'https:'], | |
| connectSrc: ["'self'"], | |
| fontSrc: ["'self'"], | |
| objectSrc: ["'none'"], | |
| frameAncestors: ["'self'", "https://*.hf.space", "https://huggingface.co"], | |
| upgradeInsecureRequests: process.env.NODE_ENV === 'production' ? [] : null, | |
| }, | |
| }, | |
| hsts: { | |
| maxAge: 31536000, | |
| includeSubDomains: true, | |
| preload: true, | |
| }, | |
| noSniff: true, | |
| referrerPolicy: { policy: 'strict-origin-when-cross-origin' }, | |
| // Disable for API usage | |
| crossOriginResourcePolicy: { policy: 'cross-origin' }, | |
| }), | |
| ); | |
| // CORS Configuration (Phase 3 Security Audit; #221 hardening) | |
| app.enableCors({ | |
| origin: true, // Allow any origin | |
| credentials: true, | |
| methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'], | |
| allowedHeaders: ['Content-Type', 'X-API-Key', 'Authorization', 'X-Request-ID'], | |
| exposedHeaders: ['X-RateLimit-Limit', 'X-RateLimit-Remaining', 'X-RateLimit-Reset'], | |
| maxAge: 86400, // 24 hours | |
| }); | |
| // Global prefix | |
| app.setGlobalPrefix('api'); | |
| // Enhanced Validation pipe with security options | |
| app.useGlobalPipes( | |
| new ValidationPipe({ | |
| whitelist: true, // Strip properties not in DTO | |
| forbidNonWhitelisted: true, // Throw error on unknown properties | |
| transform: true, | |
| transformOptions: { | |
| enableImplicitConversion: true, | |
| }, | |
| disableErrorMessages: process.env.NODE_ENV === 'production', // Hide details in prod | |
| }), | |
| ); | |
| // Swagger documentation (gated by ENABLE_SWAGGER; default on) | |
| if (isSwaggerEnabled(process.env.ENABLE_SWAGGER)) { | |
| const config = createSwaggerConfig(); | |
| const document = SwaggerModule.createDocument(app, config); | |
| SwaggerModule.setup('api/docs', app, document); | |
| } | |
| // Protect the Bull Board queue UI (/api/admin/queues). It is mounted by | |
| // @bull-board/nestjs as raw Express middleware that the global ApiKeyGuard | |
| // does not cover; registering this before app.listen() ensures it runs ahead | |
| // of the Bull Board router. Requires a valid ADMIN API key. | |
| const bullBoardAuth = new BullBoardAuthMiddleware(app.get(AuthService)); | |
| app.use('/api/admin/queues', (req: Request, res: Response, next: NextFunction) => { | |
| void bullBoardAuth.use(req, res, next); | |
| }); | |
| const port = process.env.PORT || 7860; | |
| await app.listen(port, "0.0.0.0"); | |
| console.log(`🚀 OpenWA is running on: http://localhost:${port}`); | |
| console.log(`📚 Swagger docs: http://localhost:${port}/api/docs`); | |
| } | |
| void bootstrap(); | |