Skip to content

Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.

fix(security): confine resume file paths; move file uploads out of server actions; guard backup export/import and resume import sinks

Khuram Niazc522ba4749eb
diff --git a/__tests__/backupExport.spec.ts b/__tests__/backupExport.spec.ts
index 74255e7..3757df0 100644
--- a/__tests__/backupExport.spec.ts
+++ b/__tests__/backupExport.spec.ts
@@ -1,5 +1,10 @@
+import fs from "fs";
+import os from "os";
+import path from "path";
+import JSZip from "jszip";
import db from "@/lib/db";
-import { collectBackupData } from "@/lib/backup/export";
+import { APP_CONSTANTS } from "@/lib/constants";
+import { buildBackupZip, collectBackupData } from "@/lib/backup/export";
import { MODEL_SPECS, INSERT_ORDER } from "@/lib/backup/ordering";
vi.mock("@/lib/db", () => {
@@ -126,3 +131,41 @@ describe("collectBackupData", () => {
expect(data.user).toEqual({ defaultResumeId: "r1" });
});
});
+
+describe("buildBackupZip", () => {
+ const originalUploads = APP_CONSTANTS.UPLOADS_DIR;
+ let tmp: string;
+
+ beforeEach(() => {
+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), "jobsync-export-"));
+ (APP_CONSTANTS as { UPLOADS_DIR: string }).UPLOADS_DIR = tmp;
+ });
+
+ afterEach(() => {
+ (APP_CONSTANTS as { UPLOADS_DIR: string }).UPLOADS_DIR = originalUploads;
+ fs.rmSync(tmp, { recursive: true, force: true });
+ });
+
+ it("never reads a stored path outside the resumes directory", async () => {
+ const inside = path.join(tmp, "files", "resumes", "cv.pdf");
+ const outside = path.join(tmp, "dev.db");
+ fs.mkdirSync(path.dirname(inside), { recursive: true });
+ fs.writeFileSync(inside, "%PDF-1.4 cv");
+ fs.writeFileSync(outside, "every user's data");
+ const uploadedAt = new Date("2026-01-01");
+ mockDb.file.findMany.mockResolvedValueOnce([
+ { id: "f1", fileName: "cv.pdf", filePath: inside, fileType: "application/pdf", uploadedAt },
+ { id: "f2", fileName: "dev.db", filePath: outside, fileType: "resume", uploadedAt },
+ ]);
+
+ const { buffer } = await buildBackupZip("user-1", "[email protected]");
+
+ const zip = await JSZip.loadAsync(buffer);
+ const data = JSON.parse(await zip.file("data.json")!.async("string"));
+ const byId = (id: string) => data.File.find((f: { id: string }) => f.id === id);
+ expect(zip.file("files/f1/cv.pdf")).not.toBeNull();
+ expect(Object.keys(zip.files).some((n) => n.startsWith("files/f2/"))).toBe(false);
+ expect(byId("f1").fileMissing).toBeUndefined();
+ expect(byId("f2").fileMissing).toBe(true);
+ });
+});
diff --git a/__tests__/backupImportGuards.spec.ts b/__tests__/backupImportGuards.spec.ts
index 7010483..d63c800 100644
--- a/__tests__/backupImportGuards.spec.ts
+++ b/__tests__/backupImportGuards.spec.ts
@@ -1,4 +1,8 @@
+import fs from "fs";
+import os from "os";
+import path from "path";
import JSZip from "jszip";
+import { APP_CONSTANTS } from "@/lib/constants";
import db from "@/lib/db";
import { importBackup } from "@/lib/backup/import";
import { BackupError, buildManifest } from "@/lib/backup/manifest";
@@ -125,4 +129,29 @@ describe("importBackup guards", () => {
expect(writeSnapshot).not.toHaveBeenCalled();
expect(result.snapshotPath).toBeNull();
});
+
+ it("never unlinks a replaced file outside the resumes directory", async () => {
+ const originalUploads = APP_CONSTANTS.UPLOADS_DIR;
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "jobsync-cleanup-"));
+ (APP_CONSTANTS as { UPLOADS_DIR: string }).UPLOADS_DIR = tmp;
+ try {
+ const inside = path.join(tmp, "files", "resumes", "old.pdf");
+ const outside = path.join(tmp, "dev.db");
+ fs.mkdirSync(path.dirname(inside), { recursive: true });
+ fs.writeFileSync(inside, "%PDF-1.4 old");
+ fs.writeFileSync(outside, "db");
+ mockDb.file.findMany.mockResolvedValueOnce([
+ { filePath: inside },
+ { filePath: outside },
+ ]);
+
+ await importBackup(await emptyBackup(), "user-1", EMAIL, true);
+
+ expect(fs.existsSync(inside)).toBe(false);
+ expect(fs.existsSync(outside)).toBe(true);
+ } finally {
+ (APP_CONSTANTS as { UPLOADS_DIR: string }).UPLOADS_DIR = originalUploads;
+ fs.rmSync(tmp, { recursive: true, force: true });
+ }
+ });
});
diff --git a/__tests__/defaultResume.actions.spec.ts b/__tests__/defaultResume.actions.spec.ts
index 5d60f39..df0cd3b 100644
--- a/__tests__/defaultResume.actions.spec.ts
+++ b/__tests__/defaultResume.actions.spec.ts
@@ -149,7 +149,7 @@ describe("Default Resume Actions", () => {
(prisma.resume.create as any).mockResolvedValue({ id: "resume-new" });
(prisma.user.update as any).mockResolvedValue({});
- const result = await createResumeProfile("My Resume", "");
+ const result = await createResumeProfile("My Resume");
expect(result.success).toBe(true);
expect(prisma.user.update).toHaveBeenCalledWith({
@@ -167,7 +167,7 @@ describe("Default Resume Actions", () => {
});
(prisma.user.update as any).mockResolvedValue({});
- const result = await createResumeProfile("My Resume", "");
+ const result = await createResumeProfile("My Resume");
expect(result.success).toBe(true);
expect(prisma.user.update).toHaveBeenCalledWith({
@@ -181,7 +181,7 @@ describe("Default Resume Actions", () => {
(prisma.profile.findFirst as any).mockResolvedValue({ id: "profile-1" });
(prisma.resume.create as any).mockResolvedValue({ id: "resume-new" });
- const result = await createResumeProfile("Another Resume", "");
+ const result = await createResumeProfile("Another Resume");
expect(result.success).toBe(true);
expect(prisma.user.update).not.toHaveBeenCalled();
diff --git a/__tests__/profileFiles.actions.spec.ts b/__tests__/profileFiles.actions.spec.ts
new file mode 100644
index 0000000..a96b596
--- /dev/null
+++ b/__tests__/profileFiles.actions.spec.ts
@@ -0,0 +1,79 @@
+import fs from "fs";
+import os from "os";
+import path from "path";
+import { PrismaClient } from "@prisma/client";
+import { deleteFile } from "@/actions/profile.actions";
+import { getCurrentUser } from "@/utils/user.utils";
+import { APP_CONSTANTS } from "@/lib/constants";
+
+const prisma = new PrismaClient();
+
+vi.mock("@prisma/client", () => {
+ const mPrismaClient = {
+ file: { findFirst: vi.fn(), delete: vi.fn() },
+ };
+ return {
+ PrismaClient: vi.fn(function () {
+ return mPrismaClient;
+ }),
+ };
+});
+
+vi.mock("@/utils/user.utils", () => ({ getCurrentUser: vi.fn() }));
+
+describe("deleteFile", () => {
+ const originalUploads = APP_CONSTANTS.UPLOADS_DIR;
+ let tmp: string;
+ let resumes: string;
+
+ beforeEach(() => {
+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), "jobsync-delete-"));
+ resumes = path.join(tmp, "files", "resumes");
+ fs.mkdirSync(resumes, { recursive: true });
+ (APP_CONSTANTS as { UPLOADS_DIR: string }).UPLOADS_DIR = tmp;
+ (getCurrentUser as any).mockResolvedValue({ id: "user-1" });
+ (prisma.file.delete as any).mockResolvedValue({});
+ });
+
+ afterEach(() => {
+ (APP_CONSTANTS as { UPLOADS_DIR: string }).UPLOADS_DIR = originalUploads;
+ fs.rmSync(tmp, { recursive: true, force: true });
+ });
+
+ it("unlinks the bytes and deletes the row for a file inside the directory", async () => {
+ const filePath = path.join(resumes, "cv.pdf");
+ fs.writeFileSync(filePath, "%PDF");
+ (prisma.file.findFirst as any).mockResolvedValue({ id: "f1", filePath });
+
+ await deleteFile("f1");
+
+ expect(prisma.file.findFirst).toHaveBeenCalledWith({
+ where: { id: "f1", Resume: { profile: { userId: "user-1" } } },
+ });
+ expect(fs.existsSync(filePath)).toBe(false);
+ expect(prisma.file.delete).toHaveBeenCalledWith({ where: { id: "f1" } });
+ });
+
+ it("skips the unlink for a stored path outside the directory but still deletes the row", async () => {
+ const outside = path.join(tmp, "dev.db");
+ fs.writeFileSync(outside, "db");
+ (prisma.file.findFirst as any).mockResolvedValue({
+ id: "f1",
+ filePath: outside,
+ });
+
+ await deleteFile("f1");
+
+ expect(fs.existsSync(outside)).toBe(true);
+ expect(prisma.file.delete).toHaveBeenCalledWith({ where: { id: "f1" } });
+ });
+
+ it("refuses a file the caller does not own", async () => {
+ (prisma.file.findFirst as any).mockResolvedValue(null);
+
+ await expect(deleteFile("someone-elses")).rejects.toThrow(
+ "File not found or access denied",
+ );
+ expect(prisma.file.delete).not.toHaveBeenCalled();
+ });
+});
diff --git a/__tests__/resume-upload-route.spec.ts b/__tests__/resume-upload-route.spec.ts
new file mode 100644
index 0000000..a42e7a3
--- /dev/null
+++ b/__tests__/resume-upload-route.spec.ts
@@ -0,0 +1,118 @@
+// @vitest-environment node
+// Tests for POST /api/profile/resume: the route builds the upload path itself
+// and never forwards a client-supplied fileId.
+
+vi.mock("@/auth", () => ({ auth: vi.fn() }));
+vi.mock("@/lib/db", () => ({ default: {} }));
+vi.mock("@/actions/profile.actions", () => ({ editResume: vi.fn() }));
+vi.mock("@/actions/profile/resumeUpload", () => ({
+ createResume: vi.fn(),
+ replaceResumeFile: vi.fn(),
+}));
+vi.mock("@/lib/resumeFiles", () => ({
+ saveResumeUpload: vi.fn(),
+ isResumeFilePath: vi.fn(),
+}));
+vi.mock("next/server", () => ({
+ NextResponse: class {
+ static json(data: unknown, init?: { status?: number }) {
+ return { status: init?.status ?? 200, json: async () => data };
+ }
+ },
+}));
+
+import { POST } from "@/app/api/profile/resume/route";
+import { auth } from "@/auth";
+import { editResume } from "@/actions/profile.actions";
+import {
+ createResume,
+ replaceResumeFile,
+} from "@/actions/profile/resumeUpload";
+import { saveResumeUpload } from "@/lib/resumeFiles";
+
+const UPLOAD = {
+ fileName: "cv.pdf",
+ filePath: "data/files/resumes/cv_2026-09-13T12-00-00.pdf",
+};
+
+const pdf = (bytes = "%PDF-1.4 test") =>
+ new File([Buffer.from(bytes)], "cv.pdf", { type: "application/pdf" });
+
+// The client appends `undefined` when there is no file, which sends this string
+const NO_FILE = "undefined";
+
+const post = async (fields: Record<string, string | File>) => {
+ const fd = new FormData();
+ for (const [key, value] of Object.entries(fields)) fd.append(key, value);
+ const res: any = await POST({ formData: async () => fd } as any);
+ return { status: res.status, body: await res.json() };
+};
+
+describe("POST /api/profile/resume", () => {
+ beforeEach(() => {
+ (auth as any).mockResolvedValue({ user: { id: "user-1" } });
+ (saveResumeUpload as any).mockResolvedValue(UPLOAD);
+ (createResume as any).mockResolvedValue({ success: true, data: { id: "r-new" } });
+ (replaceResumeFile as any).mockResolvedValue({ success: true, data: { id: "r1" } });
+ (editResume as any).mockResolvedValue({ success: true, data: { id: "r1" } });
+ });
+
+ it("replaces an edited resume's file and never forwards the client fileId", async () => {
+ const res = await post({
+ file: pdf(),
+ title: "CV",
+ id: "r1",
+ fileId: "someone-elses-file",
+ });
+
+ expect(res.status).toBe(200);
+ expect(saveResumeUpload).toHaveBeenCalledWith("cv.pdf", expect.any(Buffer));
+ expect(replaceResumeFile).toHaveBeenCalledWith("r1", "CV", UPLOAD);
+ expect(JSON.stringify((replaceResumeFile as any).mock.calls)).not.toContain(
+ "someone-elses-file",
+ );
+ expect(editResume).not.toHaveBeenCalled();
+ });
+
+ it("renames without touching the file when no file is sent", async () => {
+ const res = await post({ file: NO_FILE, title: "CV", id: "r1", fileId: "f1" });
+
+ expect(res.status).toBe(200);
+ expect(editResume).toHaveBeenCalledWith("r1", "CV");
+ expect(saveResumeUpload).not.toHaveBeenCalled();
+ expect(replaceResumeFile).not.toHaveBeenCalled();
+ });
+
+ it("creates a resume with an uploaded file", async () => {
+ const res = await post({ file: pdf(), title: "CV" });
+
+ expect(res.status).toBe(201);
+ expect(createResume).toHaveBeenCalledWith("CV", UPLOAD);
+ expect(res.body).toEqual({ success: true, data: { id: "r-new" } });
+ });
+
+ it("creates a resume without a file", async () => {
+ const res = await post({ file: NO_FILE, title: "CV" });
+
+ expect(res.status).toBe(201);
+ expect(createResume).toHaveBeenCalledWith("CV", undefined);
+ expect(saveResumeUpload).not.toHaveBeenCalled();
+ });
+
+ it("refuses bytes that do not match the declared type before saving", async () => {
+ const res = await post({ file: pdf("not a pdf"), title: "CV" });
+
+ expect(res.status).toBe(400);
+ expect(saveResumeUpload).not.toHaveBeenCalled();
+ expect(createResume).not.toHaveBeenCalled();
+ });
+
+ it("passes a failed replace through as 200 with success false", async () => {
+ (replaceResumeFile as any).mockResolvedValue({ success: false, message: "boom" });
+
+ const res = await post({ file: pdf(), title: "CV", id: "r1" });
+
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ success: false, message: "boom" });
+ });
+});
diff --git a/__tests__/resumeFiles.spec.ts b/__tests__/resumeFiles.spec.ts
new file mode 100644
index 0000000..5ca4862
--- /dev/null
+++ b/__tests__/resumeFiles.spec.ts
@@ -0,0 +1,110 @@
+import fs from "fs";
+import os from "os";
+import path from "path";
+import { APP_CONSTANTS } from "@/lib/constants";
+import {
+ isResumeFilePath,
+ removeResumeFile,
+ resumesDir,
+ saveResumeUpload,
+} from "@/lib/resumeFiles";
+
+const originalUploads = APP_CONSTANTS.UPLOADS_DIR;
+const setUploadsDir = (dir: string) => {
+ (APP_CONSTANTS as { UPLOADS_DIR: string }).UPLOADS_DIR = dir;
+};
+
+describe("isResumeFilePath", () => {
+ afterEach(() => setUploadsDir(originalUploads));
+
+ it("resolves the resumes directory under UPLOADS_DIR", () => {
+ expect(resumesDir()).toBe(
+ path.resolve(originalUploads, "files", "resumes"),
+ );
+ });
+
+ it("accepts relative and absolute paths inside the directory", () => {
+ expect(
+ isResumeFilePath(path.join(originalUploads, "files", "resumes", "cv.pdf")),
+ ).toBe(true);
+ expect(isResumeFilePath(path.join(resumesDir(), "cv.pdf"))).toBe(true);
+ });
+
+ it.each([
+ ["the directory itself", () => resumesDir()],
+ ["a backup snapshot", () =>
+ path.join(originalUploads, "backups", "u1", "pre-import.zip")],
+ ["the database", () => path.join(originalUploads, "dev.db")],
+ ["a sibling directory", () => path.join(`${resumesDir()}-old`, "cv.pdf")],
+ ["an absolute system path", () => "/etc/passwd"],
+ ["a ../ traversal", () => `${resumesDir()}/../../dev.db`],
+ ])("rejects %s", (_label, make) => {
+ expect(isResumeFilePath(make())).toBe(false);
+ });
+
+ it("follows a runtime UPLOADS_DIR override", () => {
+ const tmp = path.join(os.tmpdir(), "jobsync-override");
+ setUploadsDir(tmp);
+
+ expect(isResumeFilePath(path.join(tmp, "files", "resumes", "cv.pdf"))).toBe(
+ true,
+ );
+ expect(
+ isResumeFilePath(path.join(originalUploads, "files", "resumes", "cv.pdf")),
+ ).toBe(false);
+ });
+});
+
+describe("saveResumeUpload / removeResumeFile", () => {
+ let tmp: string;
+
+ beforeEach(() => {
+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), "jobsync-resumes-"));
+ setUploadsDir(tmp);
+ });
+
+ afterEach(() => {
+ setUploadsDir(originalUploads);
+ fs.rmSync(tmp, { recursive: true, force: true });
+ });
+
+ it("creates the directory and writes the bytes under a timestamped name", async () => {
+ const upload = await saveResumeUpload("cv.pdf", Buffer.from("%PDF-1.4 x"));
+
+ expect(upload.fileName).toBe("cv.pdf");
+ expect(isResumeFilePath(upload.filePath)).toBe(true);
+ expect(path.basename(upload.filePath)).toMatch(
+ /^cv_\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}\.pdf$/,
+ );
+ expect(fs.readFileSync(upload.filePath).toString()).toBe("%PDF-1.4 x");
+ });
+
+ it("never lets the client file name choose the directory", async () => {
+ const upload = await saveResumeUpload("../../dev.pdf", Buffer.from("%PDF"));
+
+ expect(path.dirname(path.resolve(upload.filePath))).toBe(resumesDir());
+ });
+
+ it("unlinks a file inside the directory", async () => {
+ const { filePath } = await saveResumeUpload("cv.pdf", Buffer.from("%PDF"));
+
+ await removeResumeFile(filePath);
+
+ expect(fs.existsSync(filePath)).toBe(false);
+ });
+
+ it("leaves a path outside the directory on disk", async () => {
+ const outside = path.join(tmp, "dev.db");
+ fs.writeFileSync(outside, "db");
+
+ await removeResumeFile(outside);
+
+ expect(fs.existsSync(outside)).toBe(true);
+ });
+
+ it("does not throw when the file is already gone", async () => {
+ await expect(
+ removeResumeFile(path.join(resumesDir(), "missing.pdf")),
+ ).resolves.toBeUndefined();
+ });
+});
diff --git a/__tests__/resumeUpload.actions.spec.ts b/__tests__/resumeUpload.actions.spec.ts
new file mode 100644
index 0000000..b884c27
--- /dev/null
+++ b/__tests__/resumeUpload.actions.spec.ts
@@ -0,0 +1,301 @@
+import fs from "fs";
+import os from "os";
+import path from "path";
+import { PrismaClient } from "@prisma/client";
+import { getCurrentUser } from "@/utils/user.utils";
+import { APP_CONSTANTS } from "@/lib/constants";
+import { createFileEntry } from "@/actions/profile/shared";
+import { editResume } from "@/actions/profile.actions";
+import {
+ createResume,
+ replaceResumeFile,
+} from "@/actions/profile/resumeUpload";
+
+const prisma = new PrismaClient();
+
+vi.mock("@prisma/client", () => {
+ const mPrismaClient: Record<string, any> = {
+ resume: {
+ findUnique: vi.fn(),
+ findMany: vi.fn(),
+ count: vi.fn(),
+ create: vi.fn(),
+ update: vi.fn(),
+ },
+ profile: { findFirst: vi.fn(), create: vi.fn() },
+ user: { update: vi.fn() },
+ file: { create: vi.fn(), delete: vi.fn() },
+ };
+ // Interactive transaction: hand the callback the same mock client
+ mPrismaClient.$transaction = vi.fn((fn: (tx: unknown) => unknown) =>
+ fn(mPrismaClient),
+ );
+ return {
+ PrismaClient: vi.fn(function () {
+ return mPrismaClient;
+ }),
+ };
+});
+
+vi.mock("@/utils/user.utils", () => ({ getCurrentUser: vi.fn() }));
+
+const db = prisma as any;
+const originalUploads = APP_CONSTANTS.UPLOADS_DIR;
+let tmp: string;
+let resumes: string;
+
+const writeResumeFile = (name: string, content: string) => {
+ const filePath = path.join(resumes, name);
+ fs.writeFileSync(filePath, content);
+ return filePath;
+};
+
+beforeEach(() => {
+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), "jobsync-upload-"));
+ resumes = path.join(tmp, "files", "resumes");
+ fs.mkdirSync(resumes, { recursive: true });
+ (APP_CONSTANTS as { UPLOADS_DIR: string }).UPLOADS_DIR = tmp;
+ (getCurrentUser as any).mockResolvedValue({ id: "user-1" });
+});
+
+afterEach(() => {
+ (APP_CONSTANTS as { UPLOADS_DIR: string }).UPLOADS_DIR = originalUploads;
+ fs.rmSync(tmp, { recursive: true, force: true });
+});
+
+describe("createFileEntry", () => {
+ it("refuses a path outside the resumes directory before writing", async () => {
+ await expect(createFileEntry("x.pdf", "/etc/passwd")).rejects.toThrow(
+ "File path is outside the resumes directory",
+ );
+ await expect(createFileEntry("x.pdf", undefined)).rejects.toThrow(
+ "File path is outside the resumes directory",
+ );
+ expect(db.file.create).not.toHaveBeenCalled();
+ });
+
+ it("writes through the client it is given", async () => {
+ const tx = { file: { create: vi.fn().mockResolvedValue({ id: "f-tx" }) } };
+
+ const id = await createFileEntry("cv.pdf", path.join(resumes, "cv.pdf"), tx as any);
+
+ expect(id).toBe("f-tx");
+ expect(tx.file.create).toHaveBeenCalledWith({
+ data: {
+ fileName: "cv.pdf",
+ filePath: path.join(resumes, "cv.pdf"),
+ fileType: "resume",
+ },
+ });
+ expect(db.file.create).not.toHaveBeenCalled();
+ });
+});
+
+describe("createResume", () => {
+ beforeEach(() => {
+ db.resume.findMany.mockResolvedValue([]);
+ db.resume.count.mockResolvedValue(1);
+ db.profile.findFirst.mockResolvedValue({ id: "profile-1" });
+ });
+
+ it("links a file built from the upload", async () => {
+ const filePath = writeResumeFile("cv.pdf", "%PDF");
+ db.file.create.mockResolvedValue({ id: "f-new" });
+ db.resume.create.mockResolvedValue({ id: "r-new" });
+
+ const result = await createResume("CV", { fileName: "cv.pdf", filePath });
+
+ expect(result).toEqual({ success: true, data: { id: "r-new" } });
+ expect(db.resume.create).toHaveBeenCalledWith({
+ data: { profileId: "profile-1", title: "CV", FileId: "f-new" },
+ });
+ expect(fs.existsSync(filePath)).toBe(true);
+ });
+
+ it("creates without a file when there is no upload", async () => {
+ db.resume.create.mockResolvedValue({ id: "r-new" });
+
+ const result = await createResume("CV");
+
+ expect(result.success).toBe(true);
+ expect(db.file.create).not.toHaveBeenCalled();
+ expect(db.resume.create).toHaveBeenCalledWith({
+ data: { profileId: "profile-1", title: "CV", FileId: null },
+ });
+ });
+
+ it("removes the uploaded bytes when the create fails", async () => {
+ const filePath = writeResumeFile("cv.pdf", "%PDF");
+ db.file.create.mockResolvedValue({ id: "f-new" });
+ db.resume.create.mockRejectedValue(new Error("boom"));
+
+ const result = await createResume("CV", { fileName: "cv.pdf", filePath });
+
+ expect(result).toEqual({ success: false, message: "boom" });
+ expect(fs.existsSync(filePath)).toBe(false);
+ });
+
+ it("keeps the bytes when the resume was created but the auto-default fails", async () => {
+ const filePath = writeResumeFile("cv.pdf", "%PDF");
+ db.resume.count.mockResolvedValue(0);
+ db.file.create.mockResolvedValue({ id: "f-new" });
+ db.resume.create.mockResolvedValue({ id: "r-new" });
+ db.user.update.mockRejectedValue(new Error("db busy"));
+
+ const result = await createResume("CV", { fileName: "cv.pdf", filePath });
+
+ expect(result).toEqual({ success: false, message: "db busy" });
+ expect(fs.existsSync(filePath)).toBe(true);
+ });
+});
+
+describe("replaceResumeFile", () => {
+ it("links the new file, then deletes the old row and bytes", async () => {
+ const oldPath = writeResumeFile("old.pdf", "%PDF old");
+ const newPath = writeResumeFile("new.pdf", "%PDF new");
+ db.resume.findUnique.mockResolvedValue({
+ File: { id: "f-old", filePath: oldPath },
+ });
+ db.file.create.mockResolvedValue({ id: "f-new" });
+ db.resume.update.mockResolvedValue({ id: "r1", FileId: "f-new" });
+ db.file.delete.mockResolvedValue({});
+
+ const result = await replaceResumeFile("r1", "CV", {
+ fileName: "new.pdf",
+ filePath: newPath,
+ });
+
+ expect(result).toEqual({ success: true, data: { id: "r1", FileId: "f-new" } });
+ expect(db.resume.findUnique).toHaveBeenCalledWith({
+ where: { id: "r1", profile: { userId: "user-1" } },
+ select: { File: { select: { id: true, filePath: true } } },
+ });
+ expect(db.resume.update).toHaveBeenCalledWith({
+ where: { id: "r1", profile: { userId: "user-1" } },
+ data: { title: "CV", FileId: "f-new" },
+ });
+ expect(db.file.delete).toHaveBeenCalledWith({ where: { id: "f-old" } });
+ expect(db.resume.update.mock.invocationCallOrder[0]).toBeLessThan(
+ db.file.delete.mock.invocationCallOrder[0],
+ );
+ expect(fs.existsSync(oldPath)).toBe(false);
+ expect(fs.existsSync(newPath)).toBe(true);
+ });
+
+ it("keeps the old file and removes the new bytes when the update fails", async () => {
+ const oldPath = writeResumeFile("old.pdf", "%PDF old");
+ const newPath = writeResumeFile("new.pdf", "%PDF new");
+ db.resume.findUnique.mockResolvedValue({
+ File: { id: "f-old", filePath: oldPath },
+ });
+ db.file.create.mockResolvedValue({ id: "f-new" });
+ db.resume.update.mockRejectedValue(new Error("update failed"));
+
+ const result = await replaceResumeFile("r1", "CV", {
+ fileName: "new.pdf",
+ filePath: newPath,
+ });
+
+ expect(result).toEqual({ success: false, message: "update failed" });
+ expect(db.file.delete).not.toHaveBeenCalled();
+ expect(fs.existsSync(oldPath)).toBe(true);
+ expect(fs.existsSync(newPath)).toBe(false);
+ });
+
+ it("rejects a resume the caller does not own before any write", async () => {
+ const newPath = writeResumeFile("new.pdf", "%PDF new");
+ db.resume.findUnique.mockResolvedValue(null);
+
+ const result = await replaceResumeFile("someone-elses", "CV", {
+ fileName: "new.pdf",
+ filePath: newPath,
+ });
+
+ expect(result).toEqual({
+ success: false,
+ message: "Resume not found or access denied",
+ });
+ expect(db.file.create).not.toHaveBeenCalled();
+ expect(db.resume.update).not.toHaveBeenCalled();
+ expect(fs.existsSync(newPath)).toBe(false);
+ });
+
+ it("attaches a file to a resume that had none", async () => {
+ const newPath = writeResumeFile("new.pdf", "%PDF new");
+ db.resume.findUnique.mockResolvedValue({ File: null });
+ db.file.create.mockResolvedValue({ id: "f-new" });
+ db.resume.update.mockResolvedValue({ id: "r1", FileId: "f-new" });
+
+ const result = await replaceResumeFile("r1", "CV", {
+ fileName: "new.pdf",
+ filePath: newPath,
+ });
+
+ expect(result.success).toBe(true);
+ expect(db.file.delete).not.toHaveBeenCalled();
+ });
+
+ it("keeps the bytes when the old and new paths collide", async () => {
+ const samePath = writeResumeFile("cv.pdf", "%PDF new");
+ db.resume.findUnique.mockResolvedValue({
+ File: { id: "f-old", filePath: samePath },
+ });
+ db.file.create.mockResolvedValue({ id: "f-new" });
+ db.resume.update.mockResolvedValue({ id: "r1", FileId: "f-new" });
+ db.file.delete.mockResolvedValue({});
+
+ const result = await replaceResumeFile("r1", "CV", {
+ fileName: "cv.pdf",
+ filePath: samePath,
+ });
+
+ expect(result.success).toBe(true);
+ expect(db.file.delete).toHaveBeenCalledWith({ where: { id: "f-old" } });
+ expect(fs.existsSync(samePath)).toBe(true);
+ });
+
+ it("still succeeds when the old row cannot be deleted", async () => {
+ const oldPath = writeResumeFile("old.pdf", "%PDF old");
+ const newPath = writeResumeFile("new.pdf", "%PDF new");
+ db.resume.findUnique.mockResolvedValue({
+ File: { id: "f-old", filePath: oldPath },
+ });
+ db.file.create.mockResolvedValue({ id: "f-new" });
+ db.resume.update.mockResolvedValue({ id: "r1", FileId: "f-new" });
+ db.file.delete.mockRejectedValue(new Error("P2025"));
+
+ const result = await replaceResumeFile("r1", "CV", {
+ fileName: "new.pdf",
+ filePath: newPath,
+ });
+
+ expect(result.success).toBe(true);
+ expect(fs.existsSync(newPath)).toBe(true);
+ expect(fs.existsSync(oldPath)).toBe(true);
+ });
+});
+
+describe("editResume", () => {
+ it("updates the title only and never touches FileId", async () => {
+ db.resume.update.mockResolvedValue({ id: "r1", title: "New" });
+
+ const result = await (editResume as any)("r1", "New", "client-file-id", "x.pdf", "/etc/passwd");
+
+ expect(result.success).toBe(true);
+ expect(db.resume.update).toHaveBeenCalledWith({
+ where: { id: "r1", profile: { userId: "user-1" } },
+ data: { title: "New" },
+ });
+ expect(db.file.create).not.toHaveBeenCalled();
+ });
+
+ it("checks the session before any write", async () => {
+ (getCurrentUser as any).mockResolvedValue(null);
+
+ const result = await editResume("r1", "New");
+
+ expect(result).toEqual({ success: false, message: "Not authenticated" });
+ expect(db.resume.update).not.toHaveBeenCalled();
+ expect(db.file.create).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/actions/profile.actions.ts b/src/actions/profile.actions.ts
index d961060..62435e0 100644
--- a/src/actions/profile.actions.ts
+++ b/src/actions/profile.actions.ts
@@ -18,7 +18,7 @@ export {
copyResume,
} from "./profile/resumeCopy";
-export { uploadFile, deleteFile } from "./profile/files";
+export { deleteFile } from "./profile/files";
export {
addContactInfo,
diff --git a/src/actions/profile/files.ts b/src/actions/profile/files.ts
index 97f7988..a0c734e 100644
--- a/src/actions/profile/files.ts
+++ b/src/actions/profile/files.ts
@@ -1,20 +1,10 @@
"use server";
import prisma from "@/lib/db";
import fs from "fs";
-import { writeFile } from "fs/promises";
+import { isResumeFilePath } from "@/lib/resumeFiles";
+import { log } from "@/lib/telemetry";
import { requireUser } from "./shared";
-export const uploadFile = async (file: File, dir: string, path: string) => {
- const bytes = await file.arrayBuffer();
- const buffer = new Uint8Array(bytes);
-
- if (!fs.existsSync(dir)) {
- fs.mkdirSync(dir, { recursive: true });
- }
-
- await writeFile(path, buffer);
-};
-
export const deleteFile = async (fileId: string) => {
const user = await requireUser();
@@ -29,7 +19,12 @@ export const deleteFile = async (fileId: string) => {
throw new Error("File not found or access denied");
}
- if (fs.existsSync(file.filePath)) {
+ // A row may predate path confinement; drop it without touching the disk
+ if (!isResumeFilePath(file.filePath)) {
+ log.warn("[Resume] Skipped unlinking a path outside the resumes directory", {
+ "file.path": file.filePath,
+ });
+ } else if (fs.existsSync(file.filePath)) {
fs.unlinkSync(file.filePath);
}
diff --git a/src/actions/profile/resume.ts b/src/actions/profile/resume.ts
index 9cdcf10..41b750b 100644
--- a/src/actions/profile/resume.ts
+++ b/src/actions/profile/resume.ts
@@ -3,7 +3,8 @@ import prisma from "@/lib/db";
import { handleError } from "@/lib/utils";
import { APP_CONSTANTS } from "@/lib/constants";
import { resumeDetailInclude } from "@/lib/jobs/resumeDetailInclude";
-import { createFileEntry, requireUser, resumeListSelect } from "./shared";
+import { requireUser, resumeListSelect } from "./shared";
+import { createResume } from "./resumeUpload";
import { deleteFile } from "./files";
export const getResumeList = async (
@@ -134,120 +135,22 @@ export const saveResumeReviewResult = async (
}
};
+// No file here: a create with a file goes through the upload route only
export const createResumeProfile = async (
title: string,
- fileName: string,
- filePath?: string,
-): Promise<any | undefined> => {
- try {
- const user = await requireUser();
-
- // Build a unique title: if base title is taken, append (2), (3), …
- const existingTitles = await prisma.resume.findMany({
- where: { profile: { userId: user.id } },
- select: { title: true },
- });
- const taken = new Set(existingTitles.map((r) => r.title.toLowerCase()));
- const base = title.trim();
- let uniqueTitle = base;
- let counter = 2;
- while (taken.has(uniqueTitle.toLowerCase())) {
- uniqueTitle = `${base} (${counter++})`;
- }
-
- // Count before creating so we can auto-default the user's first resume.
- const resumeCount = await prisma.resume.count({
- where: { profile: { userId: user.id } },
- });
-
- const profile = await prisma.profile.findFirst({
- where: {
- userId: user.id,
- },
- });
-
- let res: any;
- let createdResumeId: string;
- if (profile && profile.id) {
- res = await prisma.resume.create({
- data: {
- profileId: profile!.id,
- title: uniqueTitle,
- FileId: fileName ? await createFileEntry(fileName, filePath) : null,
- },
- });
- createdResumeId = res.id;
- } else {
- // No profile yet: profile.create returns the profile, so pull the
- // created resume's id from the nested include.
- res = await prisma.profile.create({
- data: {
- userId: user.id,
- resumes: {
- create: [
- {
- title: uniqueTitle,
- FileId: fileName
- ? await createFileEntry(fileName, filePath)
- : null,
- },
- ],
- },
- },
- include: { resumes: { select: { id: true } } },
- });
- createdResumeId = res.resumes[0].id;
- }
-
- // Auto-default only the user's very first resume (decision #4/#5).
- if (resumeCount === 0) {
- await prisma.user.update({
- where: { id: user.id },
- data: { defaultResumeId: createdResumeId },
- });
- }
- // revalidatePath("/dashboard/myjobs", "page");
- return { success: true, data: res };
- } catch (error) {
- const msg = "Failed to create resume.";
- return handleError(error, msg);
- }
-};
+): Promise<any | undefined> => createResume(title);
+// Title only: the file is replaced through the upload route, never from here
export const editResume = async (
id: string,
title: string,
- fileId?: string,
- fileName?: string,
- filePath?: string,
): Promise<any | undefined> => {
try {
- let resolvedFileId = fileId;
-
- if (!fileId && fileName && filePath) {
- resolvedFileId = await createFileEntry(fileName, filePath);
- }
-
- if (resolvedFileId) {
- const isValidFileId = await prisma.file.findFirst({
- where: { id: resolvedFileId },
- });
-
- if (!isValidFileId) {
- throw new Error(
- `The provided FileId "${resolvedFileId}" does not exist.`,
- );
- }
- }
-
const user = await requireUser();
const res = await prisma.resume.update({
where: { id, profile: { userId: user.id } },
- data: {
- title,
- FileId: resolvedFileId || null,
- },
+ data: { title },
});
return { success: true, data: res };
} catch (error) {
diff --git a/src/actions/profile/resumeUpload.ts b/src/actions/profile/resumeUpload.ts
new file mode 100644
index 0000000..7dc10fb
--- /dev/null
+++ b/src/actions/profile/resumeUpload.ts
@@ -0,0 +1,153 @@
+import path from "path";
+import prisma from "@/lib/db";
+import { handleError } from "@/lib/utils";
+import { log } from "@/lib/telemetry";
+import { removeResumeFile, type ResumeUpload } from "@/lib/resumeFiles";
+import { createFileEntry, requireUser } from "./shared";
+
+// Not a "use server" module: these take a server-built file path, so they
+// must never be browser-callable. Only the upload route and resume.ts import
+// them — never re-export them from profile.actions.ts.
+
+export const createResume = async (
+ title: string,
+ upload?: ResumeUpload,
+): Promise<any | undefined> => {
+ // Once a resume row references the upload, a failure must keep its bytes
+ let fileLinked = false;
+ try {
+ const user = await requireUser();
+
+ // Build a unique title: if base title is taken, append (2), (3), …
+ const existingTitles = await prisma.resume.findMany({
+ where: { profile: { userId: user.id } },
+ select: { title: true },
+ });
+ const taken = new Set(existingTitles.map((r) => r.title.toLowerCase()));
+ const base = title.trim();
+ let uniqueTitle = base;
+ let counter = 2;
+ while (taken.has(uniqueTitle.toLowerCase())) {
+ uniqueTitle = `${base} (${counter++})`;
+ }
+
+ // Count before creating so we can auto-default the user's first resume.
+ const resumeCount = await prisma.resume.count({
+ where: { profile: { userId: user.id } },
+ });
+
+ const profile = await prisma.profile.findFirst({
+ where: {
+ userId: user.id,
+ },
+ });
+
+ let res: any;
+ let createdResumeId: string;
+ if (profile && profile.id) {
+ res = await prisma.resume.create({
+ data: {
+ profileId: profile!.id,
+ title: uniqueTitle,
+ FileId: upload
+ ? await createFileEntry(upload.fileName, upload.filePath)
+ : null,
+ },
+ });
+ createdResumeId = res.id;
+ } else {
+ // No profile yet: profile.create returns the profile, so pull the
+ // created resume's id from the nested include.
+ res = await prisma.profile.create({
+ data: {
+ userId: user.id,
+ resumes: {
+ create: [
+ {
+ title: uniqueTitle,
+ FileId: upload
+ ? await createFileEntry(upload.fileName, upload.filePath)
+ : null,
+ },
+ ],
+ },
+ },
+ include: { resumes: { select: { id: true } } },
+ });
+ createdResumeId = res.resumes[0].id;
+ }
+ fileLinked = true;
+
+ // Auto-default only the user's very first resume (decision #4/#5).
+ if (resumeCount === 0) {
+ await prisma.user.update({
+ where: { id: user.id },
+ data: { defaultResumeId: createdResumeId },
+ });
+ }
+ return { success: true, data: res };
+ } catch (error) {
+ if (upload && !fileLinked) await removeResumeFile(upload.filePath);
+ const msg = "Failed to create resume.";
+ return handleError(error, msg);
+ }
+};
+
+export const replaceResumeFile = async (
+ resumeId: string,
+ title: string,
+ upload: ResumeUpload,
+): Promise<any | undefined> => {
+ try {
+ const user = await requireUser();
+
+ // The file being replaced comes from the owned row, never from the form
+ const resume = await prisma.resume.findUnique({
+ where: { id: resumeId, profile: { userId: user.id } },
+ select: { File: { select: { id: true, filePath: true } } },
+ });
+ if (!resume) {
+ throw new Error("Resume not found or access denied");
+ }
+
+ const res = await prisma.$transaction(async (tx) => {
+ const fileId = await createFileEntry(
+ upload.fileName,
+ upload.filePath,
+ tx,
+ );
+ return tx.resume.update({
+ where: { id: resumeId, profile: { userId: user.id } },
+ data: { title, FileId: fileId },
+ });
+ });
+
+ if (resume.File) await removeReplacedFile(resume.File, upload.filePath);
+ return { success: true, data: res };
+ } catch (error) {
+ await removeResumeFile(upload.filePath);
+ const msg = "Failed to update resume or file.";
+ return handleError(error, msg);
+ }
+};
+
+// Never throws: the swap has committed, and replaceResumeFile's catch would
+// otherwise unlink the bytes the resume now points at. Not deleteFile — its
+// ownership chain ran through the resume that no longer references this row.
+const removeReplacedFile = async (
+ file: { id: string; filePath: string },
+ newFilePath: string,
+) => {
+ try {
+ await prisma.file.delete({ where: { id: file.id } });
+ } catch (error) {
+ log.warn("[Resume] Could not delete replaced file row", {
+ "file.id": file.id,
+ error: String(error),
+ });
+ return;
+ }
+ // Same-second uploads of one name share a path; that path is now the new file
+ if (path.resolve(file.filePath) === path.resolve(newFilePath)) return;
+ await removeResumeFile(file.filePath);
+};
diff --git a/src/actions/profile/shared.ts b/src/actions/profile/shared.ts
index 96a0bba..bfe9dfa 100644
--- a/src/actions/profile/shared.ts
+++ b/src/actions/profile/shared.ts
@@ -1,4 +1,5 @@
import prisma from "@/lib/db";
+import { isResumeFilePath } from "@/lib/resumeFiles";
// Not a "use server" module: it exports selects, so it stays internal to
// src/actions/profile/ and is never imported by a client component.
@@ -19,14 +20,20 @@ export const assertResumeOwnership = async (
if (!owned) throw new Error("Resume not found or access denied");
};
+// db is the transaction client when the caller swaps a resume's file
export const createFileEntry = async (
fileName: string | undefined,
filePath: string | undefined,
+ db: Pick<typeof prisma, "file"> = prisma,
) => {
- const newFileEntry = await prisma.file.create({
+ // Only paths built by saveResumeUpload belong here
+ if (!filePath || !isResumeFilePath(filePath)) {
+ throw new Error("File path is outside the resumes directory");
+ }
+ const newFileEntry = await db.file.create({
data: {
fileName: fileName!,
- filePath: filePath!,
+ filePath,
fileType: "resume",
},
});
diff --git a/src/app/api/ai/resume/import/route.ts b/src/app/api/ai/resume/import/route.ts
index f13afa0..7c5eb08 100644
--- a/src/app/api/ai/resume/import/route.ts
+++ b/src/app/api/ai/resume/import/route.ts
@@ -14,6 +14,7 @@ import { ResumeImportSchema } from "@/models/resumeImport.schema";
import { AiModel } from "@/models/ai.model";
import prisma from "@/lib/db";
import { APP_CONSTANTS } from "@/lib/constants";
+import { isResumeFilePath } from "@/lib/resumeFiles";
import {
RESUME_IMPORT_SYSTEM_PROMPT,
buildResumeImportPrompt,
@@ -77,15 +78,11 @@ export const POST = async (req: NextRequest) => {
);
}
- // Assert path stays inside the uploads dir (no traversal)
- const resolvedPath = path.resolve(resume.File.filePath);
- const uploadsDir = path.resolve(APP_CONSTANTS.UPLOADS_DIR);
- if (
- !resolvedPath.startsWith(uploadsDir + path.sep) &&
- resolvedPath !== uploadsDir
- ) {
+ // UPLOADS_DIR also holds the database and backup snapshots
+ if (!isResumeFilePath(resume.File.filePath)) {
return NextResponse.json({ error: "Invalid file path" }, { status: 400 });
}
+ const resolvedPath = path.resolve(resume.File.filePath);
if (!fs.existsSync(resolvedPath)) {
return NextResponse.json(
diff --git a/src/app/api/profile/resume/route.ts b/src/app/api/profile/resume/route.ts
index 8b2bf4e..d225ee6 100644
--- a/src/app/api/profile/resume/route.ts
+++ b/src/app/api/profile/resume/route.ts
@@ -1,18 +1,21 @@
import { auth } from "@/auth";
import { NextRequest, NextResponse } from "next/server";
+import { editResume } from "@/actions/profile.actions";
import {
- createResumeProfile,
- deleteFile,
- editResume,
- uploadFile,
-} from "@/actions/profile.actions";
+ createResume,
+ replaceResumeFile,
+} from "@/actions/profile/resumeUpload";
import path from "path";
import fs from "fs";
-import { getTimestampedFileName } from "@/lib/utils";
import { APP_CONSTANTS } from "@/lib/constants";
import { PDF_MAGIC, ZIP_MAGIC } from "@/lib/ai/import/extract-text";
import { log } from "@/lib/telemetry";
import prisma from "@/lib/db";
+import {
+ isResumeFilePath,
+ saveResumeUpload,
+ type ResumeUpload,
+} from "@/lib/resumeFiles";
const ALLOWED_MIME = new Set<string>(APP_CONSTANTS.RESUME_ALLOWED_MIME_TYPES);
@@ -27,7 +30,6 @@ function validateFileBytes(buf: Buffer, mimeType: string): boolean {
export const POST = async (req: NextRequest) => {
const session = await auth();
const userId = session?.user?.id;
- let filePath;
try {
if (!session || !session.user) {
@@ -44,8 +46,8 @@ export const POST = async (req: NextRequest) => {
const title = formData.get("title") as string;
const file = formData.get("file") as File;
const resumeId = (formData.get("id") as string) ?? null;
- let fileId: string | undefined =
- (formData.get("fileId") as string) ?? undefined;
+ // fileId is not read: the replaced file comes from the owned resume row
+ let upload: ResumeUpload | undefined;
if (file && file.name && file.size > 0) {
// Server-side validation: size, MIME type, and magic bytes
@@ -60,33 +62,17 @@ export const POST = async (req: NextRequest) => {
return NextResponse.json({ error: "File content does not match declared type" }, { status: 400 });
}
- const uploadDir = path.join(APP_CONSTANTS.UPLOADS_DIR, "files", "resumes");
- const timestampedFileName = getTimestampedFileName(file.name);
- filePath = path.join(uploadDir, timestampedFileName);
- await uploadFile(file, uploadDir, filePath);
+ upload = await saveResumeUpload(file.name, fileBytes);
}
if (resumeId && title) {
- if (fileId && file?.name) {
- await deleteFile(fileId);
- fileId = undefined;
- }
-
- const res = await editResume(
- resumeId,
- title,
- fileId,
- file?.name,
- filePath
- );
+ const res = upload
+ ? await replaceResumeFile(resumeId, title, upload)
+ : await editResume(resumeId, title);
return NextResponse.json(res, { status: 200 });
}
- const response = await createResumeProfile(
- title,
- file.name ?? null,
- filePath
- );
+ const response = await createResume(title, upload);
return NextResponse.json(response, { status: 201 });
} catch (error) {
log.error("[Resume] Upload failed", { error: String(error) });
@@ -135,22 +121,15 @@ export const GET = async (req: NextRequest) => {
select: { File: { select: { filePath: true } } },
});
- // Not UPLOADS_DIR itself: it also holds backup snapshots and the database
- const resumesDir = path.resolve(
- APP_CONSTANTS.UPLOADS_DIR,
- "files",
- "resumes"
- );
- const fullFilePath = resume?.File?.filePath
- ? path.resolve(resume.File.filePath)
- : null;
+ const storedPath = resume?.File?.filePath;
if (
- !fullFilePath ||
- !fullFilePath.startsWith(resumesDir + path.sep) ||
- !fs.existsSync(fullFilePath)
+ !storedPath ||
+ !isResumeFilePath(storedPath) ||
+ !fs.existsSync(path.resolve(storedPath))
) {
return NextResponse.json({ error: "File not found" }, { status: 404 });
}
+ const fullFilePath = path.resolve(storedPath);
const fileType = path.extname(fullFilePath).toLowerCase();
const fileName = path.basename(fullFilePath);
diff --git a/src/lib/backup/export.ts b/src/lib/backup/export.ts
index 954a2b7..ebe00fb 100644
--- a/src/lib/backup/export.ts
+++ b/src/lib/backup/export.ts
@@ -5,6 +5,7 @@ import db from "@/lib/db";
import { INSERT_ORDER, MODEL_SPECS, type BackupModel } from "./ordering";
import { BackupDataSchema, type BackupData } from "./schema";
import { buildManifest } from "./manifest";
+import { isResumeFilePath } from "@/lib/resumeFiles";
type Row = Record<string, unknown>;
@@ -105,6 +106,11 @@ export async function buildBackupZip(
// the snapshot whose bytes land later is covered by the fileMissing marker.
const zip = new JSZip();
for (const file of data.File) {
+ // A stored path outside the resumes directory is never read into the zip
+ if (!isResumeFilePath(file.filePath)) {
+ file.fileMissing = true;
+ continue;
+ }
try {
const bytes = await fs.readFile(file.filePath);
zip.file(`files/${file.id}/${path.basename(file.filePath)}`, bytes);
diff --git a/src/lib/backup/import.ts b/src/lib/backup/import.ts
index 4dea1ca..2f53db7 100644
--- a/src/lib/backup/import.ts
+++ b/src/lib/backup/import.ts
@@ -22,6 +22,7 @@ import {
} from "./ordering";
import { writeSnapshot } from "./snapshot";
import { log } from "@/lib/telemetry";
+import { isResumeFilePath } from "@/lib/resumeFiles";
import { BackupDataSchema, type BackupData, type BackupManifest } from "./schema";
export interface PreflightResult {
@@ -395,6 +396,12 @@ export async function importBackup(
// resume files in UPLOADS_DIR forever with no row pointing at them.
for (const filePath of oldFilePaths) {
if (writtenPaths.includes(filePath)) continue;
+ if (!isResumeFilePath(filePath)) {
+ log.warn("[Backup] Skipped removing a file outside the resumes directory", {
+ "file.path": filePath,
+ });
+ continue;
+ }
await fs.unlink(filePath).catch((error) => {
log.warn("[Backup] Could not remove replaced file", {
"file.path": filePath,
diff --git a/src/lib/resumeFiles.ts b/src/lib/resumeFiles.ts
new file mode 100644
index 0000000..6cedb72
--- /dev/null
+++ b/src/lib/resumeFiles.ts
@@ -0,0 +1,50 @@
+import fs from "fs/promises";
+import path from "path";
+import { APP_CONSTANTS } from "@/lib/constants";
+import { getTimestampedFileName } from "@/lib/utils";
+import { log } from "@/lib/telemetry";
+
+export interface ResumeUpload {
+ fileName: string;
+ filePath: string;
+}
+
+// A function, not a constant: tests override UPLOADS_DIR at runtime.
+// Never UPLOADS_DIR itself — it also holds the database and backups.
+export function resumesDir(): string {
+ return path.resolve(APP_CONSTANTS.UPLOADS_DIR, "files", "resumes");
+}
+
+// The trailing separator keeps a sibling such as resumes-old from passing
+export function isResumeFilePath(filePath: string): boolean {
+ return path.resolve(filePath).startsWith(resumesDir() + path.sep);
+}
+
+// The path is built here and never taken from a caller
+export async function saveResumeUpload(
+ fileName: string,
+ bytes: Uint8Array,
+): Promise<ResumeUpload> {
+ const dir = path.join(APP_CONSTANTS.UPLOADS_DIR, "files", "resumes");
+ await fs.mkdir(dir, { recursive: true });
+ const filePath = path.join(dir, getTimestampedFileName(fileName));
+ await fs.writeFile(filePath, bytes);
+ return { fileName, filePath };
+}
+
+// Never throws: callers run it after a commit that must not be undone
+export async function removeResumeFile(filePath: string): Promise<void> {
+ if (!isResumeFilePath(filePath)) {
+ log.warn("[Resume] Skipped unlinking a path outside the resumes directory", {
+ "file.path": filePath,
+ });
+ return;
+ }
+ await fs.unlink(filePath).catch((error: NodeJS.ErrnoException) => {
+ if (error.code === "ENOENT") return;
+ log.warn("[Resume] Could not remove file", {
+ "file.path": filePath,
+ error: String(error),
+ });
+ });
+}