fix(core): remediate backend audit findings across P0-P3 vulnerabilities and performance issues
Backend Audit Remediation & Quality Enhancements (P0 – P3)
Overview
This PR resolves all confirmed findings from the full-project audit across security, concurrency/memory safety, database performance, and API contract compliance.
Key Changes
1. Security & Authentication (P0 & P1)
-
Fail-Fast Secret Validation: Added boot-time validation requiring
JWT_ACCESS_SECRET/JWT_REFRESH_SECRET(>= 32 chars) andWEBHOOK_ENCRYPTION_KEY(64-character hex string) to prevent silent fallback to default keys. -
Dedicated Email Verification Secret: Isolated email verification signing via
jwtConfig.emailVerificationSecretto eliminate token reuse vectors. -
Cryptographic Reset Password Flow: Isolated structural decode, user resolution, and cryptographic signature validation in
verifyResetToken(), ensuring no state mutation or token revocation occurs prior to verification. -
Real-Time Role Enforcement: Updated
authMiddlewareto assignreq.user.rolefrom the freshly queried database record rather than relying on stale JWT claims. - Token Leak Prevention: Removed raw password-reset token printing from stdout/dev console logs.
-
CORS Configuration: Decoupled CORS configuration from email settings, added multi-origin whitelist support via
CORS_ALLOWED_ORIGINS, and configuredmaxAge: 86400preflight caching.
2. Database & Resource Optimization (P0 & P2)
-
Memory-Safe Diff Projection: Replaced full page loading (
include: { pages: true }) with selective field projection (url,normalizedUrl,contentHash,wordCount,status,statusCode,title,crawledAt) during diff generation, preventing worker heap exhaustion on large crawl jobs. -
Asset Pagination: Added
pageandlimit(max 500) parameters withskip/takepagination toGET /crawl-jobs/:id/assets. -
Single-Query API Key Auth: Joined the
userrelation inApiKeyRepository.findByHash, eliminating a sequential redundant database roundtrip. -
Database Indexing: Added composite index
@@index([jobId, createdAt])onCrawlJobLogand@@index([ipAddress])onAuditLoginprisma/schema.prisma. -
Repository Cleanup: Removed unused duplicate
findByUserIdmethods in favor of standardizedfindAllByUser.
3. API Contract & Validation (P1 & P3)
-
Standardized Response Envelopes: Wrapped
GET /crawl-jobs/:id/diffin{ success: true, data: diffReport }to strictly match the API response contract. -
SSE Connection Guarding: Added a 30-minute maximum stream TTL guard and increased the polling interval to 3 seconds in
streamEventsto prevent lingering database connections. -
Reusable Path Validation: Added
validateParams()middleware invalidate.middleware.tsreturning standard 422VALIDATION_ERRORenvelopes. -
Password Refinement: Added validation rule requiring
newPassword !== currentPasswordinchangePasswordSchema. -
OpenAPI Documentation: Updated and regenerated Swagger definitions (
src/docs/swagger.json).