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
test: add real-database round-trip, rollback coverage and e2e for data backup; align settings card title size
Khuram Niazc3249b832ee5
diff --git a/__tests__/backupRoundTrip.spec.ts b/__tests__/backupRoundTrip.spec.tsnew file mode 100644index 0000000..19c6d6f--- /dev/null+++ b/__tests__/backupRoundTrip.spec.ts@@ -0,0 +1,378 @@+// @vitest-environment node+import fs from "fs";+import path from "path";+import { PrismaClient } from "@prisma/client";+import { APP_CONSTANTS } from "@/lib/constants";+import { buildBackupZip } from "@/lib/backup/export";+import { importBackup } from "@/lib/backup/import";+import { listSnapshots, readSnapshot } from "@/lib/backup/snapshot";+import { seedAccount } from "./helpers/backupTestDb";++// Async so the helper can be pulled in with a dynamic import — `require` is+// not defined in a Vite-transformed ESM test file.+const ctx = await vi.hoisted(async () => {+ const helpers = await import("./helpers/backupTestDb");+ const { url, dir } = helpers.makeTestDbUrl();+ helpers.pushSchema(url);+ return { url, dir };+});++vi.mock("@/lib/db", async () => {+ const { PrismaClient } = await import("@prisma/client");+ return {+ default: new PrismaClient({ datasources: { db: { url: ctx.url } } }),+ };+});++// Never start the cron in a test run.+vi.mock("@/lib/scheduler", () => ({ syncSchedulerState: vi.fn() }));++const prisma = new PrismaClient({ datasources: { db: { url: ctx.url } } });++let userId: string;+let uploadsDir: string;+const originalUploads = APP_CONSTANTS.UPLOADS_DIR;++beforeAll(async () => {+ uploadsDir = path.join(ctx.dir, "uploads");+ fs.mkdirSync(path.join(uploadsDir, "files", "resumes"), { recursive: true });+ (APP_CONSTANTS as { UPLOADS_DIR: string }).UPLOADS_DIR = uploadsDir;++ userId = await seedAccount(prisma, "[email protected]");+ await seedFullAccount();+}, 120_000);++afterAll(async () => {+ (APP_CONSTANTS as { UPLOADS_DIR: string }).UPLOADS_DIR = originalUploads;+ await prisma.$disconnect();+ fs.rmSync(ctx.dir, { recursive: true, force: true });+});++async function seedFullAccount() {+ const company = await prisma.company.create({+ data: { label: "Acme", value: "acme", createdBy: userId },+ });+ const title = await prisma.jobTitle.create({+ data: { label: "Engineer", value: "engineer", createdBy: userId },+ });+ const tag = await prisma.tag.create({+ data: { label: "Remote", value: "remote", createdBy: userId },+ });+ const status = await prisma.jobStatus.findFirstOrThrow({ where: { value: "applied" } });++ const profile = await prisma.profile.create({ data: { userId } });++ const resumeFilePath = path.join(uploadsDir, "files", "resumes", "seed-resume.pdf");+ fs.writeFileSync(resumeFilePath, Buffer.from("%PDF-1.4 seed"));+ const file = await prisma.file.create({+ data: {+ fileName: "resume.pdf",+ filePath: resumeFilePath,+ fileType: "application/pdf",+ },+ });+ const resume = await prisma.resume.create({+ data: { profileId: profile.id, title: "My CV", FileId: file.id },+ });+ await prisma.contactInfo.create({+ data: {+ resumeId: resume.id,+ firstName: "A",+ lastName: "B",+ headline: "Engineer",+ email: "[email protected]",+ phone: "123",+ },+ });+ const summary = await prisma.summary.create({ data: { content: "Summary text" } });+ const section = await prisma.resumeSection.create({+ data: {+ resumeId: resume.id,+ sectionTitle: "Summary",+ sectionType: "summary",+ summaryId: summary.id,+ },+ });+ await prisma.skill.create({+ data: { tagId: tag.id, resumeSectionId: section.id, category: "Languages", order: 1 },+ });+ await prisma.user.update({+ where: { id: userId },+ data: { defaultResumeId: resume.id },+ });++ const job = await prisma.job.create({+ data: {+ userId,+ description: "A job",+ jobType: "full-time",+ createdAt: new Date(),+ statusId: status.id,+ jobTitleId: title.id,+ companyId: company.id,+ tags: { connect: { id: tag.id } },+ },+ });+ await prisma.note.create({+ data: { jobId: job.id, userId, content: "a note" },+ });++ const question = await prisma.question.create({+ data: { question: "Why us?", createdBy: userId, tags: { connect: { id: tag.id } } },+ });+ expect(question.id).toBeTruthy();++ const activityType = await prisma.activityType.create({+ data: { label: "Applying", value: "applying", createdBy: userId },+ });+ const task = await prisma.task.create({+ data: { userId, title: "Apply to Acme", activityTypeId: activityType.id },+ });+ await prisma.activity.create({+ data: {+ userId,+ activityName: "Applying",+ startTime: new Date(),+ activityTypeId: activityType.id,+ taskId: task.id,+ },+ });++ const automation = await prisma.automation.create({+ data: {+ userId,+ name: "Nightly",+ jobBoard: "greenhouse",+ keywords: "engineer",+ location: "Remote",+ resumeId: resume.id,+ scheduleHour: 9,+ nextRunAt: new Date("2020-01-01T09:00:00"),+ status: "active",+ },+ });+ // A run left mid-flight in the backup, which must not survive as running.+ await prisma.automationRun.create({+ data: { automationId: automation.id, status: "cancelling" },+ });++ // Rows the wipe must not touch, and one it must.+ await prisma.apiKey.create({+ data: { userId, provider: "openai", encryptedKey: "e", iv: "i", last4: "1234" },+ });+ await prisma.mcpAccessToken.create({+ data: {+ userId,+ name: "cli",+ tokenHash: "hash",+ tokenPrefix: "js_",+ scopes: "[]",+ expiresAt: new Date(Date.now() + 86_400_000),+ },+ });+ await prisma.chatConversation.create({+ data: { userId, messages: "[]" },+ });+}++describe("backup round trip", () => {+ it("restores every row, relation and file over an existing account", async () => {+ const { buffer } = await buildBackupZip(userId, "[email protected]");++ // Add a lookup the backup does not contain, so replace-not-merge is testable.+ await prisma.company.create({+ data: { label: "Ghost", value: "ghost", createdBy: userId },+ });++ // The in-flight run in the backup must not block the target-side guard, so+ // clear the target's own run first — the guard is asserted separately.+ await prisma.automationRun.updateMany({+ where: { status: { in: ["running", "cancelling"] } },+ data: { status: "failed", completedAt: new Date() },+ });++ const result = await importBackup(buffer, userId, "[email protected]", true);++ expect(result.counts.Job).toBe(1);+ expect(result.filesWritten).toBe(1);++ // The safety net exists on disk and is a real, readable backup.+ expect(result.snapshotPath).toBeTruthy();+ expect(fs.existsSync(result.snapshotPath!)).toBe(true);+ expect(result.snapshotPath!.startsWith(path.join(uploadsDir, "backups", userId))).toBe(+ true,+ );++ // Lookups are replaced, not merged.+ const companies = await prisma.company.findMany({ where: { createdBy: userId } });+ expect(companies.map((c) => c.value).sort()).toEqual(["acme"]);++ // Tag associations survive on both sides.+ const job = await prisma.job.findFirstOrThrow({+ where: { userId },+ include: { tags: true, Company: true, Status: true, Notes: true },+ });+ expect(job.tags.map((t) => t.value)).toEqual(["remote"]);+ expect(job.Company.label).toBe("Acme");+ expect(job.Status.value).toBe("applied");+ expect(job.Notes).toHaveLength(1);++ const question = await prisma.question.findFirstOrThrow({+ where: { createdBy: userId },+ include: { tags: true },+ });+ expect(question.tags.map((t) => t.value)).toEqual(["remote"]);++ // Summary ordering: the section imported with its summary attached.+ const section = await prisma.resumeSection.findFirstOrThrow({+ where: { Resume: { profile: { userId } } },+ include: { summary: true, skills: { include: { Tag: true } } },+ });+ expect(section.summary?.content).toBe("Summary text");+ expect(section.skills[0].Tag.value).toBe("remote");++ // defaultResumeId points at the new resume, not the old id.+ const user = await prisma.user.findUniqueOrThrow({ where: { id: userId } });+ const resume = await prisma.resume.findFirstOrThrow({+ where: { profile: { userId } },+ });+ expect(user.defaultResumeId).toBe(resume.id);++ // Activity -> Task survived.+ const activity = await prisma.activity.findFirstOrThrow({+ where: { userId },+ include: { task: true },+ });+ expect(activity.task?.title).toBe("Apply to Acme");++ // In-flight state normalized on the way in.+ const run = await prisma.automationRun.findFirstOrThrow({+ where: { automation: { userId } },+ });+ expect(run.status).toBe("failed");+ expect(run.errorMessage).toBe("interrupted");++ const automation = await prisma.automation.findFirstOrThrow({ where: { userId } });+ expect(automation.status).toBe("active");+ expect(automation.nextRunAt!.getTime()).toBeGreaterThan(Date.now());++ // The wipe set is honoured in both directions.+ expect(await prisma.apiKey.count({ where: { userId } })).toBe(1);+ expect(await prisma.mcpAccessToken.count({ where: { userId } })).toBe(1);+ expect(await prisma.chatConversation.count({ where: { userId } })).toBe(0);++ // filePath was recomputed and the bytes are actually there.+ const file = await prisma.file.findFirstOrThrow({+ where: { Resume: { profile: { userId } } },+ });+ expect(file.filePath.startsWith(path.join(uploadsDir, "files", "resumes"))).toBe(+ true,+ );+ expect(fs.existsSync(file.filePath)).toBe(true);+ expect(fs.readFileSync(file.filePath).toString()).toContain("seed");+ }, 120_000);++ it("does not demand confirmWipe on a freshly signed-up account", async () => {+ const freshUserId = await seedAccount(prisma, "[email protected]");+ const { buffer } = await buildBackupZip(userId, "[email protected]");++ // No confirmWipe: the seeded JobSource rows must not count as data.+ const result = await importBackup(+ buffer,+ freshUserId,+ "[email protected]",+ false,+ );+ // Nothing to snapshot on an empty account.+ expect(result.snapshotPath).toBeNull();+ }, 120_000);++ it("rolls back to the snapshot an import took", async () => {+ const rollbackUserId = await seedAccount(prisma, "[email protected]");+ // A content row, not just the lookup below: EMPTINESS_MODELS deliberately+ // excludes lookup models, so a Company alone would read as an empty target+ // and importBackup would skip the snapshot this test is asserting on.+ await prisma.profile.create({ data: { userId: rollbackUserId } });+ await prisma.company.create({+ data: { label: "Before", value: "before", createdBy: rollbackUserId },+ });++ // Import someone else's backup over it, then undo that.+ const { buffer } = await buildBackupZip(userId, "[email protected]");+ const imported = await importBackup(+ buffer,+ rollbackUserId,+ "[email protected]",+ true,+ );+ expect(imported.snapshotPath).toBeTruthy();+ expect(+ (await prisma.company.findMany({ where: { createdBy: rollbackUserId } }))+ .map((c) => c.value),+ ).not.toContain("before");++ const snapshots = await listSnapshots(rollbackUserId);+ const bytes = await readSnapshot(rollbackUserId, snapshots[0].id);+ await importBackup(bytes, rollbackUserId, "[email protected]", true);++ const after = await prisma.company.findMany({+ where: { createdBy: rollbackUserId },+ });+ expect(after.map((c) => c.value)).toEqual(["before"]);+ }, 120_000);++ // The regression test for the file gate. A tampered backup is the realistic+ // hostile input for this feature: the zip is structurally valid and the rows+ // are fine, but a file entry has been swapped for something that is not a+ // resume. The row must survive and the bytes must not reach disk.+ it("drops a file entry whose bytes are not a resume, without failing the import", async () => {+ const { buffer } = await buildBackupZip(userId, "[email protected]");++ const JSZip = (await import("jszip")).default;+ const zip = await JSZip.loadAsync(buffer);+ // Directory entries (e.g. "files/") also start with the prefix and sort+ // before the real file entry in JSZip's insertion order — exclude them.+ const entryName = Object.keys(zip.files).find(+ (n) => n.startsWith("files/") && !zip.files[n].dir,+ )!;+ zip.file(entryName, Buffer.from("MZ\x90\x00 definitely not a PDF"));+ const tampered = await zip.generateAsync({ type: "nodebuffer" });++ await prisma.automationRun.updateMany({+ where: { status: { in: ["running", "cancelling"] } },+ data: { status: "failed", completedAt: new Date() },+ });++ const result = await importBackup(tampered, userId, "[email protected]", true);++ expect(result.filesWritten).toBe(0);+ expect(result.counts.File).toBe(1);++ const file = await prisma.file.findFirstOrThrow({+ where: { Resume: { profile: { userId } } },+ });+ expect(fs.existsSync(file.filePath)).toBe(false);++ // Nothing outside the resumes directory was created either.+ const resumesDir = path.join(uploadsDir, "files", "resumes");+ expect(file.filePath.startsWith(resumesDir)).toBe(true);+ expect(+ fs.readdirSync(resumesDir).some((n) => n.includes("MZ") || n.endsWith(".exe")),+ ).toBe(false);+ }, 120_000);++ it("refuses before any write when the target has an active run", async () => {+ const automation = await prisma.automation.findFirstOrThrow({ where: { userId } });+ await prisma.automationRun.create({+ data: { automationId: automation.id, status: "running" },+ });++ const { buffer } = await buildBackupZip(userId, "[email protected]");+ const jobsBefore = await prisma.job.count({ where: { userId } });++ await expect(+ importBackup(buffer, userId, "[email protected]", true),+ ).rejects.toThrow(/wait/i);+ expect(await prisma.job.count({ where: { userId } })).toBe(jobsBefore);+ }, 120_000);+});diff --git a/__tests__/helpers/backupTestDb.ts b/__tests__/helpers/backupTestDb.tsnew file mode 100644index 0000000..2ee684e--- /dev/null+++ b/__tests__/helpers/backupTestDb.ts@@ -0,0 +1,49 @@+import fs from "fs";+import os from "os";+import path from "path";+import { execFileSync } from "child_process";+import { randomUUID } from "crypto";+import type { PrismaClient } from "@prisma/client";+import { JOB_SOURCES, JOB_STATUSES } from "@/lib/constants";++export function makeTestDbUrl(): { url: string; dir: string } {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "jobsync-backup-"));+ return { url: `file:${path.join(dir, "test.db")}`, dir };+}++// db push rather than migrate deploy: the round-trip asserts against the+// current schema, not the migration history, and push is much faster.+export function pushSchema(url: string): void {+ execFileSync(+ "npx",+ ["prisma", "db", "push", "--skip-generate", "--accept-data-loss"],+ { env: { ...process.env, DATABASE_URL: url }, stdio: "pipe" },+ );+}++// Mirrors what signup() seeds, so "empty account" means the same thing here as+// it does in the app.+export async function seedAccount(+ prisma: PrismaClient,+ email: string,+): Promise<string> {+ for (const status of JOB_STATUSES) {+ await prisma.jobStatus.upsert({+ where: { value: status.value },+ update: {},+ create: { label: status.label, value: status.value },+ });+ }++ const user = await prisma.user.create({+ data: { id: randomUUID(), name: "Test User", email, password: "x" },+ });++ for (const source of JOB_SOURCES) {+ await prisma.jobSource.create({+ data: { label: source.label, value: source.value, createdBy: user.id },+ });+ }++ return user.id;+}diff --git a/e2e/backup.spec.ts b/e2e/backup.spec.tsnew file mode 100644index 0000000..4fd71df--- /dev/null+++ b/e2e/backup.spec.ts@@ -0,0 +1,55 @@+import { test, expect } from "./fixtures";++test.describe("data backup", () => {+ test("exports a non-empty zip", async ({ page }) => {+ await page.goto("/dashboard/settings");+ await page.getByRole("button", { name: "Data" }).click();++ const downloadPromise = page.waitForEvent("download");+ await page.getByRole("link", { name: /download backup/i }).click();+ const download = await downloadPromise;++ expect(download.suggestedFilename()).toMatch(/^jobsync-backup-\d{4}-\d{2}-\d{2}\.zip$/);+ const stream = await download.createReadStream();+ const chunks: Buffer[] = [];+ for await (const chunk of stream) chunks.push(chunk as Buffer);+ const bytes = Buffer.concat(chunks);+ expect(bytes.length).toBeGreaterThan(100);+ // Local file header signature.+ expect(bytes.subarray(0, 2).toString()).toBe("PK");+ });++ // Stops at the confirmation on purpose: committing an import here would wipe+ // the shared dev account every other spec depends on.+ test("previews a backup without touching anything and requires confirmation", async ({+ page,+ }) => {+ await page.goto("/dashboard/settings");+ await page.getByRole("button", { name: "Data" }).click();++ const downloadPromise = page.waitForEvent("download");+ await page.getByRole("link", { name: /download backup/i }).click();+ const download = await downloadPromise;+ const zipPath = await download.path();++ await page.getByLabel(/backup file/i).setInputFiles(zipPath!);++ await expect(page.getByText(/exported/i)).toBeVisible();+ await expect(+ page.getByRole("button", { name: /replace my data with this backup/i }),+ ).toBeVisible();++ await page+ .getByRole("button", { name: /replace my data with this backup/i })+ .click();+ await expect(+ page.getByRole("heading", { name: /delete this account's data\?/i }),+ ).toBeVisible();++ // Cancel — nothing is imported.+ await page.getByRole("button", { name: /^cancel$/i }).click();+ await expect(+ page.getByRole("heading", { name: /delete this account's data\?/i }),+ ).toBeHidden();+ });+});diff --git a/src/components/settings/DataSettings.tsx b/src/components/settings/DataSettings.tsxindex 7ab6268..810c3fe 100644--- a/src/components/settings/DataSettings.tsx+++ b/src/components/settings/DataSettings.tsx@@ -176,7 +176,7 @@ export default function DataSettings() {<div className="space-y-4"><Card><CardHeader>- <CardTitle>Export your data</CardTitle>+ <CardTitle className="text-lg font-medium">Export your data</CardTitle><CardDescription>Downloads one zip with every job, resume, task, activity and question onthis account, plus your uploaded resume files.@@ -199,7 +199,7 @@ export default function DataSettings() {<Card><CardHeader>- <CardTitle>Import a backup</CardTitle>+ <CardTitle className="text-lg font-medium">Import a backup</CardTitle><CardDescription>Replaces everything on this account with the contents of the backup.Your API keys and MCP tokens are left alone; the agent chat history is@@ -268,7 +268,7 @@ export default function DataSettings() {{snapshots.length > 0 && (<Card><CardHeader>- <CardTitle>Undo an import</CardTitle>+ <CardTitle className="text-lg font-medium">Undo an import</CardTitle><CardDescription>Every import saves your previous data first. If you imported thewrong file, restore the snapshot from just before it.diff --git a/src/components/settings/McpAccessSettings.tsx b/src/components/settings/McpAccessSettings.tsxindex e621c0b..65166e5 100644--- a/src/components/settings/McpAccessSettings.tsx+++ b/src/components/settings/McpAccessSettings.tsx@@ -211,7 +211,7 @@ export default function McpAccessSettings() {<Card><CardHeader>- <CardTitle>MCP Endpoint</CardTitle>+ <CardTitle className="text-lg font-medium">MCP Endpoint</CardTitle><CardDescription>Connect AI agents to JobSync via the Model Context Protocol.</CardDescription></CardHeader><CardContent>@@ -228,7 +228,7 @@ export default function McpAccessSettings() {<Card><CardHeader className="flex-row flex-wrap items-start justify-between gap-2"><div className="min-w-0">- <CardTitle>Personal Access Tokens</CardTitle>+ <CardTitle className="text-lg font-medium">Personal Access Tokens</CardTitle><CardDescription>Tokens authenticate external agents to call MCP tools.</CardDescription></div><Button size="sm" className="shrink-0" onClick={() => setShowGenerateDialog(true)} disabled={isLoading}>