Repository navigation
setup deploy pipeline - #17
Conversation
…into API-LogicBuilding
…ndling) #6, Added a new custom Error
…into API-LogicBuilding To Resollve Conflicts at: src/middleware/error/AppError.ts
Audit & Improve User Routes (Profile Updates, Avatar Upload, Error Handling) Close #6
…e core data models for story-centric AI generation #8
Finalize core data models for story-centric AI generation
Add full Project module with state transitions, bulk operations, pagination, and security improvements
…ions + AI related code added
Added Story Module + Improve Some Auth and Modeling + DRY implementat…
Add scenes module and fix some Context, Auth, User, Project module th…
…into API-LogicBuilding
|
Important Review skippedToo many files! This PR contains 181 files, which is 31 over the limit of 150. ⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (181)
You can disable this status message by setting the Use the checkbox below for a quick retry:
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Pull request overview
This PR sets up a deploy pipeline and significantly expands the backend application. Beyond the CI/CD infrastructure (Dockerfile, GitHub Actions, Docker Compose), it introduces many new features including project management, story generation, scene management, narration, audio/video assets, credit system, and feature permissions. It also refactors existing auth, validation, error handling, and logging.
Changes:
- Added CI/CD deployment pipeline (Dockerfile, GitHub Actions workflow deploying to AWS ECR/EC2, Docker Compose for dev/prod)
- Major application expansion: new modules (projects, stories, scenes, narrations, audio assets, scene assets, video config, credits, subscriptions, context profiles), models, validators, middleware (CSRF, active account check, file uploads, pagination), and AI prompt infrastructure
- Refactored auth middleware to JWT-only validation (no DB session check), moved validation helpers to separate files, replaced console logging with structured pino logger, and updated error handling with new
actionsfield
Reviewed changes
Copilot reviewed 171 out of 182 changed files in this pull request and generated 23 comments.
Show a summary per file
| File | Description |
|---|---|
.github/workflows/deploy.yml |
New GitHub Actions pipeline deploying Docker image to AWS ECR/EC2 |
Dockerfile / Dockerfile.dev |
Multi-stage production build and dev container |
docker-compose.*.yml |
Dev and prod Docker Compose configs |
tsconfig.json |
Changed outDir and added path aliases; includes dist (problematic) |
package.json |
Added multer, pino, fluent-ffmpeg dependencies |
src/routes/api.ts / index.ts |
Restructured routing with new middleware chain and modules |
src/middleware/auth/requireAuth.ts |
Simplified to JWT-only verification (removed DB session check) |
src/middleware/security/* |
New CSRF and active account middleware |
src/middleware/error/* |
Added PayloadTooLargeError, actions field to AppError |
src/middleware/multer/* |
New file upload middleware for images, video, audio, JSON |
src/middleware/loggerMiddleware.ts |
Replaced dev console logger with pino structured logging |
src/validation/*.ts |
New Zod schemas for all domains; refactored validateBody/validateParams |
src/validators/*.ts |
Ownership validators for stories, scenes, assets, narrations |
src/models/*.ts |
New models: Project, Story, Scene, Narration, SceneAssets, AudioAsset, Plan, Credits, etc. |
src/modules/** |
New route/controller/service files for projects, stories, scenes, narrations, audio, context profiles |
src/utils/* |
New utilities: logger, pagination, tokens, email templates, etc. |
src/libs/ai/* |
AI prompt builders for story, scene, narration generation |
src/domain/* |
Domain assertions and policies |
src/libs/aws/s3.ts |
S3 client setup (contains hardcoded credentials and debug code) |
src/config/creditPricing.ts |
Credit pricing configuration for AI actions |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| return { success: true, ...data }; | ||
| } catch (e) { | ||
| return { city: "Unknown", country: "Unknown" }; | ||
| console.error('Error fetching IP info:', e); |
There was a problem hiding this comment.
The getIpInfo function uses console.error for logging on line 31, while the rest of the codebase has migrated to using logger from @utils/logger.js. This should use logger.error for consistency with the structured logging approach.
| export const authMiddleware = async ( | ||
| req: Request, | ||
| res: Response, | ||
| next: NextFunction | ||
| ) => { | ||
| try { | ||
| const accessToken = req.cookies["access-token"]; | ||
| const accessToken = req.cookies["access-token"]; | ||
|
|
||
| if (!accessToken) { | ||
| throw new UnauthenticatedError("user not authenticated, no access token found"); | ||
| throw new UnauthenticatedError("Authentication required"); | ||
| } | ||
|
|
||
| let decoded; | ||
| try { | ||
| decoded = jwt.verify(accessToken, process.env.ACCESS_TOKEN_SECRET!) as { | ||
| userId: string; | ||
| sessionId: string; | ||
| role:"user"|"admin"; | ||
| accountStatus?:AccountStatus; | ||
| }; | ||
| } catch (err) { | ||
| throw new UnauthenticatedError("Invalid or expired token"); | ||
| throw new UnauthenticatedError("Authentication required"); | ||
| } | ||
|
|
||
| // find user with this session | ||
| const user = await UserModel.findOne({ | ||
| _id: decoded.userId, | ||
| }); | ||
|
|
||
| if (!user) { | ||
| throw new NotFoundError("User not found"); | ||
| } | ||
|
|
||
| const session = await SessionModel.findOne({ | ||
| sessionId: decoded.sessionId, | ||
| userId: decoded.userId, | ||
| }); | ||
|
|
||
| if (!session || session.revokedAt) { | ||
| throw new UnauthenticatedError("Session revoked or not found"); | ||
| } | ||
|
|
||
| // ✅ update lastUsedAt for this session | ||
| const now = Date.now(); | ||
| const last = session.lastUsedAt?.getTime() ?? 0; | ||
| // Update only if old enough (e.g., 5 minutes) | ||
| if (now - last > 5 * 60 * 1000) { | ||
| session.lastUsedAt = new Date(); | ||
| await session.save(); | ||
| } | ||
|
|
||
|
|
||
| // attach user + sessionId to request | ||
| req.user = user; | ||
| req.sessionId = decoded.sessionId; | ||
| req.user = { id: decoded.userId, role: decoded.role, accountStatus: decoded.accountStatus }; | ||
| req.sessionId = decoded.sessionId; |
There was a problem hiding this comment.
The auth middleware no longer validates the session against the database (checking if it's revoked, valid, etc.) or updates lastUsedAt. This means a revoked session's access token will continue to work until it expires. The old code performed session validation on every request. While this may be an intentional performance trade-off (pushing session validation to the CSRF middleware), it significantly weakens security since GET requests bypass CSRF checks and will never have their sessions validated.
| @@ -0,0 +1,36 @@ | |||
| import transporter from "config/mail.js"; | |||
| import { verifyUpdatedEmailTemplate } from "../templates/verifyUpdatedEmail.js"; | |||
| import { InternalServerError } from "@middleware/error/index.js"; | |||
There was a problem hiding this comment.
The InternalServerError is imported but never used in sendUpdateEmailLink.ts. It should be removed.
| reduceTime: boolean = false | ||
| ) { |
There was a problem hiding this comment.
The reduceTime parameter is declared but never used inside the function body. This is dead code that should be removed or implemented.
| export const validateBody = | ||
| <T>(schema: ZodSchema<T>): RequestHandler => | ||
| (req, res, next) => { | ||
| const result = schema.safeParse(req.body); | ||
|
|
||
| if (!result.success) { | ||
| return res.status(422).json({ | ||
| error: "validation_error", | ||
| issues: result.error.flatten(), | ||
| }); | ||
| } | ||
|
|
||
| req.validatedBody = result.data; | ||
| next(); | ||
| }; |
There was a problem hiding this comment.
The validateBody middleware returns a 422 status with error: "validation_error" and uses schema.safeParse, while validateParams returns a 400 status with error: "validation_error" and uses schema.parseAsync. The response shapes are also different (issues vs details). These should be consistent in their error response format for a predictable API.
| const origin = req.headers.Origin; | ||
| if (origin && (origin === 'null' || !ALLOWED_ORIGINS.includes(origin as string))) { |
There was a problem hiding this comment.
The Origin header is accessed with a capital "O" (req.headers.Origin), but HTTP headers in Express/Node.js are normalized to lowercase. This should be req.headers.origin. As a result, the origin check will never match, effectively bypassing this security validation.
| export function generateCsrfToken() { | ||
| const token = crypto.randomBytes(24).toString("hex"); | ||
| const signed = crypto | ||
| .createHmac("sha256", process.env.CSRF_SECRET!) | ||
| .update(token) | ||
| .digest("hex"); | ||
| return `${token}.${signed}`; | ||
| const token = crypto.randomBytes(24).toString("hex"); | ||
| return token; | ||
| } |
There was a problem hiding this comment.
The CSRF token generation now returns a plain random hex string without any HMAC signature. The old implementation used token.signature which allowed the server to verify token integrity without a database lookup. The new implementation relies on verifyToken (which does a timing-safe hash comparison against the session's stored csrfTokenHash), but the CSRF token is sent via a header (not a cookie), so it's compared against the session DB record. While this can work, it means every mutating request triggers a DB query to verify CSRF — consider whether this performance trade-off is intentional.
| message: string, | ||
| statusCode: number, | ||
| code: string, | ||
| actions?: { | ||
| reason: string; | ||
| nextStep: string; | ||
| }, | ||
| details?: any | ||
| ) { |
There was a problem hiding this comment.
The AppError constructor signature has changed: the new parameter order is (message, statusCode, code, actions?, details?), but all existing subclasses in src/middleware/error/index.ts still call super(message, statusCode, errorCode, details) — passing details in the position of the new actions parameter. This means details will be assigned to this.actions instead of this.details, and this.details will always be undefined. All error subclass constructors need to be updated to pass undefined for actions before details, e.g., super(message, 400, ERROR_CODES.BAD_REQUEST, undefined, details).
|
|
||
| if (err instanceof multer.MulterError) { | ||
| if (err.code === 'LIMIT_FILE_SIZE') { | ||
| return next(new PayloadTooLargeError('Avatar file size exceeds the 2MB limit', err)); |
There was a problem hiding this comment.
The error message says "Avatar file size exceeds the 2MB limit" but this is the imageAssetUpload middleware for scene images, not avatars. The error message should say something like "Image file size exceeds the 2MB limit".
| return res.status(err.statusCode).json(err.serialize()); | ||
| } | ||
|
|
||
| console.log(err); |
There was a problem hiding this comment.
The console.log(err) on line 24 is redundant when logger.error is called immediately after on line 25. The structured logger already handles error output. This console.log should be removed to avoid duplicate unstructured output in production.
No description provided.