Repository navigation
Updated All Modules and Added Docker Files - #16
Conversation
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (4)
📝 WalkthroughWalkthroughAdds 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
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
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related PRs
Poem
✨ Finishing Touches
🧪 Generate unit tests (beta)
|
There was a problem hiding this comment.
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.
| router.post( | ||
| '/:sceneId/permanent-bulk-delete', | ||
| validateParams(sceneIdParamSchema), | ||
| validateBody(bulkDeleteAssetsSchema), | ||
| asyncHandler(permanentDeleteAllAssetsController) | ||
| ); |
There was a problem hiding this comment.
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.
| 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 | ||
|
|
There was a problem hiding this comment.
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.
| EXPOSE 4000 | ||
|
|
||
| CMD ["npm", "run", "dev"] | ||
| CMD ["node", "dist/server.js"] No newline at end of file |
There was a problem hiding this comment.
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.
| CMD ["node", "dist/server.js"] | |
| CMD ["node", "src/dist/server.js"] |
| const minWords = Math.floor(baseWords + profile.minWordTolerance); | ||
| const maxWords = Math.ceil(baseWords + profile.maxWordTolerance); |
There was a problem hiding this comment.
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).
| 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); |
| router.get('/:storyId', validateParams(storyIdParamSchema), asyncHandler(getStoryByIdController)); | ||
| router.post( | ||
| '/:storyId/context-profile', | ||
| validateBody(addStoryContextSchema), | ||
| asyncHandler(addStoryContextController) | ||
| ); |
There was a problem hiding this comment.
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.
| export const generateImageAssetController = async (req: Request, res: Response) => { | ||
| const userId = req.user!.id; | ||
| const { sceneId } = req.params; | ||
| }; |
There was a problem hiding this comment.
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.
| if (err instanceof multer.MulterError) { | ||
| if (err.code === 'LIMIT_FILE_SIZE') { | ||
| return next(new PayloadTooLargeError('Video file size exceeds the 50MB limit', err)); | ||
| } |
There was a problem hiding this comment.
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.
| if (err instanceof multer.MulterError) { | ||
| if (err.code === 'LIMIT_FILE_SIZE') { | ||
| return next(new PayloadTooLargeError('Audio file size exceeds the 100MB limit', err)); | ||
| } |
There was a problem hiding this comment.
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.
| 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')); | ||
| } |
There was a problem hiding this comment.
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.
| const origin = req.headers.Origin; | ||
| if (origin && (origin === 'null' || !ALLOWED_ORIGINS.includes(origin as string))) { | ||
| throw new UnauthorizedError('Invalid origin'); | ||
| } |
There was a problem hiding this comment.
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.
Summary by CodeRabbit
New Features
Chores
Refactor