01 - Entry Points & Execution Flow
NestJS API Bootstrap
File: apps/api/src/main.ts
The API bootstraps a NestJS application with the following configuration:
- CORS: Enabled for all origins with credentials support; exposes
Content-Dispositionheader for file downloads - Security headers: Helmet middleware with custom CSP directives (allows inline styles/scripts for Swagger UI)
- Body parser limits: 150 MB for both JSON and URL-encoded bodies (supports base64 file uploads)
- Global validation pipe:
ValidationPipewithwhitelist,forbidNonWhitelisted, and implicit type conversion - API versioning: URI-based versioning (default
v1), e.g.,/api/v1/tasks - Swagger/OpenAPI: Available at
/api/docsin development, with API key security scheme and persistent authorization - Graceful shutdown:
SIGTERM/SIGINThandlers 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:
ConfigModule(global) with AWS and Better Auth config loadersThrottlerModule: 100 requests per 60 seconds per IP (applied asAPP_GUARD)
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:
@trycompai/design-systemglobal CSSProviderscomponent (React context: auth session, theme, query client)NuqsAdapterfor URL search param state managementToaster(sonner) for notifications- Analytics: Vercel Analytics, Dub Analytics (optional), LinkedIn Insight (optional)
- Fonts: GeneralSans (variable), GeistMono
Portal App
Directory: apps/portal/
The portal is a separate Next.js 16 application (port 3002) for external access:
- Employee tasks: Policy acceptance, training completion, device agent installation
- Policy viewer: PDF viewing and digital signature/acceptance
- Organization dashboard: Task progress overview per employee
- Auth: Separate Better Auth instance with magic link and Microsoft OAuth
- API routes: Fleet policy management, device agent download, auth endpoints
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:
- Prisma adapter (PostgreSQL)
- Plugins: organization, magicLink (1h expiry), emailOTP (6-digit, 10min expiry), jwt (1h expiry), bearer, multiSession, nextCookies
- OAuth providers: Google, GitHub, Microsoft (conditionally enabled via env vars)
- Database hooks: On session creation, auto-sets
activeOrganizationIdto the user's most recent organization - Account linking: Enabled for Google, GitHub, Microsoft
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/):
answer-question— RAG-based questionnaire answering with vector searchparse-questionnaire— Questionnaire file parsing and extraction