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.

feat: add destructive backup import with pre-import snapshot, wipe, ordered inserts and post-commit sync

Khuram Niazcf382299b4f9
diff --git a/__tests__/backupImportGuards.spec.ts b/__tests__/backupImportGuards.spec.ts
new file mode 100644
index 0000000..55fdf2d
--- /dev/null
+++ b/__tests__/backupImportGuards.spec.ts
@@ -0,0 +1,116 @@
+import JSZip from "jszip";
+import db from "@/lib/db";
+import { importBackup } from "@/lib/backup/import";
+import { BackupError, buildManifest } from "@/lib/backup/manifest";
+import { BackupDataSchema } from "@/lib/backup/schema";
+import { syncSchedulerState } from "@/lib/scheduler";
+import { writeSnapshot } from "@/lib/backup/snapshot";
+
+vi.mock("@/lib/scheduler", () => ({ syncSchedulerState: vi.fn() }));
+
+// Mocked so the guards spec never touches the filesystem; Task 4.1 covers the
+// real thing and Task 7.2 exercises it end to end.
+vi.mock("@/lib/backup/snapshot", () => ({
+ writeSnapshot: vi.fn().mockResolvedValue("data/backups/user-1/pre-import-x.zip"),
+}));
+
+vi.mock("@/lib/db", () => {
+ const counted = () => ({ count: vi.fn().mockResolvedValue(0), deleteMany: vi.fn(), createMany: vi.fn(), findMany: vi.fn().mockResolvedValue([]), create: vi.fn(), update: vi.fn(), upsert: vi.fn(), findFirst: vi.fn().mockResolvedValue(null) });
+ const mock: Record<string, unknown> = {
+ automationRun: { ...counted(), findFirst: vi.fn().mockResolvedValue(null) },
+ jobStatus: { findMany: vi.fn().mockResolvedValue([]), create: vi.fn() },
+ user: { update: vi.fn(), findUnique: vi.fn().mockResolvedValue({ defaultResumeId: null }) },
+ $transaction: vi.fn(async (fn: (tx: unknown) => Promise<unknown>) => fn(mock)),
+ };
+ for (const key of [
+ "company", "jobTitle", "location", "jobSource", "tag", "activityType",
+ "profile", "file", "resume", "contactInfo", "summary", "resumeSection",
+ "workExperience", "education", "licenseOrCertification", "otherSection",
+ "skill", "coverLetter", "automation", "job", "note", "interview",
+ "contact", "task", "activity", "question", "userSettings",
+ "chatConversation",
+ ]) {
+ mock[key] = counted();
+ }
+ return { default: mock };
+});
+
+const mockDb = db as unknown as Record<string, Record<string, ReturnType<typeof vi.fn>>>;
+
+async function emptyBackup(): Promise<Buffer> {
+ const data = BackupDataSchema.parse({});
+ const zip = new JSZip();
+ zip.file("manifest.json", JSON.stringify(buildManifest(data, "[email protected]")));
+ zip.file("data.json", JSON.stringify(data));
+ return zip.generateAsync({ type: "nodebuffer" });
+}
+
+const EMAIL = "[email protected]";
+
+describe("importBackup guards", () => {
+ it("refuses a non-empty target without confirmWipe", async () => {
+ mockDb.job.count.mockResolvedValueOnce(4);
+ await expect(
+ importBackup(await emptyBackup(), "user-1", EMAIL, false),
+ ).rejects.toThrow(/confirm/i);
+ expect(mockDb.job.deleteMany).not.toHaveBeenCalled();
+ });
+
+ it("refuses before any write when the target has a run in flight", async () => {
+ mockDb.automationRun.findFirst.mockResolvedValueOnce({ id: "run-1" });
+ await expect(
+ importBackup(await emptyBackup(), "user-1", EMAIL, true),
+ ).rejects.toThrow(/automation.*running|wait/i);
+ expect(mockDb.job.deleteMany).not.toHaveBeenCalled();
+ });
+
+ it("queries only running and cancelling runs for that guard", async () => {
+ await importBackup(await emptyBackup(), "user-1", EMAIL, true);
+ const where = mockDb.automationRun.findFirst.mock.calls[0][0].where;
+ expect(where.status).toEqual({ in: ["running", "cancelling"] });
+ expect(JSON.stringify(where)).toContain("user-1");
+ });
+
+ it("refuses a payload whose data.json fails validation", async () => {
+ const zip = new JSZip();
+ const data = BackupDataSchema.parse({});
+ zip.file("manifest.json", JSON.stringify(buildManifest(data, "[email protected]")));
+ zip.file("data.json", JSON.stringify({ Job: [{ id: "j1" }] }));
+ const bytes = await zip.generateAsync({ type: "nodebuffer" });
+ await expect(
+ importBackup(bytes, "user-1", EMAIL, true),
+ ).rejects.toBeInstanceOf(BackupError);
+ expect(mockDb.job.deleteMany).not.toHaveBeenCalled();
+ });
+
+ it("syncs the scheduler after a successful import", async () => {
+ await importBackup(await emptyBackup(), "user-1", EMAIL, true);
+ expect(syncSchedulerState).toHaveBeenCalled();
+ });
+
+ it("wipes ChatConversation but never ApiKey or McpAccessToken", async () => {
+ await importBackup(await emptyBackup(), "user-1", EMAIL, true);
+ expect(mockDb.chatConversation.deleteMany).toHaveBeenCalled();
+ expect(mockDb.apiKey).toBeUndefined();
+ expect(mockDb.mcpAccessToken).toBeUndefined();
+ });
+
+ // The ordering that makes the safety net real: a snapshot that is written
+ // after the wipe is a snapshot of nothing.
+ it("snapshots a non-empty target before deleting anything", async () => {
+ mockDb.job.count.mockResolvedValueOnce(4);
+ const result = await importBackup(await emptyBackup(), "user-1", EMAIL, true);
+
+ expect(writeSnapshot).toHaveBeenCalledWith("user-1", EMAIL);
+ expect(result.snapshotPath).toBeTruthy();
+ expect(
+ (writeSnapshot as ReturnType<typeof vi.fn>).mock.invocationCallOrder[0],
+ ).toBeLessThan(mockDb.job.deleteMany.mock.invocationCallOrder[0]);
+ });
+
+ it("skips the snapshot on an empty target", async () => {
+ const result = await importBackup(await emptyBackup(), "user-1", EMAIL, true);
+ expect(writeSnapshot).not.toHaveBeenCalled();
+ expect(result.snapshotPath).toBeNull();
+ });
+});
diff --git a/__tests__/backupOwnership.spec.ts b/__tests__/backupOwnership.spec.ts
new file mode 100644
index 0000000..d5b6e64
--- /dev/null
+++ b/__tests__/backupOwnership.spec.ts
@@ -0,0 +1,37 @@
+import { IdMap, buildCreateData } from "@/lib/backup/idmap";
+import { INSERT_ORDER, MODEL_SPECS } from "@/lib/backup/ordering";
+
+// A payload whose ownership columns are a foreign user's id. Every row must
+// come out scoped to the session user and none to the id in the file.
+describe("ownership rewrite", () => {
+ const FOREIGN = "user-from-another-instance";
+ const SESSION = "session-user";
+
+ it("never carries a foreign owner id into any model", () => {
+ const idMap = new IdMap();
+ idMap.mint("row-1");
+
+ for (const model of INSERT_ORDER) {
+ const spec = MODEL_SPECS[model];
+ const row: Record<string, unknown> = {
+ id: "row-1",
+ userId: FOREIGN,
+ createdBy: FOREIGN,
+ };
+ // Satisfy the model's foreign keys with self-references into the map.
+ for (const field of Object.keys(spec.fks)) row[field] = "row-1";
+
+ const data = buildCreateData(model, row, idMap, SESSION);
+
+ expect(JSON.stringify(data), `${model} leaked the foreign id`).not.toContain(
+ FOREIGN,
+ );
+ if (spec.owner) {
+ expect(data[spec.owner]).toBe(SESSION);
+ } else {
+ expect(data.userId).toBeUndefined();
+ expect(data.createdBy).toBeUndefined();
+ }
+ }
+ });
+});
diff --git a/__tests__/backupPreflight.spec.ts b/__tests__/backupPreflight.spec.ts
new file mode 100644
index 0000000..0da9442
--- /dev/null
+++ b/__tests__/backupPreflight.spec.ts
@@ -0,0 +1,83 @@
+import JSZip from "jszip";
+import db from "@/lib/db";
+import { preflightBackup } from "@/lib/backup/import";
+import { BackupError } from "@/lib/backup/manifest";
+import { BackupDataSchema } from "@/lib/backup/schema";
+import { buildManifest } from "@/lib/backup/manifest";
+
+vi.mock("@/lib/db", () => {
+ const counted = () => ({ count: vi.fn().mockResolvedValue(0) });
+ return {
+ default: {
+ profile: counted(),
+ resume: counted(),
+ coverLetter: counted(),
+ job: counted(),
+ note: counted(),
+ task: counted(),
+ activity: counted(),
+ question: counted(),
+ automation: counted(),
+ },
+ };
+});
+
+const mockDb = db as unknown as Record<string, { count: ReturnType<typeof vi.fn> }>;
+
+async function zipWith(manifest: unknown): Promise<Buffer> {
+ const zip = new JSZip();
+ zip.file("manifest.json", JSON.stringify(manifest));
+ zip.file("data.json", JSON.stringify(BackupDataSchema.parse({})));
+ return zip.generateAsync({ type: "nodebuffer" });
+}
+
+const manifest = () => buildManifest(BackupDataSchema.parse({}), "[email protected]");
+
+describe("preflightBackup", () => {
+ it("returns the manifest without writing anything", async () => {
+ const result = await preflightBackup(
+ await zipWith(manifest()),
+ "user-1",
+ );
+ expect(result.manifest.sourceEmail).toBe("[email protected]");
+ expect(result.emailMatches).toBe(true);
+ });
+
+ it("flags a source email that does not match the target account", async () => {
+ const result = await preflightBackup(
+ await zipWith(manifest()),
+ "user-1",
+ );
+ expect(result.emailMatches).toBe(false);
+ });
+
+ it("reports a freshly signed-up account as empty", async () => {
+ const result = await preflightBackup(
+ await zipWith(manifest()),
+ "user-1",
+ );
+ expect(result.targetIsEmpty).toBe(true);
+ expect(result.targetCounts.Job).toBe(0);
+ });
+
+ it("reports an account holding only a Profile as non-empty", async () => {
+ mockDb.profile.count.mockResolvedValueOnce(1);
+ const result = await preflightBackup(
+ await zipWith(manifest()),
+ "user-1",
+ );
+ expect(result.targetIsEmpty).toBe(false);
+ expect(result.targetCounts.Profile).toBe(1);
+ });
+
+ it("refuses a backup with the wrong formatVersion", async () => {
+ const bad = { ...manifest(), formatVersion: 99 };
+ await expect(
+ preflightBackup(await zipWith(bad), "user-1", "[email protected]"),
+ ).rejects.toBeInstanceOf(BackupError);
+ });
+});
diff --git a/__tests__/backupSnapshot.spec.ts b/__tests__/backupSnapshot.spec.ts
new file mode 100644
index 0000000..b80326c
--- /dev/null
+++ b/__tests__/backupSnapshot.spec.ts
@@ -0,0 +1,95 @@
+import fsSync from "fs";
+import os from "os";
+import path from "path";
+import { BackupError } from "@/lib/backup/manifest";
+import { pruneSnapshots, readSnapshot, snapshotDir } from "@/lib/backup/snapshot";
+import { APP_CONSTANTS } from "@/lib/constants";
+
+describe("snapshotDir", () => {
+ it("scopes snapshots to the user, under the uploads volume", () => {
+ expect(snapshotDir("u1")).toBe(
+ path.join(APP_CONSTANTS.UPLOADS_DIR, "backups", "u1"),
+ );
+ });
+
+ it("gives two users disjoint directories", () => {
+ expect(snapshotDir("u1")).not.toBe(snapshotDir("u2"));
+ });
+});
+
+describe("readSnapshot id validation", () => {
+ // Each of these would escape the per-user directory if the id were joined
+ // straight onto it. The per-user directory alone is not the guard.
+ it.each([
+ "../../../etc/passwd",
+ "../u2/pre-import-2026-08-14T1032.zip",
+ "/data/prod.db",
+ "pre-import-2026-08-14T1032.zip/../../../dev.db",
+ "..",
+ "",
+ ])("refuses %s", async (id) => {
+ await expect(readSnapshot("u1", id)).rejects.toBeInstanceOf(BackupError);
+ });
+
+ it("refuses a name that is not a snapshot at all", async () => {
+ await expect(readSnapshot("u1", "resume.pdf")).rejects.toBeInstanceOf(
+ BackupError,
+ );
+ });
+});
+
+// Deleting files is the one thing in this module that cannot be undone, and
+// the byte rule has two ways to go wrong: dropping too much, or dropping the
+// newest. Both are asserted directly.
+describe("pruneSnapshots", () => {
+ const originalUploads = APP_CONSTANTS.UPLOADS_DIR;
+ let dir: string;
+
+ const write = (name: string, bytes: number) =>
+ fsSync.writeFileSync(path.join(dir, name), Buffer.alloc(bytes));
+
+ const stamped = (n: number) => `pre-import-2026-08-14T10-0${n}-00-000Z.zip`;
+
+ beforeEach(() => {
+ const root = fsSync.mkdtempSync(path.join(os.tmpdir(), "jobsync-snap-"));
+ (APP_CONSTANTS as { UPLOADS_DIR: string }).UPLOADS_DIR = root;
+ dir = snapshotDir("u1");
+ fsSync.mkdirSync(dir, { recursive: true });
+ });
+
+ afterEach(() => {
+ (APP_CONSTANTS as { UPLOADS_DIR: string }).UPLOADS_DIR = originalUploads;
+ });
+
+ it("drops everything past the keep count, oldest first", async () => {
+ for (let n = 1; n <= 5; n++) write(stamped(n), 16);
+ await pruneSnapshots("u1", 3);
+ expect(fsSync.readdirSync(dir).sort()).toEqual([
+ stamped(3),
+ stamped(4),
+ stamped(5),
+ ]);
+ });
+
+ it("drops within the keep count once the byte budget is passed", async () => {
+ const big = APP_CONSTANTS.BACKUP_SNAPSHOT_MAX_TOTAL_BYTES / 2 + 1024;
+ write(stamped(1), big);
+ write(stamped(2), big);
+ write(stamped(3), big);
+ await pruneSnapshots("u1", 5);
+ expect(fsSync.readdirSync(dir)).toEqual([stamped(3)]);
+ });
+
+ it("keeps the newest even when it alone exceeds the budget", async () => {
+ write(stamped(1), APP_CONSTANTS.BACKUP_SNAPSHOT_MAX_TOTAL_BYTES + 1024);
+ await pruneSnapshots("u1", 5);
+ expect(fsSync.readdirSync(dir)).toEqual([stamped(1)]);
+ });
+
+ it("ignores files that are not snapshots", async () => {
+ write("notes.txt", 16);
+ write(stamped(1), 16);
+ await pruneSnapshots("u1", 0);
+ expect(fsSync.readdirSync(dir)).toEqual(["notes.txt"]);
+ });
+});
diff --git a/src/lib/backup/import.ts b/src/lib/backup/import.ts
new file mode 100644
index 0000000..ec3fc8e
--- /dev/null
+++ b/src/lib/backup/import.ts
@@ -0,0 +1,379 @@
+import fs from "fs/promises";
+import path from "path";
+import type JSZip from "jszip";
+import db from "@/lib/db";
+import { APP_CONSTANTS } from "@/lib/constants";
+import { IdMap, buildCreateData } from "./idmap";
+import { BackupError, openBackupZip, readManifest } from "./manifest";
+import {
+ checkImportedFile,
+ importedFilePath,
+ normalizeAutomation,
+ normalizeAutomationRun,
+ safeEntryName,
+} from "./normalize";
+import {
+ DELETE_ORDER,
+ EMPTINESS_MODELS,
+ INSERT_ORDER,
+ LOOKUP_MODELS,
+ MODEL_SPECS,
+ type BackupModel,
+} from "./ordering";
+import { writeSnapshot } from "./snapshot";
+import { BackupDataSchema, type BackupData, type BackupManifest } from "./schema";
+
+export interface PreflightResult {
+ manifest: BackupManifest;
+ emailMatches: boolean;
+ targetIsEmpty: boolean;
+ targetCounts: Record<string, number>;
+}
+
+// Counts read from the target database, not from the file — the manifest is
+// self-reported and cannot be allowed to size the destructive confirmation.
+export async function countTargetContent(
+ userId: string,
+): Promise<Record<string, number>> {
+ const entries = await Promise.all(
+ EMPTINESS_MODELS.map(async (model) => {
+ const spec = MODEL_SPECS[model];
+ const delegate = (db as unknown as Record<string, { count: (a: unknown) => Promise<number> }>)[
+ spec.delegate
+ ];
+ return [model, await delegate.count({ where: spec.scope(userId) })] as const;
+ }),
+ );
+ return Object.fromEntries(entries);
+}
+
+// Reads manifest.json only, writes nothing to the database and nothing to disk.
+export async function preflightBackup(
+ bytes: Buffer,
+ userId: string,
+ userEmail: string,
+): Promise<PreflightResult> {
+ const zip = await openBackupZip(bytes);
+ const manifest = await readManifest(zip);
+
+ if (!zip.file("data.json")) {
+ throw new BackupError("Backup is missing data.json.");
+ }
+
+ const targetCounts = await countTargetContent(userId);
+ const targetIsEmpty = Object.values(targetCounts).every((n) => n === 0);
+
+ return {
+ manifest,
+ emailMatches: manifest.sourceEmail === userEmail,
+ targetIsEmpty,
+ targetCounts,
+ };
+}
+
+export interface ImportResult {
+ counts: Record<string, number>;
+ filesWritten: number;
+ // Where the previous state went, so the UI can tell the user it exists.
+ snapshotPath: string | null;
+}
+
+type Tx = Record<string, Record<string, (a: unknown) => Promise<unknown>>>;
+
+async function readData(zip: JSZip): Promise<BackupData> {
+ const entry = zip.file("data.json");
+ if (!entry) throw new BackupError("Backup is missing data.json.");
+ let raw: unknown;
+ try {
+ raw = JSON.parse(await entry.async("string"));
+ } catch {
+ throw new BackupError("data.json is not valid JSON.");
+ }
+ const parsed = BackupDataSchema.safeParse(raw);
+ if (!parsed.success) {
+ throw new BackupError(
+ `Backup data failed validation: ${parsed.error.issues[0]?.path.join(".")} ${parsed.error.issues[0]?.message}`,
+ );
+ }
+ return parsed.data;
+}
+
+// The scheduler holds a live handle to an in-flight run and a partial unique
+// index enforces one per automation, so deleting it mid-flight is not a
+// contention problem the "database busy" retry covers.
+async function assertNoActiveRun(userId: string): Promise<void> {
+ const active = await db.automationRun.findFirst({
+ where: {
+ status: { in: ["running", "cancelling"] },
+ automation: { userId },
+ },
+ select: { id: true },
+ });
+ if (active) {
+ throw new BackupError(
+ "An automation run is in progress. Wait for it to finish, then import again.",
+ );
+ }
+}
+
+// Resolved against the target's global JobStatus table, creating any the target
+// lacks from the carried label/value. Runs before the transaction: it is the
+// only write outside the user's own data and it is idempotent.
+async function resolveJobStatuses(
+ data: BackupData,
+): Promise<Map<string, string>> {
+ const byValue = new Map<string, string>();
+ const existing = await db.jobStatus.findMany({ select: { id: true, value: true } });
+ for (const row of existing) byValue.set(row.value, row.id);
+
+ for (const status of data.jobStatuses) {
+ if (byValue.has(status.value)) continue;
+ const created = await db.jobStatus.create({
+ data: { label: status.label, value: status.value },
+ });
+ byValue.set(created.value, created.id);
+ }
+ return byValue;
+}
+
+// Straight inserts, no upsert. The wipe on the line above deleted every lookup
+// row this user owned, so there is nothing left to resolve against — an
+// "existing row" check here can never match. Replace-not-merge is the point:
+// post-import counts equal the manifest for every table.
+async function insertLookups(
+ tx: Tx,
+ data: BackupData,
+ idMap: IdMap,
+ userId: string,
+): Promise<void> {
+ for (const model of LOOKUP_MODELS) {
+ const spec = MODEL_SPECS[model];
+ for (const row of (data as unknown as Record<string, { id: string; value: string }[]>)[model]) {
+ const newId = idMap.mint(row.id);
+ const { id: _old, ...rest } = row;
+ await tx[spec.delegate].create({
+ data: { ...rest, id: newId, createdBy: userId },
+ });
+ }
+ }
+}
+
+async function wipe(tx: Tx, userId: string): Promise<void> {
+ // Null the back-reference first: User.defaultResumeId is a foreign key into
+ // a table the wipe is about to empty.
+ await tx.user.update({
+ where: { id: userId },
+ data: { defaultResumeId: null },
+ });
+
+ // Not restorable, but a conversation about deleted jobs is worse than a
+ // clean panel. ApiKey and McpAccessToken are deliberately absent.
+ await tx.chatConversation.deleteMany({ where: { userId } });
+
+ for (const model of DELETE_ORDER) {
+ const spec = MODEL_SPECS[model];
+ await tx[spec.delegate].deleteMany({ where: spec.scope(userId) });
+ }
+}
+
+function rowsFor(data: BackupData, model: BackupModel): Record<string, unknown>[] {
+ return (data as unknown as Record<string, Record<string, unknown>[]>)[model];
+}
+
+export async function importBackup(
+ bytes: Buffer,
+ userId: string,
+ userEmail: string,
+ confirmWipe: boolean,
+): Promise<ImportResult> {
+ const zip = await openBackupZip(bytes);
+ await readManifest(zip);
+ const data = await readData(zip);
+
+ const targetCounts = await countTargetContent(userId);
+ const targetIsEmpty = Object.values(targetCounts).every((n) => n === 0);
+ if (!targetIsEmpty && !confirmWipe) {
+ throw new BackupError(
+ "This account already holds data. Confirm that you want it replaced before importing.",
+ );
+ }
+
+ await assertNoActiveRun(userId);
+
+ // The safety net, and the last thing that happens before this function is
+ // able to destroy anything. The transaction below protects against a crash;
+ // nothing except this protects against importing the wrong file. Skipped on
+ // an empty target because there is nothing to snapshot.
+ let snapshotPath: string | null = null;
+ if (!targetIsEmpty) {
+ snapshotPath = await writeSnapshot(userId, userEmail);
+ }
+
+ const statusByValue = await resolveJobStatuses(data);
+
+ // Mint every non-lookup id up front so the file writes below can name their
+ // targets, and so a forward reference in the FK rewrite never misses.
+ const idMap = new IdMap();
+ for (const model of INSERT_ORDER) {
+ if (MODEL_SPECS[model].lookup) continue;
+ for (const row of rowsFor(data, model)) idMap.mint(row.id as string);
+ }
+
+ // Files are written before the transaction: a failed import leaves orphaned
+ // bytes (unlinked below) rather than committed rows pointing at nothing.
+ const writtenPaths: string[] = [];
+ const uploadDir = path.join(APP_CONSTANTS.UPLOADS_DIR, "files", "resumes");
+ await fs.mkdir(uploadDir, { recursive: true });
+
+ // filePath and fileType are both rebuilt here; neither is taken from the
+ // payload. A row whose bytes are absent, oversized or not really a resume
+ // keeps its row and loses its file — the same end state as an export whose
+ // bytes had already gone missing, which the schema already models.
+ const newFilePaths = new Map<string, string>();
+ const newFileTypes = new Map<string, string>();
+ const rejectedFiles: string[] = [];
+
+ for (const file of data.File) {
+ const newId = idMap.get(file.id)!;
+ const prefix = `files/${file.id}/`;
+ // A prefix scan, not `new RegExp(prefix)`: file.id comes out of the
+ // payload, and interpolating it into a pattern hands an untrusted string
+ // to the regex engine for no gain over startsWith.
+ const entry =
+ zip.file(`${prefix}${safeEntryName(file.filePath)}`) ??
+ Object.keys(zip.files)
+ .filter((name) => name.startsWith(prefix) && !zip.files[name].dir)
+ .map((name) => zip.files[name])[0] ??
+ null;
+
+ if (!entry || file.fileMissing) {
+ newFilePaths.set(file.id, importedFilePath(newId, file.filePath, "pdf"));
+ continue;
+ }
+
+ const bytes = await entry.async("nodebuffer");
+ const checked = checkImportedFile(bytes);
+ if (!checked) {
+ rejectedFiles.push(file.fileName);
+ newFilePaths.set(file.id, importedFilePath(newId, file.filePath, "pdf"));
+ continue;
+ }
+
+ const target = importedFilePath(newId, entry.name, checked.kind);
+ newFilePaths.set(file.id, target);
+ newFileTypes.set(file.id, checked.mimeType);
+ await fs.writeFile(target, bytes);
+ writtenPaths.push(target);
+ }
+
+ if (rejectedFiles.length > 0) {
+ console.warn("[Backup] Dropped file entries that are not resumes:", rejectedFiles);
+ }
+
+ // Captured before the wipe so the old bytes can be unlinked after it commits.
+ const oldFilePaths = (
+ await db.file.findMany({
+ where: MODEL_SPECS.File.scope(userId),
+ select: { filePath: true },
+ })
+ ).map((f) => f.filePath);
+
+ const counts: Record<string, number> = {};
+
+ try {
+ await db.$transaction(
+ async (transaction) => {
+ const tx = transaction as unknown as Tx;
+
+ await wipe(tx, userId);
+ await insertLookups(tx, data, idMap, userId);
+
+ for (const model of INSERT_ORDER) {
+ if (MODEL_SPECS[model].lookup) continue;
+ const spec = MODEL_SPECS[model];
+ const rows = rowsFor(data, model);
+ counts[model] = rows.length;
+
+ for (const row of rows) {
+ let payload = buildCreateData(model, row, idMap, userId);
+
+ if (model === "File") {
+ const { fileMissing: _marker, ...rest } = payload;
+ payload = {
+ ...rest,
+ filePath: newFilePaths.get(row.id as string)!,
+ // From the sniff, never the payload. The fallback only reaches
+ // rows whose bytes were absent or rejected, where the column
+ // describes a file that is not on disk either way.
+ fileType: newFileTypes.get(row.id as string) ?? "application/pdf",
+ };
+ }
+ if (model === "Job") {
+ const { statusValue, ...rest } = payload as { statusValue: string };
+ payload = { ...rest, statusId: statusByValue.get(statusValue)! };
+ }
+ if (model === "Automation") {
+ payload = normalizeAutomation(payload as never);
+ }
+ if (model === "AutomationRun") {
+ payload = normalizeAutomationRun(payload as never);
+ }
+
+ await tx[spec.delegate].create({ data: payload });
+ }
+ }
+
+ // Join tables last: both endpoints have to exist first.
+ for (const link of data._JobToTag) {
+ await tx.job.update({
+ where: { id: idMap.get(link.jobId)! },
+ data: { tags: { connect: { id: idMap.get(link.tagId)! } } },
+ });
+ }
+ for (const link of data._QuestionToTag) {
+ await tx.question.update({
+ where: { id: idMap.get(link.questionId)! },
+ data: { tags: { connect: { id: idMap.get(link.tagId)! } } },
+ });
+ }
+ counts._JobToTag = data._JobToTag.length;
+ counts._QuestionToTag = data._QuestionToTag.length;
+
+ // A back-reference from a row the import never inserts.
+ const defaultResumeId = data.user.defaultResumeId
+ ? (idMap.get(data.user.defaultResumeId) ?? null)
+ : null;
+ await tx.user.update({ where: { id: userId }, data: { defaultResumeId } });
+ },
+ { timeout: 120_000, maxWait: 15_000 },
+ );
+ } catch (error) {
+ await Promise.all(
+ writtenPaths.map((p) => fs.unlink(p).catch(() => undefined)),
+ );
+ if (error instanceof BackupError) throw error;
+ const message = error instanceof Error ? error.message : "";
+ if (/database is locked|SQLITE_BUSY/i.test(message)) {
+ throw new BackupError("The database is busy. Please try the import again.");
+ }
+ console.error("[Backup] Import transaction failed:", error);
+ throw new BackupError("Import failed and nothing was changed.");
+ }
+
+ // Without this every restore-over-existing leaves the previous account's
+ // resume files in UPLOADS_DIR forever with no row pointing at them.
+ for (const filePath of oldFilePaths) {
+ if (writtenPaths.includes(filePath)) continue;
+ await fs.unlink(filePath).catch((error) => {
+ console.warn("[Backup] Could not remove replaced file", filePath, error);
+ });
+ }
+
+ // Nothing else would: syncSchedulerState runs at boot and in the automation
+ // actions, and an import goes through neither. Imported dynamically so
+ // node-cron and the whole scraper graph stay out of this module's imports.
+ const { syncSchedulerState } = await import("@/lib/scheduler");
+ await syncSchedulerState();
+
+ return { counts, filesWritten: writtenPaths.length, snapshotPath };
+}
diff --git a/src/lib/backup/index.ts b/src/lib/backup/index.ts
index 03bb68c..4d3a624 100644
--- a/src/lib/backup/index.ts
+++ b/src/lib/backup/index.ts
@@ -2,3 +2,7 @@ export { BackupError, buildManifest, countRows, openBackupZip, readManifest } fr
export { buildBackupZip, collectBackupData } from "./export";
export { BACKUP_FORMAT_VERSION, BackupDataSchema, ManifestSchema } from "./schema";
export type { BackupData, BackupManifest } from "./schema";
+export { importBackup, preflightBackup, countTargetContent } from "./import";
+export type { ImportResult, PreflightResult } from "./import";
+export { listSnapshots, readSnapshot, writeSnapshot, snapshotDir } from "./snapshot";
+export type { SnapshotInfo } from "./snapshot";
diff --git a/src/lib/backup/snapshot.ts b/src/lib/backup/snapshot.ts
new file mode 100644
index 0000000..d815fdf
--- /dev/null
+++ b/src/lib/backup/snapshot.ts
@@ -0,0 +1,127 @@
+import fs from "fs/promises";
+import path from "path";
+import { APP_CONSTANTS } from "@/lib/constants";
+import { buildBackupZip } from "./export";
+import { BackupError, openBackupZip, readManifest } from "./manifest";
+
+export interface SnapshotInfo {
+ id: string;
+ exportedAt: string;
+ appVersion: string;
+ counts: Record<string, number>;
+ sizeBytes: number;
+}
+
+// Anchored, and deliberately narrow: the only names this accepts are ones
+// writeSnapshot produced. A traversal segment cannot match it.
+const SNAPSHOT_ID = /^pre-import-[0-9TZ.:-]+\.zip$/;
+
+export function snapshotDir(userId: string): string {
+ return path.join(APP_CONSTANTS.UPLOADS_DIR, "backups", userId);
+}
+
+export async function writeSnapshot(
+ userId: string,
+ email: string,
+): Promise<string> {
+ const { buffer } = await buildBackupZip(userId, email);
+ const dir = snapshotDir(userId);
+ await fs.mkdir(dir, { recursive: true });
+
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
+ const target = path.join(dir, `pre-import-${stamp}.zip`);
+ await fs.writeFile(target, buffer);
+
+ await pruneSnapshots(userId, APP_CONSTANTS.BACKUP_SNAPSHOT_KEEP);
+ return target;
+}
+
+export async function listSnapshots(userId: string): Promise<SnapshotInfo[]> {
+ const dir = snapshotDir(userId);
+ let names: string[];
+ try {
+ names = await fs.readdir(dir);
+ } catch {
+ return [];
+ }
+
+ const infos: SnapshotInfo[] = [];
+ for (const name of names.filter((n) => SNAPSHOT_ID.test(n))) {
+ try {
+ const bytes = await fs.readFile(path.join(dir, name));
+ const manifest = await readManifest(await openBackupZip(bytes));
+ infos.push({
+ id: name,
+ exportedAt: manifest.exportedAt,
+ appVersion: manifest.appVersion,
+ counts: manifest.counts,
+ sizeBytes: bytes.length,
+ });
+ } catch (error) {
+ // An unreadable snapshot is skipped, not fatal — the list is a recovery
+ // surface and must not be taken down by one bad file.
+ console.warn("[Backup] Skipping unreadable snapshot", name, error);
+ }
+ }
+
+ return infos.sort((a, b) => b.exportedAt.localeCompare(a.exportedAt));
+}
+
+export async function readSnapshot(
+ userId: string,
+ id: string,
+): Promise<Buffer> {
+ if (!SNAPSHOT_ID.test(id)) {
+ throw new BackupError("That is not a valid snapshot.");
+ }
+ try {
+ return await fs.readFile(path.join(snapshotDir(userId), id));
+ } catch {
+ throw new BackupError("That snapshot no longer exists.");
+ }
+}
+
+// Prunes on count and on total bytes. The count alone is not a disk bound:
+// nothing caps how large one snapshot is, these sit on the same volume as the
+// SQLite database, and an import/rollback loop writes one every time. The
+// newest is always kept, even if it alone exceeds the byte budget — dropping
+// the only record of the state a user just left is worse than overshooting.
+export async function pruneSnapshots(
+ userId: string,
+ keep: number,
+): Promise<void> {
+ const dir = snapshotDir(userId);
+ let names: string[];
+ try {
+ names = await fs.readdir(dir);
+ } catch {
+ return;
+ }
+
+ // Names are ISO-stamped, so a lexical sort is a chronological one.
+ const newestFirst = names.filter((n) => SNAPSHOT_ID.test(n)).sort().reverse();
+
+ const stale: string[] = [];
+ let running = 0;
+
+ for (const [index, name] of newestFirst.entries()) {
+ if (index >= keep) {
+ stale.push(name);
+ continue;
+ }
+ const size = await fs
+ .stat(path.join(dir, name))
+ .then((s) => s.size)
+ .catch(() => 0);
+ running += size;
+ if (index > 0 && running > APP_CONSTANTS.BACKUP_SNAPSHOT_MAX_TOTAL_BYTES) {
+ stale.push(name);
+ }
+ }
+
+ for (const name of stale) {
+ await fs
+ .unlink(path.join(dir, name))
+ .catch((error) => console.warn("[Backup] Could not prune", name, error));
+ }
+}