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.
TypeScript ai-agentai-resume-analyzerapplication-trackerapplication-tracking-systematscareerjob-applicationjob-automationjob-huntingjob-searchjob-seeker-toolsjob-trackerjob-trackingjobsearchjobseekersmcpollamaresumeresume-reviewself-hosted
fix(security): check ownership of job and contact reference ids; download resume files by resume id
Khuram Niaz9ebb70040cf9
diff --git a/__tests__/contact.actions.spec.ts b/__tests__/contact.actions.spec.tsindex 4f73072..86e2da7 100644--- a/__tests__/contact.actions.spec.ts+++ b/__tests__/contact.actions.spec.ts@@ -18,6 +18,9 @@ vi.mock("@/lib/db", () => ({updateMany: vi.fn(),deleteMany: vi.fn(),},+ company: { count: vi.fn() },+ location: { count: vi.fn() },+ contactRole: { count: vi.fn() },},}));@@ -32,6 +35,9 @@ describe("contact actions", () => {(getCurrentUser as any).mockResolvedValue(user);db.contact.findMany.mockResolvedValue([]);db.contact.count.mockResolvedValue(0);+ db.company.count.mockResolvedValue(1);+ db.location.count.mockResolvedValue(1);+ db.contactRole.count.mockResolvedValue(1);});describe("getContactList", () => {@@ -121,6 +127,79 @@ describe("contact actions", () => {});});+ describe("reference ownership", () => {+ const values = {+ name: "Dave",+ company: "co-1",+ workedAtCompany: "co-2",+ location: "loc-1",+ contactRole: "role-1",+ } as any;++ it("counts each referenced id against the caller", async () => {+ db.company.count.mockResolvedValue(2);+ db.contact.create.mockResolvedValue({ id: "c1" });++ const res = await createContact(values);++ expect(res.success).toBe(true);+ expect(db.company.count).toHaveBeenCalledWith({+ where: { id: { in: ["co-1", "co-2"] }, createdBy: user.id },+ });+ expect(db.location.count).toHaveBeenCalledWith({+ where: { id: "loc-1", createdBy: user.id },+ });+ expect(db.contactRole.count).toHaveBeenCalledWith({+ where: { id: "role-1", createdBy: user.id },+ });+ });++ it("counts a company used for both fields once", async () => {+ db.contact.create.mockResolvedValue({ id: "c1" });++ const res = await createContact({ ...values, workedAtCompany: "co-1" });++ expect(res.success).toBe(true);+ expect(db.company.count.mock.calls[0][0].where.id).toEqual({+ in: ["co-1"],+ });+ });++ it.each([+ ["company", "company", 1, "Company not found"],+ ["location", "location", 0, "Location not found"],+ ["role", "contactRole", 0, "Role not found"],+ ])(+ "create rejects another user's %s",+ async (_label, model, count, message) => {+ db.company.count.mockResolvedValue(2);+ db[model].count.mockResolvedValue(count);++ const res = await createContact(values);++ expect(res).toEqual({ success: false, message });+ expect(db.contact.create).not.toHaveBeenCalled();+ },+ );++ it.each([+ ["company", "company", 1, "Company not found"],+ ["location", "location", 0, "Location not found"],+ ["role", "contactRole", 0, "Role not found"],+ ])(+ "update rejects another user's %s before writing",+ async (_label, model, count, message) => {+ db.company.count.mockResolvedValue(2);+ db[model].count.mockResolvedValue(count);++ const res = await updateContact({ ...values, id: "c1" });++ expect(res).toEqual({ success: false, message });+ expect(db.contact.updateMany).not.toHaveBeenCalled();+ },+ );+ });+describe("deleteContactById", () => {it("deletes only the caller's contact", async () => {db.contact.deleteMany.mockResolvedValue({ count: 1 });diff --git a/__tests__/job.actions.spec.ts b/__tests__/job.actions.spec.tsindex 4346f16..20703bf 100644--- a/__tests__/job.actions.spec.ts+++ b/__tests__/job.actions.spec.ts@@ -29,10 +29,12 @@ vi.mock("@prisma/client", () => {findMany: vi.fn(),findFirst: vi.fn(),create: vi.fn(),+ count: vi.fn(),},job: {findMany: vi.fn(),findUnique: vi.fn(),+ findFirst: vi.fn(),count: vi.fn(),create: vi.fn(),update: vi.fn(),@@ -43,7 +45,13 @@ vi.mock("@prisma/client", () => {findFirst: vi.fn(),create: vi.fn(),update: vi.fn(),+ count: vi.fn(),},+ jobTitle: { count: vi.fn() },+ company: { count: vi.fn() },+ resume: { count: vi.fn() },+ coverLetter: { count: vi.fn() },+ tag: { count: vi.fn() },};return {PrismaClient: vi.fn(function () {@@ -81,8 +89,20 @@ describe("jobActions", () => {resume: "",tags: [],};+ const refModels = [+ "jobTitle",+ "company",+ "location",+ "jobSource",+ "resume",+ "coverLetter",+ "tag",+ ];beforeEach(() => {vi.clearAllMocks();+ for (const model of refModels) {+ (prisma as any)[model].count.mockResolvedValue(1);+ }});describe("getStatusList", () => {it("should return status list on successful query", async () => {@@ -1041,8 +1061,148 @@ describe("jobActions", () => {message: "Not authenticated",});});+ it("counts each referenced id against the caller", async () => {+ (getCurrentUser as any).mockResolvedValue(mockUser);+ (prisma.job.create as any).mockResolvedValue(jobData);++ await addJob({+ ...jobData,+ resume: "resume-id",+ coverLetter: "letter-id",+ tags: ["tag-1", "tag-1"],+ });++ const db = prisma as any;+ const owned = { createdBy: mockUser.id };+ const inProfile = { profile: { userId: mockUser.id } };+ expect(db.jobTitle.count).toHaveBeenCalledWith({+ where: { id: "job-title-id", ...owned },+ });+ expect(db.company.count).toHaveBeenCalledWith({+ where: { id: "company-id", ...owned },+ });+ expect(db.location.count).toHaveBeenCalledWith({+ where: { id: "location-id", ...owned },+ });+ expect(db.jobSource.count).toHaveBeenCalledWith({+ where: { id: "source-id", ...owned },+ });+ expect(db.resume.count).toHaveBeenCalledWith({+ where: { id: "resume-id", ...inProfile },+ });+ expect(db.coverLetter.count).toHaveBeenCalledWith({+ where: { id: "letter-id", ...inProfile },+ });+ expect(db.tag.count).toHaveBeenCalledWith({+ where: { id: { in: ["tag-1"] }, ...owned },+ });+ expect(prisma.job.create).toHaveBeenCalledTimes(1);+ });+ it.each([+ ["company", {}, "Company not found"],+ ["resume", { resume: "resume-id" }, "Resume not found"],+ ["coverLetter", { coverLetter: "letter-id" }, "Cover letter not found"],+ ])("rejects another user's %s", async (model, overrides, message) => {+ (getCurrentUser as any).mockResolvedValue(mockUser);+ (prisma as any)[model].count.mockResolvedValue(0);++ const result = await addJob({ ...jobData, ...overrides });++ expect(result).toStrictEqual({ success: false, message });+ expect(prisma.job.create).not.toHaveBeenCalled();+ });+ it("rejects a tag list that includes another user's tag", async () => {+ (getCurrentUser as any).mockResolvedValue(mockUser);++ const result = await addJob({ ...jobData, tags: ["tag-1", "tag-2"] });++ expect(result).toStrictEqual({ success: false, message: "Tag not found" });+ expect(prisma.job.create).not.toHaveBeenCalled();+ });+ it("skips the check for a resume that was not picked", async () => {+ (getCurrentUser as any).mockResolvedValue(mockUser);+ (prisma.job.create as any).mockResolvedValue(jobData);++ await addJob(jobData);++ expect((prisma as any).resume.count).not.toHaveBeenCalled();+ expect((prisma as any).tag.count).not.toHaveBeenCalled();+ });});describe("updateJob", () => {+ const currentRefs = {+ jobTitleId: "job-title-id",+ companyId: "company-id",+ locationId: "location-id",+ jobSourceId: "source-id",+ resumeId: null,+ coverLetterId: null,+ tags: [{ id: "tag-1" }],+ };+ beforeEach(() => {+ (prisma.job as any).findFirst.mockResolvedValue(currentRefs);+ });+ it("does not re-check ids the job already holds", async () => {+ (getCurrentUser as any).mockResolvedValue(mockUser);+ (prisma as any).jobSource.count.mockResolvedValue(0);+ (prisma.job.update as any).mockResolvedValue(jobData);++ const result = await updateJob({ ...jobData, tags: ["tag-1"] });++ expect(result.success).toBe(true);+ expect((prisma.job as any).findFirst.mock.calls[0][0].where).toEqual({+ id: "job-id",+ userId: mockUser.id,+ });+ expect((prisma as any).jobSource.count).not.toHaveBeenCalled();+ expect((prisma as any).company.count).not.toHaveBeenCalled();+ expect((prisma as any).tag.count).not.toHaveBeenCalled();+ });+ it("rejects a newly attached company the caller does not own", async () => {+ (getCurrentUser as any).mockResolvedValue(mockUser);+ (prisma as any).company.count.mockResolvedValue(0);++ const result = await updateJob({ ...jobData, company: "other-company" });++ expect(result).toStrictEqual({+ success: false,+ message: "Company not found",+ });+ expect(prisma.job.update).not.toHaveBeenCalled();+ });+ it.each([+ ["resume", { resume: "resume-id" }, "Resume not found"],+ ["coverLetter", { coverLetter: "letter-id" }, "Cover letter not found"],+ ])("rejects another user's %s", async (model, overrides, message) => {+ (getCurrentUser as any).mockResolvedValue(mockUser);+ (prisma as any)[model].count.mockResolvedValue(0);++ const result = await updateJob({ ...jobData, ...overrides });++ expect(result).toStrictEqual({ success: false, message });+ expect(prisma.job.update).not.toHaveBeenCalled();+ });+ it("checks only the tags being added", async () => {+ (getCurrentUser as any).mockResolvedValue(mockUser);+ (prisma as any).tag.count.mockResolvedValue(0);++ const result = await updateJob({ ...jobData, tags: ["tag-1", "tag-2"] });++ expect((prisma as any).tag.count).toHaveBeenCalledWith({+ where: { id: { in: ["tag-2"] }, createdBy: mockUser.id },+ });+ expect(result).toStrictEqual({ success: false, message: "Tag not found" });+ expect(prisma.job.update).not.toHaveBeenCalled();+ });+ it("reports a job the caller does not own", async () => {+ (getCurrentUser as any).mockResolvedValue(mockUser);+ (prisma.job as any).findFirst.mockResolvedValue(null);++ const result = await updateJob(jobData);++ expect(result).toStrictEqual({ success: false, message: "Job not found" });+ expect(prisma.job.update).not.toHaveBeenCalled();+ });it("should update a job successfully", async () => {(getCurrentUser as any).mockResolvedValue(mockUser);(prisma.job.update as any).mockResolvedValue(jobData);diff --git a/__tests__/resume-download-route.spec.ts b/__tests__/resume-download-route.spec.tsnew file mode 100644index 0000000..89c6b4e--- /dev/null+++ b/__tests__/resume-download-route.spec.ts@@ -0,0 +1,100 @@+// Tests for GET /api/profile/resume: the file is found through the caller's+// own resume row, never through a client-supplied path.+import path from "path";++const { existsSync, readFileSync } = vi.hoisted(() => ({+ existsSync: vi.fn(),+ readFileSync: vi.fn(),+}));++vi.mock("fs", () => ({+ default: { existsSync, readFileSync },+ existsSync,+ readFileSync,+}));++vi.mock("@/auth", () => ({ auth: vi.fn() }));++vi.mock("@/lib/db", () => ({+ default: { resume: { findUnique: vi.fn() } },+}));++vi.mock("next/server", () => ({+ NextResponse: class {+ status = 200;+ body: unknown;+ headers: Record<string, string>;+ constructor(body: unknown, init?: { headers?: Record<string, string> }) {+ this.body = body;+ this.headers = init?.headers ?? {};+ }+ static json(data: unknown, init?: { status?: number }) {+ return { status: init?.status ?? 200, json: async () => data };+ }+ },+}));++import { GET } from "@/app/api/profile/resume/route";+import { auth } from "@/auth";+import prisma from "@/lib/db";+import { APP_CONSTANTS } from "@/lib/constants";++const db = prisma as any;+const resumesDir = path.join(APP_CONSTANTS.UPLOADS_DIR, "files", "resumes");+const req = (query: string) =>+ ({ url: `http://localhost/api/profile/resume?${query}` }) as any;+const withFile = (filePath: string) =>+ db.resume.findUnique.mockResolvedValue({ File: { filePath } });++describe("GET /api/profile/resume", () => {+ beforeEach(() => {+ (auth as any).mockResolvedValue({ user: { id: "user-1" } });+ existsSync.mockReturnValue(true);+ readFileSync.mockReturnValue(Buffer.from("%PDF"));+ });++ it("streams the file attached to the caller's own resume", async () => {+ withFile(path.join(resumesDir, "cv.pdf"));++ const res: any = await GET(req("resumeId=r1"));++ expect(db.resume.findUnique).toHaveBeenCalledWith({+ where: { id: "r1", profile: { userId: "user-1" } },+ select: { File: { select: { filePath: true } } },+ });+ expect(res.status).toBe(200);+ expect(res.headers["Content-Disposition"]).toBe(+ 'attachment; filename="cv.pdf"',+ );+ });++ it("returns 404 for a resume the caller does not own", async () => {+ db.resume.findUnique.mockResolvedValue(null);++ const res: any = await GET(req("resumeId=someone-elses"));++ expect(res.status).toBe(404);+ expect(readFileSync).not.toHaveBeenCalled();+ });++ it("ignores a filePath query param", async () => {+ const res: any = await GET(req("filePath=%2Fdata%2Fsecret.pdf"));++ expect(res.status).toBe(400);+ expect(db.resume.findUnique).not.toHaveBeenCalled();+ expect(existsSync).not.toHaveBeenCalled();+ });++ it.each([+ path.join(APP_CONSTANTS.UPLOADS_DIR, "backups", "cv.pdf"),+ path.join(`${resumesDir}-old`, "cv.pdf"),+ "/etc/cv.pdf",+ ])("refuses a stored path outside the resumes directory: %s", async (filePath) => {+ withFile(filePath);++ const res: any = await GET(req("resumeId=r1"));++ expect(res.status).toBe(404);+ expect(readFileSync).not.toHaveBeenCalled();+ });+});diff --git a/src/actions/contact/mutations.ts b/src/actions/contact/mutations.tsindex 6226654..335f0e4 100644--- a/src/actions/contact/mutations.ts+++ b/src/actions/contact/mutations.ts@@ -26,13 +26,53 @@ const toContactData = (values: ContactFormValues) => ({lastContactedAt: values.lastContactedAt ?? null,});+// Foreign keys prove a row exists, not that the caller owns it, so every+// referenced id is counted against the caller before it is written.+const assertContactRefsOwned = async (+ userId: string,+ data: ReturnType<typeof toContactData>,+) => {+ const companyIds = [+ ...new Set(+ [data.companyId, data.workedAtCompanyId].filter(+ (id): id is string => !!id,+ ),+ ),+ ];++ const [companies, location, role] = await Promise.all([+ companyIds.length > 0+ ? prisma.company.count({+ where: { id: { in: companyIds }, createdBy: userId },+ })+ : 0,+ data.locationId+ ? prisma.location.count({+ where: { id: data.locationId, createdBy: userId },+ })+ : 1,+ data.roleId+ ? prisma.contactRole.count({+ where: { id: data.roleId, createdBy: userId },+ })+ : 1,+ ]);++ if (companies !== companyIds.length) throw new Error("Company not found");+ if (location === 0) throw new Error("Location not found");+ if (role === 0) throw new Error("Role not found");+};+export const createContact = async (values: ContactFormValues,): Promise<any | undefined> => {try {const user = await requireUser();+ const contactData = toContactData(values);+ await assertContactRefsOwned(user.id, contactData);+const data = await prisma.contact.create({- data: { ...toContactData(values), createdBy: user.id },+ data: { ...contactData, createdBy: user.id },});return { success: true, data };} catch (error) {@@ -47,11 +87,14 @@ export const updateContact = async (const user = await requireUser();if (!values.id) throw new Error("Please provide a contact id");+ const contactData = toContactData(values);+ await assertContactRefsOwned(user.id, contactData);+// updateMany, not update: a unique-where cannot carry createdBy, and a// count of 0 is how a contact belonging to someone else surfaces.const res = await prisma.contact.updateMany({where: { id: values.id, createdBy: user.id },- data: toContactData(values),+ data: contactData,});if (res.count === 0) throw new Error("Contact not found");diff --git a/src/actions/job/mutations.ts b/src/actions/job/mutations.tsindex 3bf6ded..10ac08e 100644--- a/src/actions/job/mutations.ts+++ b/src/actions/job/mutations.ts@@ -7,6 +7,59 @@ import { revalidatePath } from "next/cache";import { z } from "zod";import { requireUser } from "../shared";+type JobRefs = {+ jobTitleId?: string | null;+ companyId?: string | null;+ locationId?: string | null;+ jobSourceId?: string | null;+ resumeId?: string | null;+ coverLetterId?: string | null;+ tagIds?: string[];+};++// Foreign keys prove a row exists, not that the caller owns it, so every+// referenced id is counted against the caller before it is attached.+const assertJobRefsOwned = async (userId: string, refs: JobRefs) => {+ const owned = { createdBy: userId };+ const inProfile = { profile: { userId } };+ const tagIds = [...new Set(refs.tagIds ?? [])];++ const [title, company, location, source, resume, coverLetter, tags] =+ await Promise.all([+ refs.jobTitleId+ ? prisma.jobTitle.count({ where: { id: refs.jobTitleId, ...owned } })+ : 1,+ refs.companyId+ ? prisma.company.count({ where: { id: refs.companyId, ...owned } })+ : 1,+ refs.locationId+ ? prisma.location.count({ where: { id: refs.locationId, ...owned } })+ : 1,+ refs.jobSourceId+ ? prisma.jobSource.count({ where: { id: refs.jobSourceId, ...owned } })+ : 1,+ refs.resumeId+ ? prisma.resume.count({ where: { id: refs.resumeId, ...inProfile } })+ : 1,+ refs.coverLetterId+ ? prisma.coverLetter.count({+ where: { id: refs.coverLetterId, ...inProfile },+ })+ : 1,+ tagIds.length > 0+ ? prisma.tag.count({ where: { id: { in: tagIds }, ...owned } })+ : 0,+ ]);++ if (title === 0) throw new Error("Job title not found");+ if (company === 0) throw new Error("Company not found");+ if (location === 0) throw new Error("Location not found");+ if (source === 0) throw new Error("Job source not found");+ if (resume === 0) throw new Error("Resume not found");+ if (coverLetter === 0) throw new Error("Cover letter not found");+ if (tags !== tagIds.length) throw new Error("Tag not found");+};+export const addJob = async (data: z.infer<typeof AddJobFormSchema>,): Promise<any | undefined> => {@@ -32,6 +85,16 @@ export const addJob = async (tags,} = data;+ await assertJobRefsOwned(user.id, {+ jobTitleId: title,+ companyId: company,+ locationId: location,+ jobSourceId: source,+ resumeId: resume,+ coverLetterId: coverLetter,+ tagIds: tags,+ });+const job = await createJobRecord({jobTitleId: title,companyId: company,@@ -90,6 +153,37 @@ export const updateJob = async (const tagIds = tags ?? [];+ const current = await prisma.job.findFirst({+ where: { id, userId: user.id },+ select: {+ jobTitleId: true,+ companyId: true,+ locationId: true,+ jobSourceId: true,+ resumeId: true,+ coverLetterId: true,+ tags: { select: { id: true } },+ },+ });+ if (!current) {+ throw new Error("Job not found");+ }++ // Only newly attached ids are checked: migration 20260212202940 gave every+ // JobSource to the first user, so other users' older jobs must stay editable.+ const changed = (next?: string, prev?: string | null) =>+ next !== prev ? next : undefined;+ const currentTagIds = new Set(current.tags.map((tag) => tag.id));+ await assertJobRefsOwned(user.id, {+ jobTitleId: changed(title, current.jobTitleId),+ companyId: changed(company, current.companyId),+ locationId: changed(location, current.locationId),+ jobSourceId: changed(source, current.jobSourceId),+ resumeId: changed(resume, current.resumeId),+ coverLetterId: changed(coverLetter, current.coverLetterId),+ tagIds: tagIds.filter((tagId) => !currentTagIds.has(tagId)),+ });+const job = await prisma.job.update({where: {id,diff --git a/src/app/api/profile/resume/route.ts b/src/app/api/profile/resume/route.tsindex 3694e83..8b2bf4e 100644--- a/src/app/api/profile/resume/route.ts+++ b/src/app/api/profile/resume/route.ts@@ -12,6 +12,7 @@ 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";const ALLOWED_MIME = new Set<string>(APP_CONSTANTS.RESUME_ALLOWED_MIME_TYPES);@@ -107,7 +108,7 @@ export const GET = async (req: NextRequest) => {const userId = session?.user?.id;try {- if (!session || !session.user) {+ if (!session || !session.user || !userId) {return NextResponse.json({error: "Not Authenticated",@@ -119,17 +120,35 @@ export const GET = async (req: NextRequest) => {}const { searchParams } = new URL(req.url);- const filePath = searchParams.get("filePath");+ const resumeId = searchParams.get("resumeId");- if (!filePath) {+ if (!resumeId) {return NextResponse.json(- { error: "File path is required" },+ { error: "Resume id is required" },{ status: 400 });}- const fullFilePath = path.join(filePath);- if (!fs.existsSync(fullFilePath)) {+ // The path comes from the caller's own resume row, never from the client+ const resume = await prisma.resume.findUnique({+ where: { id: resumeId, profile: { userId } },+ 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;+ if (+ !fullFilePath ||+ !fullFilePath.startsWith(resumesDir + path.sep) ||+ !fs.existsSync(fullFilePath)+ ) {return NextResponse.json({ error: "File not found" }, { status: 404 });}diff --git a/src/components/myjobs/job-details/JobSummaryCard.tsx b/src/components/myjobs/job-details/JobSummaryCard.tsxindex cd86c36..47706cc 100644--- a/src/components/myjobs/job-details/JobSummaryCard.tsx+++ b/src/components/myjobs/job-details/JobSummaryCard.tsx@@ -94,6 +94,7 @@ export function JobSummaryCard({<div className="mt-1 font-medium">{job.Resume?.File?.filePath ? (DownloadFileButton(+ job.Resume.id!,job.Resume.File.filePath,job.Resume.title,job.Resume.File.fileName,diff --git a/src/components/profile/DownloadFileButton.tsx b/src/components/profile/DownloadFileButton.tsxindex 642a58a..9a2f728 100644--- a/src/components/profile/DownloadFileButton.tsx+++ b/src/components/profile/DownloadFileButton.tsx@@ -1,13 +1,14 @@import { Paperclip } from "lucide-react";export function DownloadFileButton(+ resumeId: string,filePath: any,fileTitle: string,fileName: string) {const handleDownload = async () => {const response = await fetch(- `/api/profile/resume?filePath=${encodeURIComponent(filePath)}`,+ `/api/profile/resume?resumeId=${encodeURIComponent(resumeId)}`,{method: "GET",headers: {diff --git a/src/components/profile/resume-container/ResumeHeader.tsx b/src/components/profile/resume-container/ResumeHeader.tsxindex c05fd54..bcb82fc 100644--- a/src/components/profile/resume-container/ResumeHeader.tsx+++ b/src/components/profile/resume-container/ResumeHeader.tsx@@ -46,6 +46,7 @@ export function ResumeHeader({<CardTitle>{resume.FileId && resume.File?.filePath? DownloadFileButton(+ resume.id!,resume.File?.filePath,title,resume.File?.fileName,