Skip to main content

Internals

Architecture

A tour of the VulnRadar codebase: how the pieces fit together, where config lives, and how a request flows from browser to database.

Overview

VulnRadar is a Next.js 15 App Router application with a single-process deployment. The runtime stack is deliberately small: one Next.js process + one PostgreSQL database. No Redis, no message broker, no separate API server. Everything you need to understand lives in this repository.

Project Layout

text
vulnradar.dev/
├── app/                          # Next.js App Router
│   ├── (root pages)              # /, /landing, /pricing, /demo, /contact, /donate
│   ├── admin/                    # Admin dashboard (staff-gated)
│   ├── api/v3/                   # REST API v3 (and /api/security-txt, /api/version)
│   ├── dashboard/                # User dashboard (authenticated)
│   ├── docs/                     # This documentation site
│   ├── history/                  # Scan history (authenticated)
│   ├── legal/                    # Terms, privacy, etc.
│   ├── login, signup,            # Auth pages
│   ├── forgot-password,
│   │  reset-password,
│   │  verify-email
│   ├── pricing/                  # Pricing + Stripe checkout
│   ├── profile/                  # User profile
│   ├── shared/[token]/           # Public shared-scan viewer
│   ├── staff/                    # Public staff list
│   └── teams/                    # Team management
│
├── components/                   # React components (mostly client)
│   ├── admin/                    # Admin UI
│   ├── auth/                     # Auth forms
│   ├── badge/                    # Public badge widgets
│   ├── billing/                  # Stripe checkout UI
│   ├── docs/                     # Documentation site components
│   ├── landing/                  # Marketing landing
│   ├── scanner/                  # Scan UI (results, footer)
│   ├── shared/                   # Cross-cutting (notifications, logo)
│   └── ui/                       # shadcn/ui primitives
│
├── lib/                          # Server-side libraries (no React)
│   ├── api/                      # API helpers (Bearer validation, request utils)
│   ├── auth/                     # Sessions, 2FA, password hashing, device trust
│   ├── billing/                  # Stripe + plan catalog
│   ├── config/                   # Configuration system
│   ├── database/                 # Pool, query helpers, boot/ and schema/
│   ├── discord/                  # Discord OAuth helpers
│   ├── email/                    # Transactional email (SMTP)
│   ├── notifications/            # In-app + email notification preferences
│   ├── rate-limiting/            # Generic + plan-based rate limits
│   ├── reports/                  # SARIF, Markdown, compliance, PDF reports
│   ├── scanner/                  # Detection engine
│   ├── types/                    # Shared TypeScript types
│   └── uploads/                  # Avatar validation
│
├── instrumentation.ts            # Next.js startup hooks (DB init, schema check)
├── middleware.ts                 # Auth + public-path middleware
│
├── public/                       # Static assets
├── scripts/                      # DB migration + audit scripts
│   ├── _lib/                     # Shared helpers
│   ├── create-fresh-db/          # Side-by-side DB clone
│   └── migrate/                  # Schema migrations
│
├── .github/                      # Workflows, dependabot, PR template
├── Dockerfile
├── docker-compose.yml
├── docker-compose.dev.yml
├── next.config.mjs
├── tsconfig.json
├── tailwind.config.mjs
├── eslint.config.mjs
├── vitest.config.ts
└── package.json

Key Subsystems

1. Configuration

See the Configuration page for full details. Flow:

  • lib/config/config-values.ts: raw CONFIG_* constants. Edit this file.
  • lib/config/registry.ts: SETTINGS_REGISTRY classifies each constant (type, bounds, admin tab, runtime or build tier)
  • lib/config/runtime-config.ts: the resolver. Database value ?? environment override ?? shipped default, behind a 30 second cache
  • lib/config/env.ts: Zod validation of the required environment variables at boot
  • lib/config/constants.ts: re-exports + derived maps (RATE_LIMITS, BILLING_PLAN_LIMITS, ROUTES, API)
  • lib/config/client-constants.ts: client-safe subset (no server-only secrets)
  • lib/config/registry.ts: classifies every configurable CONFIG_* value into a settings registry (type, bounds, admin-facing tab, and whether an edit takes effect immediately or only on the next build) that drives the admin settings UI at /admin and the runtime resolver below
  • lib/config/runtime-config.ts: resolves a registry key database-override, then env, then shipped default, with a short in-process cache invalidated on write

2. Database

  • Driver: pg (the @neondatabase/serverless dependency is installed but the app uses node-postgres via lib/database/db.ts)
  • Pool: single instance in lib/database/db.ts (max 10, 5s connect timeout, DATABASE_SSL/DATABASE_SSL_CA respected)
  • Schema: every CREATE / ALTER / DROP lives in lib/database/schema/ as one ordered list of steps (01-core, 02-features, 03-integrations, 04-constraints, seeds), applied at boot by lib/database/boot/apply-boot-schema.ts and by npm run db:create. It used to be 4,000 lines of template literals inside instrumentation.ts, which is why a database built by db:create silently missed constraints no tool could extract from that file
  • Schema version gate: instrumentation.ts reads the vulnradar_schema_meta row and refuses to start if schema_version < CONFIG_MIN_SCHEMA_VERSION
  • Migration: npm run db:migrate runs scripts/migrate/migrate.mjs (interactive, with --dry-run)
  • Side-by-side clone: npm run db:create runs scripts/create-fresh-db/create-fresh-db.mjs

3. Authentication

  • Sessions: DB-backed (table sessions), cookie value is a 64-hex random id, httpOnly + sameSite=lax + 7-day TTL. See lib/auth/auth.ts.
  • Password hashing: node:crypto scrypt (N=131072, r=8, p=1, 16-byte salt, 64-byte derived key). Format: N:r:p:saltHex:hashHex.
  • 2FA: hand-rolled TOTP (RFC 6238, SHA-1, 6 digits, 30s step, ±1 window) in lib/auth/totp.ts. Backup codes (8 per user, hashed via scrypt). Email 2FA alternative in lib/email/email.ts.
  • Password reset / email verify: 32-byte hex tokens stored as sha256(token) in their respective tables; lifetimes are CONFIG_PASSWORD_RESET_HOURS=1 and CONFIG_EMAIL_VERIFICATION_HOURS=24.
  • Device trust: per-device 256-bit random token in device_trust; 30-day cookie. See lib/auth/device-trust.ts.
  • Discord OAuth: HMAC-signed state with AUTH_SECRET || API_KEY_ENCRYPTION_KEY, 5-minute TTL. Two actions: ?action=connect (link existing) and ?action=login (sign in via Discord).
  • API auth: Bearer API keys with prefix vr_live_; encrypted at rest with AES-256-GCM via lib/auth/crypto.ts using API_KEY_ENCRYPTION_KEY (64 hex chars).
  • IP binding: optional, off by default, admin-configurable. Sessions can be bound to the subnet they started on (default /24 IPv4, /48 IPv6); a mismatch deletes the session and asks for login again. API keys can be bound the same way with stricter default prefixes (/32 IPv4, /128 IPv6, i.e. exact match). See Configuration.

4. Scanner Engine

The detection engine is split across per-category files:

  • lib/scanner/checks/*.ts: 13 synchronous per-category detector modules (headers, ssl, content, cookies, configuration, information-disclosure, code, api, secrets-extended, vibe-code, client-side, supply-chain, host-validation). Each exports detectors: Record<id, EvidenceFn> where EvidenceFn returns string | null. tls, dns, and email run separately as async modules (see below) because they need a live socket rather than a fixed response body.
  • lib/scanner/checks-data/*.json: human-readable metadata (title, description, severity, category, fix steps, code examples) for every legacy detector. 852 entries across the per-category files; the live count is always GET /api/v3/finding-types.
  • lib/scanner/checks/page-checks/: 55 checks on a newer PageCheck architecture that run against a real parsed page instead of a flat-string regex. lib/scanner/page-context.ts builds a PageContext once per scan (parsed forms, scripts with resolved origins, CSP directives with fallback-to-default-src semantics, parsed cookies, deduped third-party origins), and lib/scanner/engine.ts (runSyncChecks) runs both the legacy detectors and every applicable page check against it in one pass. Findings from either source carry a 0-100 confidence score keyed to the detection method and a verbatim evidence excerpt, and a dedupe pass folds duplicate findings from different checks into one survivor. These checks fold into the existing 18 categories rather than adding a new one; combined with the legacy set, the engine now runs 905+ checks.
  • lib/scanner/auth/: ephemeral authenticated scanning for POST /api/v3/scan/authenticated. Credentials travel in that one request and are never persisted; form-based login opens a real, ephemeral BrowserBase browser session over CDP to render and submit the login page, and detects Cloudflare/CAPTCHA bot-protection walls instead of treating them as a failed login. This endpoint scans a single page synchronously (no crawl) using the legacy detector set; it does not yet run the page-checks above.
  • lib/scanner/scan-jobs.ts: background scan jobs. POST /api/v3/scan and POST /api/v3/scan/crawl insert a scan_history row and return { scanId, status: "running" } immediately; the scan itself runs detached from that request (safe because this is a single persistent Node process, not a serverless function), reporting real per-category progress to the row as it goes. GET /api/v3/scan/status/[id] is polled for status, progress, and the final result; a watchdog timer force-fails a job that runs past its time budget.
  • lib/scanner/async-checks.ts: network-dependent checks run in parallel: DNS (SPF, DMARC, DKIM, DNSSEC via Google + Cloudflare DoH), TLS handshake (self-signed / expired / weak protocol), live-fetch (robots.txt sensitive paths, security.txt presence)
  • lib/scanner/protocols/: protocol-specific warnings: https.ts, websocket.ts (7 check IDs), ftp.ts (4 check IDs), banner.ts (TCP banner-grab used by the port sweep below)
  • lib/scanner/safe-fetch.ts: SSRF protection: blocks private IP ranges, localhost, .local/.internal/.lan hostnames; 15s default fetch timeout
  • lib/scanner/access-rules.ts: IP/URL blacklist + whitelist from the access_rules table
  • lib/scanner/safety-rating.ts: maps findings to safe / caution / unsafe for badges

Categories (lib/scanner/types.ts): the Category union has 18 members. 17 of them are in ALL_CATEGORIES and run by default: headers, ssl, tls, content, cookies, configuration, information-disclosure, dns, email, api, code, secrets-extended, vibe-code, client-side, supply-chain, host-validation, reputation. The remaining one, active-probes, is deliberately left out of that list because it writes to the target, so it runs only when a request names it explicitly. Severities: info, low, medium, high, critical.

The port and service sweep (lib/scanner/port-scan.ts) probes a curated set of well-known ports on the target host with bounded concurrency, a short per-port connect timeout, and an overall deadline, never a full 65535 sweep. Each open port is reported with the service usually found there and whatever banner it volunteered; lib/scanner/protocols/banner.ts holds the per-protocol greetings and port allowlists used to read those banners and report version disclosure. It is opt-in per scan with "portScan": true and gated on the same verified-domain check as active probing. The earlier per-service "probes": ["ssh:2222"] array no longer exists: it was collapsed into that single boolean.

5. API Layer

REST v3 is the only API this build serves. There is no /api/v1 or /api/v2 route tree. Each v3 route handler:

  • Wraps the body in a try/catch via the withErrorHandling helper (lib/api/api-utils.ts)
  • Authenticates via getSession() (cookie) or validateApiKey() (Bearer)
  • Validates input with Zod schemas using the Validate helper
  • Applies a rate limit via checkRateLimit (lib/rate-limiting/rate-limit.ts) and/or a daily quota via checkAndRecordRequest (lib/rate-limiting/daily-limits.ts)
  • Returns NextResponse.json with a standard shape on both success and error

6. Billing

  • Plans are defined once in lib/billing/catalog.ts: free, core_supporter, pro_supporter, elite_supporter. Each paid plan auto-generates monthly + yearly variants (yearly is 20% off).
  • Stripe products are auto-created on first call to GET /api/v3/stripe/setup-products; webhooks via GET /api/v3/stripe/setup-webhook
  • Subscription state lives on the users row: plan, stripe_customer_id, stripe_subscription_id, subscription_status, current_period_end, cancel_at_period_end
  • Webhook handler: app/api/v3/webhooks/stripe/route.ts processes checkout.session.completed, customer.subscription.created/updated/deleted, and invoice.payment_succeeded/failed
  • Plan limits and retention windows are in lib/config/config-values.ts under CONFIG_BILLING_*. Disable billing entirely with CONFIG_BILLING_ENABLED = false.

7. Permissions

Nine roles, defined as STAFF_ROLE_HIERARCHY in lib/config/client-constants.ts. The numbers below are read from that table, not typed out here:

text
user              0
support           10
billing           20
security_analyst  20
content_manager   20
ops               20
moderator         30
admin             40
super_admin       50

The gaps of 10 leave room to insert a role without renumbering, and every comparison goes through a named key rather than a literal. Two things the shape does not show on its own:

  • The four roles at level 20 are lateral specialists, not a rung. billing, security_analyst, content_manager and ops sit at the same level and differ by which permissions they hold, not by seniority. Level alone never decides access: the permission check does.
  • super_admin is bootstrap-only. It is assigned to the first account created on a fresh install (lib/auth/auth.ts) and by the 5.5.0 to 5.6.0 migration. No UI or API path can grant it: app/api/v3/admin/route.ts filters it out of the assignable roles before validating a set_role request.
  • lib/auth/permissions-client.ts: the permission model itself (STAFF_PERMISSIONS, hasStaffPermission, canManageRole, getRoleLevel, hasGodMode). Client-safe, and the server imports the same module, so there is no second copy to drift.
  • lib/auth/authorization.ts: route-handler helpers: requireStaff(role?), requireAdmin(), requirePermission(), verifyOwnership(resource, id), verifyTeamMembership(), logAuditAction()

Request Lifecycle

text
Browser / client
  │
  ▼
middleware.ts
  - Allow public paths (lib/config/public-paths.ts)
  - For /api/v3/* with Authorization: Bearer … → pass through
    (the route handler performs API-key validation)
  - Otherwise: parse session cookie → look up session row
    - Disabled / expired session → destroy cookie, redirect to /login
  - Inject Cross-Origin-* security headers
  │
  ▼
Route handler (app/api/v3/<resource>/route.ts)
  1. withErrorHandling wrapper
  2. Auth check (getSession OR validateApiKey)
  3. Rate limit check (lib/rate-limiting/rate-limit.ts)
  4. Daily quota check (lib/rate-limiting/daily-limits.ts, API-key + session)
  5. Input validation (Zod via Validate)
  6. Authorization (requireStaff / requireAdmin / verifyOwnership)
  7. Business logic
  8. Database query (lib/database/db.ts)
  9. ApiResponse.json(...)
  │
  ▼
instrumentation.ts (server startup only)
  - Validate env, install error-log capture
  - Read vulnradar_schema_meta; refuse to start if version < required
  - Take a boot advisory lock, then, inside it:
      apply lib/database/schema/ -> backfills -> cleanup + workers
      -> safety nets. A failure in any of them exits rather than
      serving traffic against a half-built database.

CI/CD Pipeline

text
On push to main / PR
  ├── Lint (ESLint 9, flat config in eslint.config.mjs)
  ├── Typecheck (tsc --noEmit, hard gate)
  ├── Test (vitest run)
  ├── Format check (prettier --check)
  └── Build (next build)

On tag v*
  └── Docker publish (ghcr.io/<owner>/<repo>)

Weekly / on PR
  ├── Stale bot
  ├── Label (PR)
  └── Dependabot → auto-merge patch + minor only

All four checks (lint, typecheck, test, build) run on Node 22 LTS in CI. See .github/workflows/.

Scanner Architecture and Data Model | VulnRadar