Freecodecamp Freecodecamp Deepwiki

Gombloh
-
freecodecamp freecodecamp deepwiki

Loading... Loading... Menu - api/__mocks__/exam.ts - api/package.json - api/src/app.ts - api/src/db/extensions.test.ts - api/src/db/prisma.ts - api/src/plugins/__fixtures__/user.ts - api/src/plugins/cors.test.ts - api/src/plugins/cors.ts - api/src/reset.d.ts - api/src/routes/helpers/challenge-helpers.test.ts - api/src/routes/helpers/challenge-helpers.ts - api/src/routes/protected/challenge.test.ts - api/src/routes/protected/challenge.ts - api/src/routes/public/status.test.ts - api/src/routes/public/status.ts - api/src/schema.test.ts - api/src/schemas.ts - api/src/schemas/user/get-session-user.ts - api/src/server.test.ts - api/src/server.ts - api/src/utils/common-challenge-functions.ts - api/src/utils/create-user.ts - api/src/utils/env.ts - api/src/utils/exam-schemas.ts - api/src/utils/exam-types.ts - api/src/utils/exam.test.ts - api/src/utils/get-challenges.test.ts - api/src/utils/get-challenges.ts - api/src/utils/normalize.test.ts - api/src/utils/normalize.ts - api/src/utils/progress.ts - api/tsconfig.json - client/src/utils/challenge-request-helpers.ts - sample.env The API Server is a Fastify-based Node.js application that handles all server-side operations for freeCodeCamp.

It provides RESTful endpoints for user authentication, challenge submissions, progress tracking, payment processing, and certificate management. The server communicates with MongoDB via Prisma ORM and integrates with third-party services including Auth0, Stripe, PayPal, and AWS SES. For information about client-side state management and Redux, see Redux State Management. For curriculum structure and content processing, see Curriculum. For deployment workflows and CI/CD processes, see CI/CD Pipeline.

Sources: api/src/app.ts1-252 api/src/server.ts1-30 api/package.json6-40 Sources: api/src/app.ts100-251 api/src/plugins/auth.ts api/src/plugins/csrf.ts api/src/db/prisma.ts38-60 The server is built using a factory pattern in build() which returns a configured Fastify instance with TypeBox type provider for type-safe schemas.

Key configuration: - Custom AJV validator with objectid format api/src/app.ts65-81 - Random request ID generation api/src/app.ts88 - Structured logging via Pino api/src/app.ts87 - Request/response logging hooks api/src/app.ts108-118 TypeBox integration: api/src/app.ts105 Plugins are registered in a specific order to ensure proper middleware chain execution: Sources: api/src/app.ts120-174 Routes are organized into two main categories with different authorization levels: Protected route registration: api/src/app.ts177-208 The protected routes are wrapped in authorization hooks: fastify.authorize - populatesreq.user if authenticated api/src/app.ts178fastify.csrfProtection - validates CSRF token api/src/app.ts185fastify.send401IfNoUser - returns 401 if not authenticated api/src/app.ts186fastify.redirectIfNoUser - redirects if not authenticated api/src/app.ts204 Sources: api/src/app.ts177-249 api/src/routes/protected/challenge.ts69-852 api/src/routes/public/status.ts13-29 The server uses Auth0 for OAuth 2.0 authentication.

The auth plugin decorates the Fastify instance with authorization hooks. Configuration: api/src/utils/env.ts176-178 AUTH0_DOMAIN - Auth0 tenant domainAUTH0_CLIENT_ID - OAuth client IDAUTH0_CLIENT_SECRET - OAuth client secret JWT validation: The server validates JWT tokens signed with JWT_SECRET api/src/utils/env.ts213 The auth plugin provides several hooks for different authorization patterns: User object structure: When authenticated, req.user contains { id: string } with the MongoDB user ID.

CSRF protection uses double-submit cookie pattern: - Server sets csrf_token cookie (httpOnly, signed) api/src/plugins/csrf.ts - Client reads cookie and sends value in csrf-token header - Server validates header matches cookie api/src/plugins/csrf.ts CSRF is enabled for: POST, PUT, DELETE requests to protected routes api/src/app.ts180-193 CSRF is disabled for: GET requests, public routes, CodeRoad token-based routes api/src/app.ts196-200 Sources: api/src/plugins/auth.ts api/src/plugins/csrf.ts api/src/app.ts177-208 All request/response schemas are defined using TypeBox and exported from api/src/schemas.ts1-49 Example schema structure: Complete schema exports: api/src/schemas.ts1-49 Custom AJV instance with security-focused configuration api/src/app.ts65-81: Custom format: objectid format validates MongoDB ObjectIDs api/src/app.ts78-80 Schema security validation: All schemas are tested to prevent ReDoS and other attacks api/src/schema.test.ts14-58 Sources: api/src/app.ts65-107 api/src/schemas.ts1-49 api/src/schema.test.ts1-59 Plugin registration: api/src/db/prisma.ts14-32 The Prisma plugin: - Creates PrismaClient with MongoDB connection URL - Applies custom extensions via extendClient() - Connects to database - Decorates Fastify instance with fastify.prisma - Registers disconnect hook on server close Sources: api/src/db/prisma.ts1-63 The extendClient() function adds automatic updateCount incrementing api/src/db/prisma.ts38-60: Purpose: Track the number of times a user document has been updated for audit/debugging purposes.

Testing: api/src/db/extensions.test.ts1-110 Sources: api/src/db/prisma.ts34-60 api/src/db/extensions.test.ts1-110 The normalize.ts utility handles data serialization between MongoDB and the API api/src/utils/normalize.ts1-229: Date handling: MongoDB stores dates as {$date: "ISO8601"} objects, which must be converted to numeric timestamps api/src/utils/normalize.ts69-82 Sources: api/src/utils/normalize.ts1-229 api/src/utils/normalize.test.ts1-215 Sources: api/src/routes/protected/challenge.ts218-252 api/src/utils/common-challenge-functions.ts118-247 Challenge type constants: shared/config/challenge-types.js Endpoint implementations: api/src/routes/protected/challenge.ts69-852 To prevent request body size limit issues, the client can encode file contents in base64: Encoding helper (client-side): client/src/utils/challenge-request-helpers.ts30-36 Decoding helper (server-side): api/src/routes/helpers/challenge-helpers.ts150-165 Endpoints supporting encoded files: /encoded/modern-challenge-completed api/src/routes/protected/challenge.ts254-289/encoded/save-challenge api/src/routes/protected/challenge.ts341-369 The decodeFiles() function converts base64 contents back to UTF-8 strings api/src/routes/helpers/challenge-helpers.ts150-155 Sources: api/src/routes/protected/challenge.ts254-369 api/src/routes/helpers/challenge-helpers.ts144-176 client/src/utils/challenge-request-helpers.ts30-36 Exam challenges use a multi-stage validation process: - Exam generation ( GET /exam/:id ) api/src/routes/protected/challenge.ts371-469:- Verify user completed prerequisites - Load exam from MongoDB via Prisma - Validate exam structure with Joi api/src/utils/exam-schemas.ts64-96 - Generate randomized exam with generateRandomExam() api/src/utils/exam.ts - Return shuffled questions with 5 answers each (1 correct, 4 wrong) - Exam submission ( POST /exam-challenge-completed ) api/src/routes/protected/challenge.ts576-796:- Validate user answers with Joi api/src/utils/exam-schemas.ts160-172 - Grade exam with createExamResults() api/src/utils/exam.ts - Always save to completedExams[] for record keeping - If passed, add/update in completedChallenges[] - If already passed with better score, keep old score - Add point only on first pass Exam data structures: GeneratedExam - Randomized exam sent to client api/src/utils/exam-types.ts12-13UserExam - User's submitted answers api/src/utils/exam-types.ts22-25ExamResults - Graded results [Prisma schema] Validation schemas: api/src/utils/exam-schemas.ts1-193 Sources: api/src/routes/protected/challenge.ts371-796 api/src/utils/exam.ts api/src/utils/exam-schemas.ts1-193 api/src/utils/exam-types.ts1-26 Common challenge operations are abstracted in common-challenge-functions.ts : updateUserChallengeData() api/src/utils/common-challenge-functions.ts118-247: - Main function for persisting challenge completion - Handles duplicate submissions (preserves original completedDate ) - Manages savedChallenges for multifile cert projects - Updates progressTimestamps for point calculation - Removes from partiallyCompletedChallenges on full completion saveUserChallengeData() api/src/utils/common-challenge-functions.ts84-106: - Saves challenge files without marking as complete - Used by /save-challenge endpoint for auto-save - Updates or adds to savedChallenges[] array Challenge ID lists: jsCertProjectIds - JavaScript certification projects common-challenge-functions.ts8-14multifileCertProjectIds - Multifile certification projects common-challenge-functions.ts16-18multifilePythonCertProjectIds - Python cert projects common-challenge-functions.ts20-22msTrophyChallenges - Microsoft trophy challenges common-challenge-functions.ts24-26 Sources: api/src/utils/common-challenge-functions.ts1-248 The server validates required environment variables at startup api/src/utils/env.ts50-62: Production-only requirements: api/src/utils/env.ts90-157 SES_ID ,SES_SECRET - AWS SES credentialsSENTRY_DSN ,SENTRY_ENVIRONMENT - Error trackingCOOKIE_DOMAIN - Cookie domain scopeDEPLOYMENT_VERSION - Deployment identifierGROWTHBOOK_FASTIFY_API_HOST ,GROWTHBOOK_FASTIFY_CLIENT_KEY - Feature flags- All default values must be changed Log level configuration: api/src/utils/env.ts63-88 FCC_API_LOG_LEVEL - Log verbosity (fatal ,error ,warn ,info ,debug ,trace ,silent )FCC_API_LOG_TRANSPORT - Log format (pretty ordefault ) Provider selection: api/src/app.ts134-136 Sources: api/src/utils/env.ts1-233 sample.env1-77 The API integrates with GrowthBook for A/B testing and feature rollouts api/src/app.ts129-132: Configuration: GROWTHBOOK_FASTIFY_API_HOST - GrowthBook API endpointGROWTHBOOK_FASTIFY_CLIENT_KEY - SDK client key Usage in code: The ??

Feature flags used: swagger-ui - Swagger documentation app.ts139shadow-capture - Shadow mode capture app.ts167exam-environment - Exam environment app.ts226sentry-routes - Sentry proxy app.ts236 Sources: api/src/app.ts129-239 api/src/plugins/growth-book.ts The error-handling plugin provides centralized error handling api/src/plugins/error-handling.ts: Capabilities: - Catches unhandled errors from route handlers - Logs errors with structured logging - Reports errors to Sentry in production - Returns appropriate HTTP status codes Individual routes can override the global error handler with custom logic: Example: Challenge submission error formatting api/src/routes/protected/challenge.ts78-87 The server uses Pino for structured JSON logging api/src/utils/logger.ts: Log levels: api/src/utils/env.ts63-71 fatal - Application crasherror - Errors requiring attentionwarn - Warningsinfo - General information (default)debug - Debug informationtrace - Detailed trace informationsilent - No logging Request/response logging: api/src/app.ts108-118 - Every request generates a unique ID - Request details logged at debug level - Response details logged after completion - Child loggers used for request context Conditional logging: /status/* routes use debug level to reduce noise api/src/plugins/cors.test.ts24-36- Challenge submission uses debug level (high volume) api/src/routes/protected/challenge.ts237-242 - CORS plugin uses debug for status routes, info for others api/src/plugins/cors.ts13-30 Error tracking is configured via Sentry api/src/instrument.ts: Configuration: SENTRY_DSN - Sentry project DSNSENTRY_ENVIRONMENT - Environment identifierDEPLOYMENT_VERSION - Release version Manual error capture: Route handlers can explicitly capture errors: Sources: api/src/plugins/error-handling.ts api/src/utils/logger.ts api/src/instrument.ts api/src/app.ts108-118 The API uses Vitest for unit and integration testing with a custom test server setup api/vitest.utils.ts: setupServer() - Creates a test Fastify instance: - Uses in-memory test database (separate per worker) - Mocks environment variables - Provides helper functions for authenticated requests Test database isolation: Each Vitest worker gets a unique database api/src/utils/env.ts36-48: Example test structure: api/src/routes/protected/challenge.test.ts225-238 Fetch mocking: api/vitest.utils.ts createFetchMock() - Creates mock fetch responses for external API testing Prisma mocking: Tests can spy on Prisma methods: Microsoft Learn API mocking: api/src/routes/helpers/challenge-helpers.test.ts81-170 - Mocks profile API responses - Mocks achievements API responses - Tests various error conditions Major test files: - api/src/routes/protected/challenge.test.ts - Challenge submission endpoints (1245 lines) - api/src/utils/normalize.test.ts - Data normalization functions - api/src/db/extensions.test.ts - Prisma extension behavior - api/src/server.test.ts - Security headers and CORS - api/src/schema.test.ts - Schema security validation Schema security testing: api/src/schema.test.ts14-58 All schemas are validated against ajv/lib/refs/json-schema-secure.json to prevent: - ReDoS (Regular Expression Denial of Service) - Prototype pollution - Code injection Sources: api/vitest.utils.ts api/src/routes/protected/challenge.test.ts1-1245 api/src/schema.test.ts1-59 Two simple endpoints for monitoring and health checks api/src/routes/public/status.ts13-29: No authentication required - These are public endpoints for monitoring systems.

Deployment version source: api/src/utils/env.ts232 Sources: api/src/routes/public/status.ts1-30 api/src/routes/public/status.test.ts1-26 When enabled, the API serves interactive Swagger UI documentation api/src/app.ts139-165: Enable via: - Environment: FCC_ENABLE_SWAGGER_UI=true - Feature flag: swagger-ui in GrowthBook Access at: ${API_LOCATION}/documentation CSRF integration: The Swagger UI automatically extracts the csrf_token cookie and includes it as the csrf-token header api/src/app.ts151-161: Schema source: All TypeBox schemas from api/src/schemas.ts are automatically included in the OpenAPI spec.

Sources: api/src/app.ts139-165 Refresh this wiki - API Server - Purpose and Scope - Overall Architecture - Request Lifecycle - Core Components - Fastify Instance Creation - Plugin Registration Order - Route Organization - Authentication and Authorization - Auth0 Integration - Authorization Hooks - CSRF Protection - Schema Validation - TypeBox Schema Definition - Schema Categories - AJV Validator Configuration - Database Layer - Prisma ORM Setup - Prisma Extensions - Data Normalization - Challenge Submission System - Challenge Submission Flow - Challenge Types and Endpoints - Base64 Encoding for Large Files - Exam Challenge System - Challenge Data Helpers - Configuration and Environment Variables - Required Environment Variables - Optional Feature Flags - Email Provider Configuration - Feature Flag Integration (GrowthBook) - Error Handling and Logging - Global Error Handler - Custom Error Handlers - Structured Logging - Sentry Integration - Testing Infrastructure - Test Setup - Test Utilities - Mock Services - Test Coverage - Health Check and Status Endpoints - Status Routes - API Documentation (Swagger)

People Also Asked

freeCodeCamp/freeCodeCamp | DeepWiki?

Loading... Loading... Menu - api/__mocks__/exam.ts - api/package.json - api/src/app.ts - api/src/db/extensions.test.ts - api/src/db/prisma.ts - api/src/plugins/__fixtures__/user.ts - api/src/plugins/cors.test.ts - api/src/plugins/cors.ts - api/src/reset.d.ts - api/src/routes/helpers/challenge-helpers.test.ts - api/src/routes/helpers/challenge-helpers.ts - api/src/routes/protected/challenge.test.ts...

Build and Deployment Workflows | freeCodeCamp/freeCodeCamp | DeepWiki?

It provides RESTful endpoints for user authentication, challenge submissions, progress tracking, payment processing, and certificate management. The server communicates with MongoDB via Prisma ORM and integrates with third-party services including Auth0, Stripe, PayPal, and AWS SES. For information about client-side state management and Redux, see Redux State Management. For curriculum structure a...

API Server | freeCodeCamp/freeCodeCamp | DeepWiki?

Loading... Loading... Menu - api/__mocks__/exam.ts - api/package.json - api/src/app.ts - api/src/db/extensions.test.ts - api/src/db/prisma.ts - api/src/plugins/__fixtures__/user.ts - api/src/plugins/cors.test.ts - api/src/plugins/cors.ts - api/src/reset.d.ts - api/src/routes/helpers/challenge-helpers.test.ts - api/src/routes/helpers/challenge-helpers.ts - api/src/routes/protected/challenge.test.ts...

Authentication and Authorization | freeCodeCamp/freeCodeCamp | DeepWiki?

Key configuration: - Custom AJV validator with objectid format api/src/app.ts65-81 - Random request ID generation api/src/app.ts88 - Structured logging via Pino api/src/app.ts87 - Request/response logging hooks api/src/app.ts108-118 TypeBox integration: api/src/app.ts105 Plugins are registered in a specific order to ensure proper middleware chain execution: Sources: api/src/app.ts120-174 Routes ar...

System Architecture | freeCodeCamp/freeCodeCamp | DeepWiki?

Sources: api/src/app.ts139-165 Refresh this wiki - API Server - Purpose and Scope - Overall Architecture - Request Lifecycle - Core Components - Fastify Instance Creation - Plugin Registration Order - Route Organization - Authentication and Authorization - Auth0 Integration - Authorization Hooks - CSRF Protection - Schema Validation - TypeBox Schema Definition - Schema Categories - AJV Validator C...