CodeDocs Vault

01 - Entry Points & Execution Flow

NestJS API Bootstrap

File: apps/api/src/main.ts

The API bootstraps a NestJS application with the following configuration:

  1. CORS: Enabled for all origins with credentials support; exposes Content-Disposition header for file downloads
  2. Security headers: Helmet middleware with custom CSP directives (allows inline styles/scripts for Swagger UI)
  3. Body parser limits: 150 MB for both JSON and URL-encoded bodies (supports base64 file uploads)
  4. Global validation pipe: ValidationPipe with whitelist, forbidNonWhitelisted, and implicit type conversion
  5. API versioning: URI-based versioning (default v1), e.g., /api/v1/tasks
  6. Swagger/OpenAPI: Available at /api/docs in development, with API key security scheme and persistent authorization
  7. Graceful shutdown: SIGTERM/SIGINT handlers for clean process termination

Registered modules (28 feature modules in apps/api/src/app.module.ts):

Module Purpose
AuthModule Authentication (API key + JWT)
OrganizationModule Multi-tenant org management
PeopleModule Employee/personnel records
RisksModule Risk register and assessment
VendorsModule Third-party vendor management
ContextModule Organization context Q&A
DevicesModule Device inventory
PoliciesModule Policy CRUD and publishing
DeviceAgentModule Fleet MDM agent
AttachmentsModule File upload/download (S3)
TasksModule Compliance task management
EvidenceExportModule Evidence export (PDF/ZIP)
CommentsModule Threaded comments on tasks
HealthModule Health check endpoints
TrustPortalModule Public trust portal config
TaskTemplateModule Framework editor task templates
FindingTemplateModule Finding templates
FindingsModule Security findings
QuestionnaireModule Security questionnaire answering
VectorStoreModule Embedding sync and search
KnowledgeBaseModule Document knowledge base
SOAModule Statement of Applicability
IntegrationPlatformModule Integration runtime
CloudSecurityModule Cloud security scanning
BrowserbaseModule Browser automation
TaskManagementModule Task scheduling/orchestration
AssistantChatModule AI chat assistant
TrainingModule Security awareness training

Global configuration:

Next.js Frontend Entry

File: apps/app/src/app/page.tsx

The root page is a server component that handles the initial routing decision:

HTTP GET /
  → auth.api.getSession()
    → No session?  → redirect /auth
    → No active org?
      → Pending invite? → redirect /invite/:id
      → Otherwise       → redirect /setup
    → intent=create-additional? → redirect /setup
    → Org not onboarded?       → redirect /onboarding/:orgId
    → User not a member?       → redirect /setup
    → Otherwise                → redirect /:orgId/frameworks

File: apps/app/src/app/layout.tsx

The root layout wraps the application with:

Portal App

Directory: apps/portal/

The portal is a separate Next.js 16 application (port 3002) for external access:

Route structure:

/auth                          → Portal authentication
/(app)/(home)/                 → Dashboard and task overview
/(app)/(home)/[orgId]/         → Organization-specific dashboard
/(app)/(home)/[orgId]/policy/[policyId]/ → Policy acceptance view
/api/auth/[...all]             → Better Auth API routes
/api/download-agent/           → Device agent downloads
/api/fleet-policy/             → Fleet policy endpoints

Authentication Flow

File: apps/api/src/auth/hybrid-auth.guard.ts

The HybridAuthGuard implements a dual authentication strategy that supports both external API consumers and the internal frontend:

Incoming request
  │
  ├─ Has X-API-Key header?
  │   → Hash key (SHA256 + optional salt)
  │   → Look up in DB (apiKey table)
  │   → Check expiration
  │   → Set: organizationId, authType='api-key', isApiKey=true
  │   → Roles: null (org-scoped only)
  │
  └─ Has Authorization: Bearer <token>?
      → Validate JWT against Better Auth JWKS endpoint
      → JWKS cached (60s max age, 10s cooldown)
      → On key mismatch: retry with fresh JWKS (0 cache)
      → Require X-Organization-Id header
      → Verify user membership in requested org (DB lookup)
      → Set: userId, userEmail, userRoles, organizationId, authType='jwt'

Additional guards in apps/api/src/auth/:

Guard Purpose
ApiKeyGuard API key-only authentication (simpler variant)
InternalTokenGuard Validates X-Internal-Token for service-to-service calls
PlatformAdminGuard JWT + platform admin flag check
RequireRoles Role-based authorization decorator

Auth configuration (apps/app/src/utils/auth.ts):

Better Auth is configured with:

Request Lifecycle

A typical authenticated API request flows through:

HTTP Request
  → Express middleware (Helmet, CORS, body parser)
  → ThrottlerGuard (100 req/60s rate limit)
  → HybridAuthGuard (API key or JWT validation)
  → Optional: RequireRoles guard
  → NestJS Controller (route handler)
  → Service layer (business logic)
  → Prisma ORM → PostgreSQL
  → Response serialization → HTTP Response

Trigger.dev Background Jobs

Directory: apps/app/src/trigger/tasks/

Background jobs are defined as Trigger.dev tasks and organized by domain:

Directory Tasks
onboarding/ onboard-organization — full org setup, policy generation, risk assessment
onboarding/ generate-full-policies — LLM-based policy content generation
onboarding/ generate-risk-mitigation, generate-vendor-mitigation — AI assessments
task/ task-schedule — recurring task creation on schedules
task/ policy-schedule — periodic policy review reminders
task/ weekly-task-reminder — email digest of pending tasks
email/ new-policy-email, publish-all-policies-email, weekly-task-digest-email
integration/ run-integration-tests, integration-schedule, integration-results
device/ create-fleet-label-for-org, create-fleet-label-for-all-orgs
scrape/ research — Firecrawl-based web scraping
auditor/ generate-auditor-content — AI-generated audit preparation content

API-side tasks (apps/api/src/trigger/questionnaire/):