🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix: improve video generation security and type safety
YuTengjing43820eeb2e24
diff --git a/packages/database/src/models/generationBatch.ts b/packages/database/src/models/generationBatch.tsindex ac5cb1faa0b..f8ea26c958e 100644--- a/packages/database/src/models/generationBatch.ts+++ b/packages/database/src/models/generationBatch.ts@@ -2,6 +2,7 @@ import type {Generation,GenerationBatch,GenerationConfig,+ ImageGenerationAsset,VideoGenerationAsset,} from '@lobechat/types';import debug from 'debug';@@ -202,10 +203,12 @@ export class GenerationBatchModel {const filesToDelete: string[] = [];if (batchWithGenerations.generations) {for (const gen of batchWithGenerations.generations) {- const asset = gen.asset as VideoGenerationAsset;+ const asset = gen.asset as ImageGenerationAsset | VideoGenerationAsset | null;if (asset?.url) filesToDelete.push(asset.url);if (asset?.thumbnailUrl) filesToDelete.push(asset.thumbnailUrl);- if (asset?.coverUrl) filesToDelete.push(asset.coverUrl);+ if (asset && 'coverUrl' in asset && asset.coverUrl) {+ filesToDelete.push(asset.coverUrl);+ }}}diff --git a/packages/database/src/models/generationTopic.ts b/packages/database/src/models/generationTopic.tsindex 09c8d820059..45cafc5471a 100644--- a/packages/database/src/models/generationTopic.ts+++ b/packages/database/src/models/generationTopic.ts@@ -1,4 +1,8 @@-import type { ImageGenerationTopic, VideoGenerationAsset } from '@lobechat/types';+import type {+ ImageGenerationAsset,+ ImageGenerationTopic,+ VideoGenerationAsset,+} from '@lobechat/types';import { and, desc, eq } from 'drizzle-orm';import { FileService } from '@/server/services/file';@@ -117,10 +121,12 @@ export class GenerationTopicModel {if (topicWithBatches.batches) {for (const batch of topicWithBatches.batches) {for (const gen of batch.generations) {- const asset = gen.asset as VideoGenerationAsset;+ const asset = gen.asset as ImageGenerationAsset | VideoGenerationAsset | null;if (asset?.url) filesToDelete.push(asset.url);if (asset?.thumbnailUrl) filesToDelete.push(asset.thumbnailUrl);- if (asset?.coverUrl) filesToDelete.push(asset.coverUrl);+ if (asset && 'coverUrl' in asset && asset.coverUrl) {+ filesToDelete.push(asset.coverUrl);+ }}}}diff --git a/src/app/(backend)/api/webhooks/video/[provider]/route.ts b/src/app/(backend)/api/webhooks/video/[provider]/route.tsindex ff563ab4845..2a34ab38fd9 100644--- a/src/app/(backend)/api/webhooks/video/[provider]/route.ts+++ b/src/app/(backend)/api/webhooks/video/[provider]/route.ts@@ -85,13 +85,11 @@ export const POST = async (req: Request, { params }: { params: Promise<{ provideconst metadata = asyncTask.metadata as VideoGenerationTaskMetadata | undefined;const expectedToken = metadata?.webhookToken;- if (expectedToken) {- if (!token || !safeCompare(token, expectedToken)) {- log('Webhook token verification failed for asyncTask: %s', asyncTask.id);- return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });- }- log('Webhook token verified for asyncTask: %s', asyncTask.id);+ if (!expectedToken || !token || !safeCompare(token, expectedToken)) {+ log('Webhook token verification failed for asyncTask: %s', asyncTask.id);+ return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });}+ log('Webhook token verified for asyncTask: %s', asyncTask.id);asyncTaskId = asyncTask.id;asyncTaskUserId = asyncTask.userId;diff --git a/src/app/[variants]/(main)/video/loading.tsx b/src/app/[variants]/(main)/video/loading.tsxindex f5906433e8a..ab8af8d3350 100644--- a/src/app/[variants]/(main)/video/loading.tsx+++ b/src/app/[variants]/(main)/video/loading.tsx@@ -1,3 +1,5 @@import Loading from '@/components/Loading/BrandTextLoading';-export default () => <Loading debugId="Video Page" />;+const VideoLoading = () => <Loading debugId="Video Page" />;++export default VideoLoading;diff --git a/src/server/services/generation/video.ts b/src/server/services/generation/video.tsindex 25e680e4ea8..4245bf4092b 100644--- a/src/server/services/generation/video.ts+++ b/src/server/services/generation/video.ts@@ -1,4 +1,5 @@import { execFile } from 'node:child_process';+import { createHash } from 'node:crypto';import { createWriteStream, promises as fs } from 'node:fs';import os from 'node:os';import path from 'node:path';@@ -8,7 +9,6 @@ import { promisify } from 'node:util';import { type LobeChatDatabase } from '@lobechat/database';import debug from 'debug';-import { sha256 } from 'js-sha256';import { nanoid } from 'nanoid';import sharp from 'sharp';@@ -71,7 +71,7 @@ export class VideoGenerationService {log('Video metadata: %O', metadata);- const fileHash = sha256(videoBuffer);+ const fileHash = createHash('sha256').update(videoBuffer).digest('hex');const fileSize = videoBuffer.length;// Determine MIME type from URL or default to mp4@@ -157,23 +157,55 @@ export class VideoGenerationService {}}+ /** Max video file size: 500 MB */+ private static MAX_VIDEO_SIZE = 500 * 1024 * 1024;+ /** Download timeout: 5 minutes */+ private static DOWNLOAD_TIMEOUT_MS = 5 * 60 * 1000;+private async downloadVideo(url: string): Promise<string> {const ext = path.extname(new URL(url).pathname).toLowerCase() || '.mp4';const tempVideoPath = path.join(os.tmpdir(), `lobe-video-${nanoid()}${ext}`);log('Downloading video to: %s', tempVideoPath);- const response = await fetch(url);+ const response = await fetch(url, {+ signal: AbortSignal.timeout(VideoGenerationService.DOWNLOAD_TIMEOUT_MS),+ });if (!response.ok) {throw new Error(`Failed to download video: ${response.status} ${response.statusText}`);}+ // Check Content-Length header if available+ const contentLength = Number(response.headers.get('content-length'));+ if (contentLength && contentLength > VideoGenerationService.MAX_VIDEO_SIZE) {+ throw new Error(+ `Video file too large: ${contentLength} bytes (max ${VideoGenerationService.MAX_VIDEO_SIZE} bytes)`,+ );+ }+if (!response.body) {throw new Error(`Response body is empty for video URL: ${url}`);}- await pipeline(Readable.fromWeb(response.body as any), createWriteStream(tempVideoPath));-- log('Video downloaded successfully');+ // Track downloaded size during streaming+ let downloadedSize = 0;+ const maxSize = VideoGenerationService.MAX_VIDEO_SIZE;+ const sizeCheckTransform = new TransformStream({+ transform(chunk, controller) {+ downloadedSize += chunk.byteLength;+ if (downloadedSize > maxSize) {+ controller.error(+ new Error(`Video file too large: exceeded ${maxSize} bytes during download`),+ );+ return;+ }+ controller.enqueue(chunk);+ },+ });++ const limitedBody = response.body.pipeThrough(sizeCheckTransform);+ await pipeline(Readable.fromWeb(limitedBody as any), createWriteStream(tempVideoPath));++ log('Video downloaded successfully (%d bytes)', downloadedSize);return tempVideoPath;}@@ -226,10 +258,14 @@ export class VideoGenerationService {log('Generating screenshot from video');await execFileAsync(ffmpegPath, [- '-ss', '0.1',- '-i', videoPath,- '-frames:v', '1',- '-s', `${width}x${height}`,+ '-ss',+ '0.1',+ '-i',+ videoPath,+ '-frames:v',+ '1',+ '-s',+ `${width}x${height}`,'-y',outputPath,]);