Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .cursorindexingignore
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/**
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ yarn-debug.log*
yarn-error.log*

# local env files
.env
.env.local
.env.development.local
.env.test.local
Expand All @@ -50,3 +51,4 @@ package-lock.json
/Bruno
/tsconfig.tsbuildinfo
/public/generated.css
/.specstory
6 changes: 6 additions & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"@elysiajs/jwt": "^1.4.0",
"@elysiajs/static": "^1.4.6",
"@kitajs/html": "^4.2.11",
"adm-zip": "^0.5.16",
"elysia": "^1.4.16",
"sanitize-filename": "^1.6.3",
"tar": "^7.5.2"
Expand All @@ -34,6 +35,7 @@
"@kitajs/ts-html-plugin": "^4.1.3",
"@tailwindcss/cli": "^4.1.17",
"@tailwindcss/postcss": "^4.1.17",
"@types/adm-zip": "^0.5.7",
"@types/bun": "latest",
"@types/node": "^24.10.1",
"@typescript-eslint/parser": "^8.46.4",
Expand Down
132 changes: 130 additions & 2 deletions src/converters/main.ts
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";
Expand Down Expand Up @@ -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, ""));
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

sanitize already removes / and \


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();
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

What do you think about using tar instead like src/pages/download.tsx


// 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,
Expand Down Expand Up @@ -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);
})
Expand Down