Skip to content

Updated All Modules and Added Docker Files - #16

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

azeemstack merged 4 commits into
mainfrom
API-LogicBuilding

Conversation

@azeemstack

@azeemstack azeemstack commented Mar 6, 2026 •

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • New Features

    • Audio asset management (generate, upload, versions, active selection, restore/delete)
    • Scene asset management for images/videos (generate, upload, versions, active selection, restore/delete)
    • Full narration system with AI generation, timing validation, uploads, and versioning
    • Credits & plan-based feature gating with capability overrides
    • File upload handlers and ownership/validation middleware for assets and narrations
  • Chores

    • Docker/dev/prod setup and compose files
    • Added media processing dependency and TypeScript types
    • Updated gitignore and project path aliases
  • Refactor

    • Many services/controllers migrated to transactional flows and unified validation/pagination middleware

@azeemstack azeemstack self-assigned this Mar 6, 2026
Copilot AI review requested due to automatic review settings March 6, 2026 02:08
@azeemstack azeemstack added the enhancement New feature or request label Mar 6, 2026
@coderabbitai

coderabbitai Bot commented Mar 6, 2026 •

Copy link
Copy Markdown

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2e655d26-e66a-4279-9708-57058b55e41d

📥 Commits

Reviewing files that changed from the base of the PR and between 7d4382f and f52d45d.

📒 Files selected for processing (4)
  • src/modules/featurePermission/featurePermission.service.ts
  • src/modules/sceneAssets/sceneAssets.controller.ts
  • src/modules/sceneAssets/sceneAssets.service.ts
  • src/modules/videoConfig/index.ts

📝 Walkthrough

Walkthrough

Adds containerization configs and extensive new media, narration, and video features: models, constants, validators, services, controllers, routes, multer upload handlers, transactional DB helper, feature/credit systems, and many Zod validation schemas; also refactors auth/session flows and several existing models and middleware.

Changes

Cohort / File(s) Summary
Docker & Compose
\.dockerignore, Dockerfile, Dockerfile.dev, docker-compose.dev.yml, docker-compose.prod.yml
Add dev/prod Dockerfiles and compose configs; update .dockerignore to exclude build/VCS artifacts and dist.
Package deps
package.json
Add fluent-ffmpeg and types for video duration probing.
DB transaction helper
src/db/withTransaction.ts
New MongoDB transaction wrapper used by multiple services.
Credit pricing & utilities
src/config/creditPricing.ts, src/utils/getCreditCost.ts
Add CREDIT_PRICING mapping and getter to compute credit cost per action/grade.
Constants
src/constants/* (audioAssetConsts.ts, sceneAssetConsts.ts, videoConfigConsts.ts, globalConts.ts)
Add comprehensive audio/scene/video constants and adjust default dev origin port.
Models: audio/narration/video/credits/plans/capabilities
src/models/... (AudioAsset.ts, Narration.ts, Credits.ts, Plan.ts, CapabilityOverride.ts, FinalVideo.ts, VideoConfig.ts, ContextProfile.ts, SceneAssets.ts, Scene.ts, Story.ts, Project.ts, User.ts, Session.ts, etc.)
Introduce many new models (Narration, Credits, Plan, CapabilityOverride, VideoConfig); extend/refactor existing models (AudioAsset, SceneAsset, ContextProfile, Story, Project, User, FinalVideo) with versioning, soft-delete, refs, and indexes. Remove ContextProfileHistory.
Audio subsystem
src/modules/audio/*, src/modules/audio/audio.routes.ts
New audio service/controllers/routes: generation, regeneration, upload, active asset management, bulk soft/permanent delete/restore, transactional handling and ownership validation.
Narration subsystem
src/modules/narration/*, src/validation/narration.schema.ts
New narration model, service, controllers, routes, file/JSON upload handling, segment/timing validation, and AI integration scaffolding.
Scene assets subsystem
src/modules/sceneAssets/*, src/validation/sceneAssets.schema.ts
New scene asset services/controllers/routes/validation: generate/upload image/video, activation, bulk operations, versioning, soft/permanent delete, transactional flows and permission/credit checks.
Video config framework (scaffolded)
src/modules/videoConfig/*, src/validation/videoConfig.schema.ts
Add extensive video config model, validation schemas and commented controller/service/route scaffolding (non-executable).
Feature & credit services
src/modules/featurePermission/*, src/modules/credit/credit.service.ts
Add capability resolution utilities, assertFeaturePermission, getAvailableCredits and consumeCredits with expiry-aware consumption.
Auth/session refactor & helpers
src/modules/auth/*, src/modules/auth/utils/*
Refactor auth flows to use withTransaction, add createSessionPayload and createUsername utilities, replace createUserSession removal.
Subscription
src/modules/subscription/subscription.service.ts
Add assignFreePlan to provision free plan and initial credits within a transaction.
Context profiles
src/modules/contextProfile/*
Add creation controller/service with project/global scope logic and transactional project default handling.
Domain assertions & policies
src/domain/assertions/*, src/domain/policies/*
Add many assertion helpers (asset, audio, scene, narration, story, character/timing fits) and model resolution policy for AI modes/plans.
Middleware & multer reorganized
src/middleware/multer/..., src/middleware/*
Remove old multer module; add per-type filenameLogic (audio/image/video/json) and upload wrappers (avatar, imageAsset, videoAsset, audioAsset, narrationJSON); move pagination middleware to request namespace; update error/logger middlewares (requestId tracking).
Validators
src/validators/*
Add ownership/validator helpers for user/story/scene/audio/asset/videoConfig.
Utilities & helpers
src/utils/*
Add getVideoDuration (ffprobe), hashSceneOrder, arraysEqual, short helpers, and update paginationResponse and sanitize utilities (user/project sanitizers) with some public response shape changes.
Validation schemas
src/validation/*.ts
Add/update many Zod schemas (audio, narration, sceneAssets, videoConfig, project, story, auth, user) with new input shapes and stricter constraints.
Routing & API wiring
src/routes/api.ts, src/routes/index.ts, src/modules/*/routes.ts
Wire new routers (narration, sceneAssets, audio, scene assets private routes), adjust middleware order, add several new endpoints across story/project/scene/narration/audio subsystems.
TS types & config
src/types/index.ts, src/types/express.d.ts, tsconfig.json
Add StoryContent, Plan, AIMode types; add path aliases for validators/security/domain modules and small type file updates.
Misc: gitignore / postman
.gitignore, .postman/config.json
Add postman dir to .gitignore; delete .postman/config.json.
Removed / commented
src/middleware/multer.ts, src/middleware/avatarUpload.ts (old), src/modules/videoConfig/* (commented), src/modules/auth/utils/createUserSession.ts, src/utils/createUsername.ts, src/models/ContextProfileHistory.ts
Remove or replace legacy helpers/modules; several videoConfig controller/service files are commented out (scaffold only).

Sequence Diagram(s)

sequenceDiagram
  participant Client as Client
  participant API as API Server
  participant Service as Audio/Narration Service
  participant DB as MongoDB
  participant AI as AI Provider
  participant Storage as File Storage

  rect rgba(200, 230, 255, 0.5)
  Client->>API: POST /narrations/:id/generate (or /audio/generate + file)
  API->>Service: validate & authorize request
  Service->>DB: validate ownership (validateNarrationOwnership)
  end

  rect rgba(200, 255, 200, 0.5)
  Service->>AI: send prompt (buildStoryNarrationPrompt / narration prompt)
  AI-->>Service: JSON narration / audio payload
  Service->>DB: withTransaction { create narration/audio asset, increment version, mark active }
  Service->>Storage: upload generated audio/video file (store URL)
  DB-->>Service: commit transaction
  end

  rect rgba(255, 230, 200, 0.5)
  Service-->>API: return created resource (201)
  API-->>Client: 201 Created with resource payload
  end
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

Poem

"I'm a rabbit with a dev-time hop,
I stitch the audio and scenes non-stop,
Narrations hum and videos play,
Credits tumble, assets sway—hip-hop hooray! 🐇🎧🎬"

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch API-LogicBuilding

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 is a broad backend refactor and feature expansion: it introduces new “ownership” validators, adds new modules (narration, scene assets, audio, credits/feature-permissions/plans), refactors routing/middleware paths, and adds Docker artifacts for dev/prod workflows.

Changes:

  • Added new domain modules/models for narration, scene-assets, audio assets, credits, plans, and capability overrides, with supporting validators and Zod schemas.
  • Refactored routes and middleware structure (notably pagination/sorting and upload middleware) and updated multiple response sanitizers.
  • Added Dockerfiles + compose configs and adjusted build/runtime setup.

Reviewed changes

Copilot reviewed 134 out of 141 changed files in this pull request and generated 10 comments.

Show a summary per file
File Description
tsconfig.json Adds new TS path aliases (@validators, @security, @domain).
src/validators/validateVideoConfigOwnership.ts New helper to load a VideoConfig and enforce user ownership.
src/validators/validateUser.ts New helper to validate user existence (optional session support).
src/validators/validateStoryOwnership.ts New helper to ensure story belongs to user.
src/validators/validateSceneOwnership.ts New helpers to validate scene ownership (including story-scoped lookup).
src/validators/validateNarrationOwnership.ts New helper to validate narration ownership.
src/validators/validateAudioAssetOwnership.ts New helper to validate audio asset ownership.
src/validators/validateAssetOwnership.ts New helper to validate scene-asset ownership.
src/validation/user.schema.ts Minor schema cleanup/formatting.
src/validation/story.schema.ts Expanded story schemas (context typing, status, richer context payload).
src/validation/sceneAssets.schema.ts New validation schemas for scene assets CRUD/bulk operations.
src/validation/project.schema.ts Reformats + updates context-profile discriminated union and enums.
src/validation/narration.schema.ts New validation schemas for narration operations and segments.
src/validation/auth.schema.ts Reformats and adjusts auth validation fields/messages.
src/validation/audio.schema.ts New validation schemas for audio asset operations.
src/utils/sanitizeUserResponse.ts Renames/updates user response sanitizer and plan field mapping.
src/utils/sanitizeProjectResponse.ts Updates project response sanitizer fields (adds defaultContextProfileId).
src/utils/paginationResponse.ts Adjusts pagination response shape (total field).
src/utils/hashSceneOrder.ts Adds hashing helpers for scene order integrity.
src/utils/getVideoDuration.ts Adds ffprobe-based video duration extraction utility.
src/utils/getIpInfo.ts Changes IP info response structure (success wrapper + error logging).
src/utils/getCreditCost.ts Adds utility to compute credit costs from config.
src/utils/createUsername.ts Removes old username generator utility (moved under auth utils).
src/utils/buildSessionMetadata.ts (No diff shown) placeholder/relocation context.
src/utils/arraysEqual.ts Adds small array equality helper.
src/types/index.ts Adds shared types (StoryContent, Plan, AIMode).
src/types/express.d.ts Updates Express Request typings and pagination import path.
src/security/guards/getAccountBlockResponse.ts Updates import path to domain policy.
src/routes/index.ts Reformats router setup and middleware ordering.
src/routes/api.ts Registers new routers for narrations and assets.
src/modules/videoConfig/videoConfig.routes.ts Adds (currently commented) videoConfig routes scaffold.
src/modules/videoConfig/index.ts Adds module index exports for videoConfig.
src/modules/user/user.routes.ts Updates avatar upload import path (multer refactor).
src/modules/user/user.controller.ts Updates user plan field to currentPlan.
src/modules/subscription/subscription.service.ts Adds free plan assignment + credit grant creation in transaction.
src/modules/story/story.private.routes.ts Expands story routes (deleted/archived lists, soft/permanent delete).
src/modules/scenes/scenes.private.routes.ts Expands scene routes (inactive/deleted, bulk deletes, deactivate/reactivate).
src/modules/scenes/scenes.controller.ts Adds controllers for inactive/deleted/bulk deletion + permanent deletion.
src/modules/sceneAssets/sceneAssets.private.routes.ts Adds private routes for scene assets (bulk ops, uploads, generation).
src/modules/sceneAssets/sceneAssets.controller.ts Adds scene asset controllers (list/count/upload/delete/restore/generate).
src/modules/project/utils/transitionProjectById.ts Adds rule preventing activation without default context profile.
src/modules/project/utils/transitionManyProjectsByIds.ts Updates bulk transition logic to allow multiple from-states.
src/modules/project/rules/projectStatus.ts Refactors status constants/types and allowed transitions.
src/modules/project/project.routes.ts Adds many new project bulk/status routes and permanent delete endpoints.
src/modules/narration/narration.routes.ts Adds narration routes for story-scoped operations and uploads.
src/modules/narration/narration.controller.ts Adds narration controllers for CRUD + generation + uploads + activation.
src/modules/narration/narration.constants.ts Adds narration constants.
src/modules/featurePermission/utils/resolveEffectiveCapabilities.ts Adds capability resolution merging plan caps + overrides.
src/modules/featurePermission/featurePermission.service.ts Adds permission assertion logic for actions/grades.
src/modules/credit/credit.service.ts Adds credit availability + consumption logic within a transaction.
src/modules/contextProfile/contextProfile.service.ts Adds transactional context-profile creation w/ project default handling.
src/modules/contextProfile/contextProfile.routes.ts Enables context profile creation route + wraps handlers in asyncHandler.
src/modules/contextProfile/contextProfile.controller.ts Adds create controller and uses validated body types.
src/modules/auth/utils/createUsername.ts Reintroduces username generator under auth utils with session support.
src/modules/auth/utils/createUserSession.ts Removes old session creation helper (replaced by payload builder).
src/modules/auth/utils/createSessionPayload.ts Adds new session payload builder using getIpInfo success wrapper.
src/modules/auth/auth.routes.ts Reformats auth routes and adds refresh endpoint formatting.
src/modules/auth/auth.controller.ts Refactors cookie handling and refresh-token error behavior.
src/modules/audio/audio.routes.ts Adds audio asset routes for narration-scoped + single-asset ops.
src/modules/audio/audio.constants.ts Adds audio generation/provider/constants configuration.
src/models/User.ts Refactors user plan representation (currentPlan ref) + enums/formatting.
src/models/Story.ts Updates Story schema (content authorType, required contextProfileId, versioning).
src/models/Session.ts Updates TTL durations + formatting.
src/models/SceneAssets.ts Refactors SceneAsset schema (sceneId ref, versioning, TTL for deletedAt).
src/models/Scene.ts Adds narrativeRole, active flag, activeAssetId ref, and soft-delete semantics.
src/models/Project.ts Adds thumbnail field and formats schema/enums.
src/models/Plan.ts Adds Plan model with capabilities + credit grant configuration.
src/models/Narration.ts Adds StoryNarration model with segments, hashes, TTL, and indexes.
src/models/FinalVideo.ts Refactors FinalVideo schema (adds videoConfigId, removes renderConfig).
src/models/Credits.ts Adds Credits model with grant/usage and indexes.
src/models/ContextProfileHistory.ts Removes ContextProfileHistory model.
src/models/CapabilityOverride.ts Adds user capability override model with validity windows.
src/models/AudioAsset.ts Refactors AudioAsset schema for narration association/versioning/soft delete.
src/middleware/security/requireCsrf.ts Refactors CSRF enforcement logic and origin validation.
src/middleware/requireActiveAccountFresh.ts (No diff shown) placeholder/relocation context.
src/middleware/request/paginationAndSorting.ts Adds new pagination/sorting middleware under middleware/request.
src/middleware/paginationAndSorting.ts Removes old pagination/sorting middleware file.
src/middleware/multer/videoAssetUpload.ts Adds video upload middleware with Multer error mapping.
src/middleware/multer/narrationJSONUpload.ts Adds narration JSON upload middleware with Multer error mapping.
src/middleware/multer/imageAssetUpload.ts Adds image upload middleware with Multer error mapping.
src/middleware/multer/filenameLogic/multerVideo.ts Adds disk storage + validation rules for video uploads.
src/middleware/multer/filenameLogic/multerJSON.ts Adds disk storage + validation rules for JSON uploads.
src/middleware/multer/filenameLogic/multerImage.ts Adds disk storage + validation rules for image uploads.
src/middleware/multer/filenameLogic/multerAudio.ts Adds disk storage + validation rules for audio uploads.
src/middleware/multer/avatarUpload.ts Adds avatar upload middleware (image-based).
src/middleware/multer/audioAssetUpload.ts Adds audio upload middleware with Multer error mapping.
src/middleware/multer.ts Removes old shared multer config.
src/middleware/loggerMiddleware.ts Refactors request logger (requestId in res.locals, formatting).
src/middleware/error/index.ts Reformats error classes and string literals.
src/middleware/error/globalErrorHandler.ts Refactors error logging payload and requestId inclusion.
src/middleware/avatarUpload.ts Removes old avatar upload middleware (replaced by multer module).
src/libs/ai/prompts/utils/buildStoryContextSection.ts Removes old context section builder.
src/libs/ai/prompts/utils/buildContextSection.ts Adds new unified context section builder for prompts.
src/libs/ai/prompts/singleScenePrompt.ts Updates to use new context builder + shared StoryContent type.
src/libs/ai/prompts/narrationPrompt.ts Adds full-story narration prompt builder.
src/libs/ai/prompts/generateStoryRegenerationPrompt.ts Uses new context builder and reformats word-limit calculation.
src/libs/ai/prompts/generateStoryPrompt.ts Uses new context builder and reformats word-limit calculation.
src/libs/ai/prompts/batchScenesPrompt.ts Uses new context builder + shared StoryContent type and formatting.
src/libs/ai/policies/resolveModel.ts Adds plan-based model/provider resolution policy.
src/libs/ai/constants/narrationPromptConsts.ts Adds strict JSON output format constant for narration.
src/libs/ai/clients/openAI.ts Refactors OpenRouter request formatting and error handling.
src/domain/policies/isSameContextContract.ts Adds context equality contract helper.
src/domain/policies/accountStatusResponses.ts Adds policy mapping account statuses to responses.
src/domain/assertions/assertStoryState.ts Adds story state assertions (deleted/archived/etc).
src/domain/assertions/assertSceneState.ts Adds scene state assertions (deleted/active/inactive).
src/domain/assertions/assertNarrationState.ts Adds narration state assertions.
src/domain/assertions/assertNarrationFitsTime.ts Adds narration timing assertion helper.
src/domain/assertions/assertCharacterFits.ts Adds narration character validation against context profile.
src/domain/assertions/assertAudioAssetState.ts Adds audio asset state assertions.
src/domain/assertions/assertAssetState.ts Adds scene asset state assertions.
src/db/withTransaction.ts Adds transaction helper wrapper.
src/constants/videoConfigConsts.ts Adds video config constants and error messages.
src/constants/sceneAssetConsts.ts Adds scene asset validation constants/types.
src/constants/globalConts.ts Updates dev client default URL/port.
src/constants/audioAssetConsts.ts Adds audio asset validation constants/types.
src/config/creditPricing.ts Adds action pricing matrix and ActionType type.
package.json Adds fluent-ffmpeg and types; updates dependency set accordingly.
package-lock.json Locks new dependencies including fluent-ffmpeg and transitive deps.
docker-compose.prod.yml Adds prod compose config for backend service.
docker-compose.dev.yml Adds dev compose config with bind mounts and dev command.
Dockerfile.dev Adds dev Dockerfile for running npm run dev.
Dockerfile Updates production Dockerfile to build + run compiled output.
.postman/config.json Removes Postman workspace config from repo.
.gitignore Adds postman ignore entry and keeps temp dirs ignored.
.dockerignore Expands ignore list and orders entries (includes dist, Docker files).

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +82 to +87
router.post(
'/:sceneId/permanent-bulk-delete',
validateParams(sceneIdParamSchema),
validateBody(bulkDeleteAssetsSchema),
asyncHandler(permanentDeleteAllAssetsController)
);

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 /:sceneId/permanent-bulk-delete route is wired to permanentDeleteAllAssetsController, which will delete all assets for the scene rather than only the requested assetIds. This looks like a copy/paste mistake—use the permanentBulkDeleteAssetsController here.

Copilot uses AI. Check for mistakes.
Comment thread Dockerfile
Comment on lines 5 to +12
COPY package*.json ./
RUN npm ci

# If you prefer nodemon global: RUN npm install -g nodemon
# Copy only when building image layer for deps (source will be mounted at runtime)
# Expose the port your app uses
RUN npm ci --only=production

COPY . .

RUN npm run build

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.

This Dockerfile installs production-only dependencies (npm ci --only=production) and then runs npm run build, but build uses tsc which is in devDependencies. The image build will fail unless TypeScript is installed. Consider a multi-stage build (install dev deps to build, then copy compiled output + prod deps), or install dev deps during the build stage.

Copilot uses AI. Check for mistakes.
Comment thread Dockerfile
EXPOSE 4000

CMD ["npm", "run", "dev"]
CMD ["node", "dist/server.js"] No newline at end of file

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 container entrypoint runs node dist/server.js, but tsconfig.json currently emits to src/dist (outDir: "src/dist"). Unless artifacts are moved as part of the build, the container will fail at startup. Either change outDir to dist or update the Docker CMD/start script to match the emitted path.

Suggested change
CMD ["node", "dist/server.js"]
CMD ["node", "src/dist/server.js"]

Copilot uses AI. Check for mistakes.
Comment on lines +28 to +29
const minWords = Math.floor(baseWords + profile.minWordTolerance);
const maxWords = Math.ceil(baseWords + profile.maxWordTolerance);

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 tolerance math is incorrect: minWordTolerance/maxWordTolerance are treated as additive constants (baseWords + tolerance) rather than multiplicative factors (e.g., baseWords * 0.9). With the current code, a 0.9 tolerance only shifts the bound by <1 word regardless of duration. Compute bounds using multiplication (or rename the fields if they’re intended to be absolute word deltas).

Suggested change
const minWords = Math.floor(baseWords + profile.minWordTolerance);
const maxWords = Math.ceil(baseWords + profile.maxWordTolerance);
const minWords = Math.floor(baseWords * profile.minWordTolerance);
const maxWords = Math.ceil(baseWords * profile.maxWordTolerance);

Copilot uses AI. Check for mistakes.
Comment on lines +69 to +74
router.get('/:storyId', validateParams(storyIdParamSchema), asyncHandler(getStoryByIdController));
router.post(
'/:storyId/context-profile',
validateBody(addStoryContextSchema),
asyncHandler(addStoryContextController)
);

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.

POST /:storyId/context-profile uses req.params.storyId in the controller but doesn’t validate the storyId route param (unlike most other story routes). Add validateParams(storyIdParamSchema) to this route to avoid passing malformed IDs into downstream DB queries.

Copilot uses AI. Check for mistakes.
Comment on lines +196 to +199
export const generateImageAssetController = async (req: Request, res: Response) => {
const userId = req.user!.id;
const { sceneId } = req.params;
};

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.

generateImageAssetController is currently a no-op (it reads params but never calls a service or sends a response). Hitting this endpoint will hang until Express times out. Implement the controller (and import the corresponding service function) or remove/disable the route until it’s ready.

Copilot uses AI. Check for mistakes.
Comment on lines +10 to +13
if (err instanceof multer.MulterError) {
if (err.code === 'LIMIT_FILE_SIZE') {
return next(new PayloadTooLargeError('Video file size exceeds the 50MB 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 the video limit is 50MB, but the configured multer limit is 20MB (limits.fileSize in multerVideo). This will confuse clients when uploads fail. Either raise the limit to 50MB or update the error message to reflect the actual configured limit.

Copilot uses AI. Check for mistakes.
Comment on lines +10 to +13
if (err instanceof multer.MulterError) {
if (err.code === 'LIMIT_FILE_SIZE') {
return next(new PayloadTooLargeError('Audio file size exceeds the 100MB 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 the audio limit is 100MB, but the configured multer limit is 10MB (limits.fileSize in multerAudio). This will confuse clients when uploads fail. Either raise the limit to 100MB or update the error message to the actual limit.

Copilot uses AI. Check for mistakes.
Comment on lines +1 to +9
import { InternalServerError } from '@middleware/error/index.js';
import ffmpeg from 'fluent-ffmpeg';

export function getVideoDuration(filePath: string): Promise<number> {
return new Promise((resolve, reject) => {
ffmpeg.ffprobe(filePath, (err, metadata) => {
if (err) {
return reject(new InternalServerError('FFPROBE_FAILED'));
}

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.

This utility relies on ffmpeg.ffprobe, which requires the ffprobe binary to be present in the runtime environment. The current node:20-alpine Docker image does not install ffmpeg/ffprobe, so this will fail in containers unless additional OS packages are added. Either install ffmpeg in the image (e.g., apk add --no-cache ffmpeg) or switch to a pure-JS metadata reader that doesn’t depend on external binaries.

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

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.

req.headers.Origin is not a valid/standard Express header key (Node normalizes header names to lowercase). This makes origin always undefined and effectively disables the origin allowlist check for unsafe methods. Use req.headers.origin (and optionally fall back to req.get('origin')) to enforce the check reliably.

Copilot uses AI. Check for mistakes.
@azeemstack
azeemstack merged commit e3c2ad4 into main Mar 6, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants