Skip to content

setup deploy pipeline - #17

Merged
azeemstack merged 22 commits into
mainfrom
API-LogicBuilding
Mar 6, 2026
Merged

azeemstack merged 22 commits into
mainfrom
API-LogicBuilding

Conversation

@azeemstack

Copy link
Copy Markdown
Owner

No description provided.

…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
Added Story Module + Improve Some Auth and Modeling + DRY implementat…
Add scenes module and fix some Context, Auth, User, Project module th…
Copilot AI review requested due to automatic review settings March 6, 2026 03:15
@coderabbitai

coderabbitai Bot commented Mar 6, 2026

Copy link
Copy Markdown

Important

Review skipped

Too many files!

This PR contains 181 files, which is 31 over the limit of 150.

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: eea6bc1a-0059-44a2-987c-803970dc0176

📥 Commits

Reviewing files that changed from the base of the PR and between a1173e1 and 481be9b.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (181)
  • .dockerignore
  • .github/workflows/deploy.yml
  • .gitignore
  • Dockerfile
  • Dockerfile.dev
  • docker-compose.dev.yml
  • docker-compose.prod.yml
  • example.env
  • package.json
  • src/config/corsConfig.ts
  • src/config/creditPricing.ts
  • src/constants/accountStatus.ts
  • src/constants/audioAssetConsts.ts
  • src/constants/authConsts.ts
  • src/constants/globalConts.ts
  • src/constants/narrationProfiles.ts
  • src/constants/sceneAssetConsts.ts
  • src/constants/sceneConsts.ts
  • src/constants/storyConsts.ts
  • src/constants/userConsts.ts
  • src/constants/videoConfigConsts.ts
  • src/db/connect.ts
  • src/db/withTransaction.ts
  • src/domain/assertions/assertAssetState.ts
  • src/domain/assertions/assertAudioAssetState.ts
  • src/domain/assertions/assertCharacterFits.ts
  • src/domain/assertions/assertNarrationFitsTime.ts
  • src/domain/assertions/assertNarrationState.ts
  • src/domain/assertions/assertSceneState.ts
  • src/domain/assertions/assertStoryState.ts
  • src/domain/policies/accountStatusResponses.ts
  • src/domain/policies/isSameContextContract.ts
  • src/libs/ai/clients/openAI.ts
  • src/libs/ai/constants/calculateWordLimits.ts
  • src/libs/ai/constants/globalSafetyRules.ts
  • src/libs/ai/constants/narrationPromptConsts.ts
  • src/libs/ai/constants/sceneAssetsPromptConts.ts
  • src/libs/ai/constants/scenesPromptConts.ts
  • src/libs/ai/constants/storyPromptConts.ts
  • src/libs/ai/policies/resolveModel.ts
  • src/libs/ai/prompts/batchScenesPrompt.ts
  • src/libs/ai/prompts/generateStoryPrompt.ts
  • src/libs/ai/prompts/generateStoryRegenerationPrompt.ts
  • src/libs/ai/prompts/narrationPrompt.ts
  • src/libs/ai/prompts/singleScenePrompt.ts
  • src/libs/ai/prompts/utils/buildContextSection.ts
  • src/libs/ai/utils/costEstimator.ts
  • src/libs/ai/utils/tokenCounter.ts
  • src/libs/aws/s3.ts
  • src/middleware/auth/requireAuth.ts
  • src/middleware/auth/requireCsrf.ts
  • src/middleware/auth/roles.ts
  • src/middleware/error/appError.ts
  • src/middleware/error/errorCodes.ts
  • src/middleware/error/globalErrorHandler.ts
  • src/middleware/error/index.ts
  • src/middleware/loggerMiddleware.ts
  • src/middleware/multer/audioAssetUpload.ts
  • src/middleware/multer/avatarUpload.ts
  • src/middleware/multer/filenameLogic/multerAudio.ts
  • src/middleware/multer/filenameLogic/multerImage.ts
  • src/middleware/multer/filenameLogic/multerJSON.ts
  • src/middleware/multer/filenameLogic/multerVideo.ts
  • src/middleware/multer/imageAssetUpload.ts
  • src/middleware/multer/narrationJSONUpload.ts
  • src/middleware/multer/videoAssetUpload.ts
  • src/middleware/request/paginationAndSorting.ts
  • src/middleware/security/requireActiveAccount.ts
  • src/middleware/security/requireCsrf.ts
  • src/models/AudioAsset.ts
  • src/models/Bookmark.ts
  • src/models/CapabilityOverride.ts
  • src/models/ContextProfile.ts
  • src/models/Credits.ts
  • src/models/FinalVideo.ts
  • src/models/Narration.ts
  • src/models/Plan.ts
  • src/models/Project.ts
  • src/models/Scene.ts
  • src/models/SceneAssets.ts
  • src/models/Session.ts
  • src/models/Story.ts
  • src/models/User.ts
  • src/models/VideoConfig.ts
  • src/modules/audio/audio.constants.ts
  • src/modules/audio/audio.controller.ts
  • src/modules/audio/audio.routes.ts
  • src/modules/audio/audio.service.ts
  • src/modules/auth/auth.controller.ts
  • src/modules/auth/auth.routes.ts
  • src/modules/auth/auth.service.ts
  • src/modules/auth/utils/createSessionPayload.ts
  • src/modules/auth/utils/createUsername.ts
  • src/modules/contextProfile/contextProfile.controller.ts
  • src/modules/contextProfile/contextProfile.routes.ts
  • src/modules/contextProfile/contextProfile.service.ts
  • src/modules/credit/credit.service.ts
  • src/modules/featurePermission/featurePermission.service.ts
  • src/modules/featurePermission/utils/resolveEffectiveCapabilities.ts
  • src/modules/narration/narration.constants.ts
  • src/modules/narration/narration.controller.ts
  • src/modules/narration/narration.routes.ts
  • src/modules/narration/narration.service.ts
  • src/modules/project/project.controller.ts
  • src/modules/project/project.routes.ts
  • src/modules/project/project.service.ts
  • src/modules/project/rules/projectStatus.ts
  • src/modules/project/utils/transitionManyProjectsByIds.ts
  • src/modules/project/utils/transitionProjectById.ts
  • src/modules/sceneAssets/sceneAssets.controller.ts
  • src/modules/sceneAssets/sceneAssets.private.routes.ts
  • src/modules/sceneAssets/sceneAssets.service.ts
  • src/modules/scenes/scenes.controller.ts
  • src/modules/scenes/scenes.private.routes.ts
  • src/modules/scenes/scenes.service.ts
  • src/modules/story/story.controller.ts
  • src/modules/story/story.private.routes.ts
  • src/modules/story/story.service.ts
  • src/modules/subscription/subscription.service.ts
  • src/modules/user/user.controller.ts
  • src/modules/user/user.routes.ts
  • src/modules/user/user.service.ts
  • src/modules/videoConfig/index.ts
  • src/modules/videoConfig/videoConfig.controller.ts
  • src/modules/videoConfig/videoConfig.routes.ts
  • src/modules/videoConfig/videoConfig.service.ts
  • src/routes/api.ts
  • src/routes/index.ts
  • src/security/guards/ensureActiveAccount.ts
  • src/security/guards/getAccountBlockResponse.ts
  • src/server.ts
  • src/types/Context.ts
  • src/types/Pagination.ts
  • src/types/express.d.ts
  • src/types/index.ts
  • src/utils/arraysEqual.ts
  • src/utils/asyncHandler.ts
  • src/utils/createUsername.ts
  • src/utils/emails/sender/sendEmailVerificationLink.ts
  • src/utils/emails/sender/sendOldEmailVerificationForEmailUpdate.ts
  • src/utils/emails/sender/sendPasswordUpdatedEmail.ts
  • src/utils/emails/sender/sendResetLink.ts
  • src/utils/emails/sender/sendUpdateEmailLink.ts
  • src/utils/emails/sender/sendWelcomeEmail.ts
  • src/utils/emails/templates/emailVerification.ts
  • src/utils/emails/templates/newAccount.ts
  • src/utils/emails/templates/passwordChangedNotification.ts
  • src/utils/emails/templates/resetPassword.ts
  • src/utils/emails/templates/verifyOldEmailForEmailUpdate.ts
  • src/utils/emails/templates/verifyUpdatedEmail.ts
  • src/utils/generateAllCookieTokens.ts
  • src/utils/getCreditCost.ts
  • src/utils/getIpInfo.ts
  • src/utils/getVideoDuration.ts
  • src/utils/hashSceneOrder.ts
  • src/utils/logger.ts
  • src/utils/paginationResponse.ts
  • src/utils/safeParseJSON.ts
  • src/utils/sanitizeProjectResponse.ts
  • src/utils/sanitizeUserResponse.ts
  • src/utils/tokens.ts
  • src/validation/audio.schema.ts
  • src/validation/auth.schema.ts
  • src/validation/contextProfile.schema.ts
  • src/validation/narration.schema.ts
  • src/validation/project.schema.ts
  • src/validation/sceneAssets.schema.ts
  • src/validation/scenes.schema.ts
  • src/validation/story.schema.ts
  • src/validation/user.schema.ts
  • src/validation/validateBody.ts
  • src/validation/validateParams.ts
  • src/validation/videoConfig.schema.ts
  • src/validators/validateAssetOwnership.ts
  • src/validators/validateAudioAssetOwnership.ts
  • src/validators/validateNarrationOwnership.ts
  • src/validators/validateSceneOwnership.ts
  • src/validators/validateStoryOwnership.ts
  • src/validators/validateUser.ts
  • src/validators/validateVideoConfigOwnership.ts
  • tsconfig.json

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch API-LogicBuilding

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@azeemstack
azeemstack merged commit 04e8a77 into main Mar 6, 2026
4 checks passed

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 actions field

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.

Comment thread src/utils/getIpInfo.ts
return { success: true, ...data };
} catch (e) {
return { city: "Unknown", country: "Unknown" };
console.error('Error fetching IP info:', e);

Copilot AI Mar 6, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
Comment on lines +7 to +33
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;

Copilot AI Mar 6, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
@@ -0,0 +1,36 @@
import transporter from "config/mail.js";
import { verifyUpdatedEmailTemplate } from "../templates/verifyUpdatedEmail.js";
import { InternalServerError } from "@middleware/error/index.js";

Copilot AI Mar 6, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The InternalServerError is imported but never used in sendUpdateEmailLink.ts. It should be removed.

Copilot uses AI. Check for mistakes.
Comment thread src/utils/tokens.ts
Comment on lines +66 to 67
reduceTime: boolean = false
) {

Copilot AI Mar 6, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reduceTime parameter is declared but never used inside the function body. This is dead code that should be removed or implemented.

Copilot uses AI. Check for mistakes.
Comment on lines +5 to +19
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();
};

Copilot AI Mar 6, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
Comment on lines +13 to +14
const origin = req.headers.Origin;
if (origin && (origin === 'null' || !ALLOWED_ORIGINS.includes(origin as string))) {

Copilot AI Mar 6, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
Comment thread src/utils/tokens.ts
Comment on lines 73 to 76
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;
}

Copilot AI Mar 6, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
Comment on lines 13 to 21
message: string,
statusCode: number,
code: string,
actions?: {
reason: string;
nextStep: string;
},
details?: any
) {

Copilot AI Mar 6, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Copilot uses AI. Check for mistakes.

if (err instanceof multer.MulterError) {
if (err.code === 'LIMIT_FILE_SIZE') {
return next(new PayloadTooLargeError('Avatar file size exceeds the 2MB limit', err));

Copilot AI Mar 6, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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".

Copilot uses AI. Check for mistakes.
return res.status(err.statusCode).json(err.serialize());
}

console.log(err);

Copilot AI Mar 6, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants