Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
329 changes: 328 additions & 1 deletion package-lock.json

Large diffs are not rendered by default.

6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
"@fastify/helmet": "^13.0.1",
"@fastify/jwt": "^9.0.2",
"@fastify/rate-limit": "^10.2.0",
"@fastify/swagger": "^9.8.1",
"@fastify/swagger-ui": "^5.2.6",
"@opentelemetry/api": "^1.9.1",
"@opentelemetry/exporter-trace-otlp-http": "^0.219.0",
"@opentelemetry/instrumentation-fastify": "^0.56.0",
Expand Down Expand Up @@ -50,13 +52,13 @@
"@types/sanitize-html": "^2.16.1",
"@typescript-eslint/eslint-plugin": "^8.61.1",
"@typescript-eslint/parser": "^8.61.1",
"@vitest/coverage-v8": "^3.0.4",
"drizzle-kit": "^0.30.1",
"eslint": "^9.17.0",
"pino-pretty": "^13.0.0",
"tsx": "^4.19.2",
"typescript": "^5.7.3",
"typescript-eslint": "^8.61.1",
"vitest": "^3.0.4",
"@vitest/coverage-v8": "^3.0.4"
"vitest": "^3.0.4"
}
}
9 changes: 6 additions & 3 deletions src/audit/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { logger } from "../utils/logger.js";
import { db } from "../config/database.js";
import { auditLogs } from "../database/schema.js";
import { getRequestId } from "../utils/request-context.js";

type AuditEvent =
| "quiz.submitted"
Expand All @@ -24,13 +25,15 @@ interface AuditFields {
queued?: boolean;
ip?: string;
userAgent?: string;
requestId?: string;
}

export async function auditLog(event: AuditEvent, fields: AuditFields): Promise<void> {
logger.info({ audit: true, event, ...fields }, `audit: ${event}`);
const auditFields = { requestId: getRequestId(), ...fields };
logger.info({ audit: true, event, ...auditFields }, `audit: ${event}`);
for (let attempt = 0; attempt < 3; attempt++) {
try {
await db.insert(auditLogs).values({ event, fields });
await db.insert(auditLogs).values({ event, fields: auditFields });
return;
} catch (err) {
if (attempt < 2) {
Expand All @@ -39,7 +42,7 @@ export async function auditLog(event: AuditEvent, fields: AuditFields): Promise<
}
logger.error({ err }, "Failed to persist audit log after 3 attempts");
process.stdout.write(
JSON.stringify({ audit: true, event, ...fields, persistError: String(err) }) + "\n",
JSON.stringify({ audit: true, event, ...auditFields, persistError: String(err) }) + "\n",
);
}
}
Expand Down
2 changes: 2 additions & 0 deletions src/database/migrations/0010_users_stellar_address_index.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
CREATE INDEX IF NOT EXISTS idx_users_stellar_address
ON users (stellar_address);
3 changes: 2 additions & 1 deletion src/database/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ export const users = pgTable(
updatedAt: timestamp("updated_at", { withTimezone: true })
.notNull()
.defaultNow(),
}
},
(table) => [index("idx_users_stellar_address").on(table.stellarAddress)]
);

// ─── Courses ────────────────────────────────────────────────────────────────
Expand Down
12 changes: 12 additions & 0 deletions src/modules/courses/course.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,15 @@ export async function courseRoutes(app: FastifyInstance): Promise<void> {
schema: {
description: "List available courses",
tags: ["courses"],
querystring: {
type: "object",
properties: {
difficulty: { type: "string", enum: ["beginner", "intermediate", "advanced"] },
search: { type: "string" },
page: { type: "integer", minimum: 1, default: 1 },
limit: { type: "integer", minimum: 1, maximum: 50, default: 20 },
},
},
} as FastifySchema,
},
(request, reply) => courseController.list(request, reply)
Expand All @@ -24,6 +33,7 @@ export async function courseRoutes(app: FastifyInstance): Promise<void> {
schema: {
description: "Get course details by ID",
tags: ["courses"],
params: { type: "object", required: ["id"], properties: { id: { type: "string", format: "uuid" } } },
} as FastifySchema,
},
(request, reply) => courseController.getById(request, reply)
Expand All @@ -36,6 +46,8 @@ export async function courseRoutes(app: FastifyInstance): Promise<void> {
schema: {
description: "Enroll in a course",
tags: ["courses"],
security: [{ bearerAuth: [] }],
params: { type: "object", required: ["id"], properties: { id: { type: "string", format: "uuid" } } },
} as FastifySchema,
},
(request, reply) => courseController.enroll(request, reply)
Expand Down
12 changes: 11 additions & 1 deletion src/modules/courses/course.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { eq, and, count, desc, inArray } from "drizzle-orm";
import { eq, and, count, desc, inArray, ilike, or } from "drizzle-orm";
import { db } from "../../config/database.js";
import { courses, enrollments, quizzes } from "../../database/schema.js";
import { NotFoundError, ConflictError } from "../../utils/errors.js";
Expand Down Expand Up @@ -50,10 +50,12 @@ export class CourseService {
query: ListCoursesQuery,
): Promise<{ courses: CourseSummary[]; total: number }> {
const namespace = "courses";
const search = query.search?.trim() || undefined;
const cacheKeyString = cacheKey(
namespace,
"list",
query.difficulty ?? "all",
search ? encodeURIComponent(search.toLowerCase()) : "all",
query.page,
query.limit,
);
Expand All @@ -68,6 +70,14 @@ export class CourseService {
if (query.difficulty) {
conditions.push(eq(courses.difficulty, query.difficulty));
}
if (search) {
conditions.push(
or(
ilike(courses.title, `%${search}%`),
ilike(courses.description, `%${search}%`),
)!,
);
}

const where = and(...conditions);
const offset = (query.page - 1) * query.limit;
Expand Down
1 change: 1 addition & 0 deletions src/modules/courses/course.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { z } from "zod";

export const listCoursesSchema = z.object({
difficulty: z.enum(["beginner", "intermediate", "advanced"]).optional(),
search: z.string().optional(),
page: z.coerce.number().int().min(1).default(1),
limit: z.coerce.number().int().min(1).max(50).default(20),
});
Expand Down
10 changes: 10 additions & 0 deletions src/modules/credentials/credential.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,15 @@ export async function credentialRoutes(app: FastifyInstance): Promise<void> {
schema: {
description: "Mint a course completion credential (NFT)",
tags: ["credentials"],
security: [{ bearerAuth: [] }],
body: {
type: "object", required: ["courseId", "submissionId", "idempotencyKey"],
properties: {
courseId: { type: "string", format: "uuid" },
submissionId: { type: "string", format: "uuid" },
idempotencyKey: { type: "string", minLength: 16, maxLength: 64 },
},
},
} as FastifySchema,
},
(request, reply) => credentialController.mint(request, reply)
Expand All @@ -25,6 +34,7 @@ export async function credentialRoutes(app: FastifyInstance): Promise<void> {
schema: {
description: "List user credentials",
tags: ["credentials"],
security: [{ bearerAuth: [] }],
} as FastifySchema,
},
(request, reply) => credentialController.list(request, reply)
Expand Down
9 changes: 8 additions & 1 deletion src/modules/quizzes/ai-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { z } from "zod";
import { config } from "../../config/index.js";
import { logger } from "../../utils/logger.js";
import { createTransientRetryPolicy, createCircuitBreaker } from "../../utils/resilience.js";
import { context, propagation } from "@opentelemetry/api";
import { getRequestId } from "../../utils/request-context.js";

const aiQuizQuestionSchema = z.object({
prompt: z.string(),
Expand Down Expand Up @@ -36,9 +38,14 @@ async function requestQuiz(
const timeout = setTimeout(() => controller.abort(), config.AI_TIMEOUT_MS);

try {
const headers: Record<string, string> = { "Content-Type": "application/json" };
const requestId = getRequestId();
if (requestId) headers["X-Request-ID"] = requestId;
propagation.inject(context.active(), headers);

const response = await fetch(`${config.AI_SERVICE_URL}/generate-quiz`, {
method: "POST",
headers: { "Content-Type": "application/json" },
headers,
body: JSON.stringify({
user_id: params.userId,
course_id: params.courseId,
Expand Down
29 changes: 29 additions & 0 deletions src/modules/quizzes/quiz.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,17 @@ export async function quizRoutes(app: FastifyInstance): Promise<void> {
schema: {
description: "Generate a quiz for a course module",
tags: ["quizzes"],
security: [{ bearerAuth: [] }],
body: {
type: "object",
required: ["courseId", "moduleId"],
properties: {
courseId: { type: "string", format: "uuid" },
moduleId: { type: "string", minLength: 1 },
difficulty: { type: "string", enum: ["beginner", "intermediate", "advanced"] },
numQuestions: { type: "integer", minimum: 1, maximum: 20 },
},
},
} as FastifySchema,
},
(request, reply) => quizController.generate(request, reply)
Expand All @@ -28,6 +39,24 @@ export async function quizRoutes(app: FastifyInstance): Promise<void> {
schema: {
description: "Submit quiz answers",
tags: ["quizzes"],
security: [{ bearerAuth: [] }],
params: { type: "object", required: ["id"], properties: { id: { type: "string", format: "uuid" } } },
body: {
type: "object",
required: ["answers"],
properties: {
answers: {
type: "array", minItems: 1, maxItems: 50,
items: {
type: "object", required: ["questionId", "selectedIndex"],
properties: {
questionId: { type: "string", minLength: 1, maxLength: 100 },
selectedIndex: { type: "integer", minimum: 0, maximum: 20 },
},
},
},
},
},
} as FastifySchema,
},
(request, reply) => quizController.submit(request, reply)
Expand Down
16 changes: 16 additions & 0 deletions src/modules/rewards/reward.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@ export async function rewardRoutes(app: FastifyInstance): Promise<void> {
schema: {
description: "Claim a reward for a passed quiz",
tags: ["rewards"],
security: [{ bearerAuth: [] }],
body: {
type: "object", required: ["submissionId", "idempotencyKey"],
properties: {
submissionId: { type: "string", format: "uuid" },
idempotencyKey: { type: "string", minLength: 16, maxLength: 64 },
},
},
} as FastifySchema,
},
(request, reply) => rewardController.claim(request, reply)
Expand All @@ -28,6 +36,14 @@ export async function rewardRoutes(app: FastifyInstance): Promise<void> {
schema: {
description: "Get reward claim history",
tags: ["rewards"],
security: [{ bearerAuth: [] }],
querystring: {
type: "object",
properties: {
page: { type: "integer", minimum: 1, default: 1 },
limit: { type: "integer", minimum: 1, maximum: 50, default: 20 },
},
},
} as FastifySchema,
},
(request, reply) => rewardController.history(request, reply)
Expand Down
13 changes: 13 additions & 0 deletions src/modules/users/user.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export async function userRoutes(app: FastifyInstance): Promise<void> {
schema: {
description: "Get authenticated user profile",
tags: ["users"],
security: [{ bearerAuth: [] }],
} as FastifySchema,
},
(request, reply) => userController.getMe(request, reply)
Expand All @@ -25,6 +26,17 @@ export async function userRoutes(app: FastifyInstance): Promise<void> {
schema: {
description: "Update authenticated user profile",
tags: ["users"],
security: [{ bearerAuth: [] }],
body: {
type: "object",
properties: {
displayName: { type: "string", minLength: 1, maxLength: 100 },
background: { type: "string", maxLength: 1000 },
learningGoal: { type: "string", maxLength: 500 },
pace: { type: "string", enum: ["slow", "medium", "fast"] },
language: { type: "string", maxLength: 10 },
},
},
} as FastifySchema,
},
(request, reply) => userController.updateMe(request, reply)
Expand All @@ -36,6 +48,7 @@ export async function userRoutes(app: FastifyInstance): Promise<void> {
schema: {
description: "Get learning progress stats",
tags: ["users"],
security: [{ bearerAuth: [] }],
} as FastifySchema,
},
(request, reply) => userController.getProgress(request, reply)
Expand Down
36 changes: 35 additions & 1 deletion src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import cors from "@fastify/cors";
import helmet from "@fastify/helmet";
import jwt from "@fastify/jwt";
import rateLimit from "@fastify/rate-limit";
import swagger from "@fastify/swagger";
import swaggerUi from "@fastify/swagger-ui";
import { sql } from "drizzle-orm";
import { config } from "./config/index.js";
import { logger } from "./utils/logger.js";
Expand Down Expand Up @@ -32,6 +34,7 @@ import {
} from "./jobs/reconcile-pending-rewards.js";
import { processRewardClaim } from "./modules/rewards/reward.service.js";
import { warmCourseCache } from "./cache/warmer.js";
import { runWithRequestContext } from "./utils/request-context.js";

// Versioned route modules
import { registerVersionedRoutes } from "./routes/versioning.js";
Expand Down Expand Up @@ -75,6 +78,35 @@ async function buildApp() {
genReqId: () => crypto.randomUUID(),
});

app.addHook("onRequest", (request, _reply, done) => {
runWithRequestContext(request.id, done);
});

await app.register(swagger, {
openapi: {
info: {
title: "ChainLearn API",
description: "API for the ChainLearn Stellar-based learning platform",
version: "1.0.0",
},
components: {
securitySchemes: {
bearerAuth: { type: "http", scheme: "bearer", bearerFormat: "JWT" },
},
},
tags: [
{ name: "auth", description: "SEP-10 authentication" },
{ name: "users", description: "User profile and progress" },
{ name: "courses", description: "Course discovery and enrollment" },
{ name: "quizzes", description: "Quiz generation and submission" },
{ name: "rewards", description: "Learning rewards" },
{ name: "credentials", description: "Course credentials" },
],
},
});

await app.register(swaggerUi, { routePrefix: "/docs" });

// ─── Plugins ────────────────────────────────────────────────────────────

// #220: OWASP security headers via @fastify/helmet.
Expand All @@ -84,7 +116,9 @@ async function buildApp() {
contentSecurityPolicy: {
directives: {
defaultSrc: ["'none'"],
scriptSrc: ["'none'"],
scriptSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:"],
objectSrc: ["'none'"],
frameAncestors: ["'none'"],
},
Expand Down
Loading