forked from C4illin/ConvertX
-
Notifications
You must be signed in to change notification settings - Fork 3
fix: package animated image frames into secure zip archive #14
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
devopenstuds
wants to merge
1
commit into
swe-productivity:main
Choose a base branch
from
devopenstuds:fix-animated-image-download
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
|
|
||
| # Don't index SpecStory auto-save files, but allow explicit context inclusion via @ references | ||
| .specstory/** |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,8 @@ | ||
| import { Cookie } from "elysia"; | ||
| import AdmZip from "adm-zip"; | ||
| import { unlink, rename, stat } from "node:fs/promises"; | ||
| import path from "node:path"; | ||
| import sanitize from "sanitize-filename"; | ||
| import db from "../db/db"; | ||
| import { MAX_CONVERT_PROCESS } from "../helpers/env"; | ||
| import { normalizeFiletype, normalizeOutputFiletype } from "../helpers/normalizeFiletype"; | ||
|
|
@@ -148,6 +152,129 @@ function chunks<T>(arr: T[], size: number): T[][] { | |
| ); | ||
| } | ||
|
|
||
| async function handleMultiFrameOutput( | ||
| targetPath: string, | ||
| newFileName: string, | ||
| userOutputDir: string, | ||
| ): Promise<string> { | ||
| const targetFile = Bun.file(targetPath); | ||
| const exists = await targetFile.exists(); | ||
|
|
||
| if (exists) { | ||
| // Target file exists as expected, return unchanged | ||
| return newFileName; | ||
| } | ||
|
|
||
| // Target file doesn't exist, multi-frame detection will be needed | ||
| console.log(`Multi-frame detection needed for: ${newFileName}`); | ||
| console.log(`Expected file not found: ${targetPath}`); | ||
|
|
||
| // Extract base filename and extension | ||
| const lastDotIndex = newFileName.lastIndexOf("."); | ||
| const baseFileName = lastDotIndex > 0 ? newFileName.substring(0, lastDotIndex) : newFileName; | ||
| const extension = lastDotIndex > 0 ? newFileName.substring(lastDotIndex + 1) : ""; | ||
|
|
||
| // Sanitize: strip path separators then apply sanitize-filename to prevent path traversal | ||
| const safeBaseFileName = sanitize(baseFileName.replace(/[/\\]/g, "")); | ||
|
|
||
| console.log(`Base filename: ${safeBaseFileName}, Extension: ${extension}`); | ||
|
|
||
| // Escape glob metacharacters in baseFileName to prevent pattern injection | ||
| const escapedBaseFileName = safeBaseFileName.replace(/[*?[\]{}!\\]/g, "\\$&"); | ||
|
|
||
| // Search for frame files matching pattern: baseFileName-*.extension | ||
| const framePattern = `${escapedBaseFileName}-*.${extension}`; | ||
| const glob = new Bun.Glob(framePattern); | ||
| const frameFiles: string[] = []; | ||
|
|
||
| // Scan the output directory for matching files | ||
| for await (const file of glob.scan({ cwd: userOutputDir, onlyFiles: true })) { | ||
| frameFiles.push(file); | ||
| } | ||
|
|
||
| console.log(`Detected ${frameFiles.length} frame file(s):`); | ||
| for (const frameFile of frameFiles) { | ||
| console.log(` - ${frameFile}`); | ||
| } | ||
|
|
||
| // Handle based on number of frame files detected | ||
| if (frameFiles.length === 0) { | ||
| throw new Error(`No output files generated for ${newFileName}`); | ||
| } | ||
|
|
||
| if (frameFiles.length === 1) { | ||
| // Single frame: rename to expected target path | ||
| const frame = frameFiles[0]!; | ||
| const singleFramePath = path.join(userOutputDir, frame); | ||
| console.log(`Renaming single frame: ${frameFiles[0]} -> ${newFileName}`); | ||
| await rename(singleFramePath, targetPath); | ||
| return newFileName; | ||
| } | ||
|
|
||
| // Multiple frames: create a zip archive | ||
| console.log(`Creating zip archive for ${frameFiles.length} frames`); | ||
| const zipFileName = `${safeBaseFileName}.zip`; | ||
| const zipPath = path.join(userOutputDir, zipFileName); | ||
|
|
||
| // Verify the resolved zip path is inside userOutputDir to prevent path traversal | ||
| const resolvedZipPath = path.resolve(zipPath); | ||
| const resolvedOutputDir = path.resolve(userOutputDir); | ||
| if (!resolvedZipPath.startsWith(resolvedOutputDir + path.sep)) { | ||
| throw new Error(`Path traversal detected: zip path escapes output directory`); | ||
| } | ||
|
|
||
| // Memory safeguard: reject before loading anything if total frame size exceeds 200 MB | ||
| const MAX_ZIP_BYTES = 200 * 1024 * 1024; | ||
| let totalFrameSize = 0; | ||
| for (const frameFile of frameFiles) { | ||
| const { size } = await stat(path.join(userOutputDir, frameFile)); | ||
| totalFrameSize += size; | ||
| } | ||
| if (totalFrameSize > MAX_ZIP_BYTES) { | ||
| throw new Error( | ||
| `Total frame size (${Math.round(totalFrameSize / 1024 / 1024)} MB) exceeds the 200 MB zip memory limit`, | ||
| ); | ||
| } | ||
|
|
||
| const zip = new AdmZip(); | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What do you think about using tar instead like |
||
|
|
||
| // Add all frame files to the zip | ||
| for (const frameFile of frameFiles) { | ||
| const frameFilePath = path.join(userOutputDir, frameFile); | ||
| console.log(`Adding to zip: ${frameFile}`); | ||
| zip.addLocalFile(frameFilePath); | ||
| } | ||
|
|
||
| try { | ||
| // Write synchronously — no callback, no hanging Promise | ||
| zip.writeZip(zipPath); | ||
|
|
||
| console.log(`Zip created successfully: ${zipFileName}`); | ||
|
|
||
| // Delete individual frame files only after zip is confirmed written | ||
| for (const frameFile of frameFiles) { | ||
| const frameFilePath = path.join(userOutputDir, frameFile); | ||
| try { | ||
| await unlink(frameFilePath); | ||
| console.log(`Deleted frame file: ${frameFile}`); | ||
| } catch (err) { | ||
| console.error(`Failed to delete frame file ${frameFile}: ${err instanceof Error ? err.message : String(err)}`); | ||
| } | ||
| } | ||
| } catch (err) { | ||
| // Clean up any partial zip, but leave frame files intact | ||
| const partialExists = await Bun.file(zipPath).exists(); | ||
| if (partialExists) { | ||
| await unlink(zipPath).catch(() => {}); | ||
| } | ||
| throw new Error( | ||
| `Failed to create zip for ${safeBaseFileName}: ${err instanceof Error ? err.message : String(err)}`, | ||
| ); | ||
| } | ||
|
|
||
| return zipFileName; | ||
| } | ||
|
|
||
| export async function handleConvert( | ||
| fileNames: string[], | ||
| userUploadsDir: string, | ||
|
|
@@ -175,9 +302,10 @@ export async function handleConvert( | |
| toProcess.push( | ||
| new Promise((resolve, reject) => { | ||
| mainConverter(filePath, fileType, convertTo, targetPath, {}, converterName) | ||
| .then((r) => { | ||
| .then(async (r) => { | ||
| const finalFileName = await handleMultiFrameOutput(targetPath, newFileName, userOutputDir); | ||
| if (jobId.value) { | ||
| query.run(jobId.value, fileName, newFileName, r); | ||
| query.run(jobId.value, fileName, finalFileName, r); | ||
| } | ||
| resolve(r); | ||
| }) | ||
|
|
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
sanitize already removes / and \