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 backup foundations — jszip, size caps, model spec table, zod schemas and capped zip reader

Khuram Niaz79c0790e53ed
diff --git a/__tests__/backupManifest.spec.ts b/__tests__/backupManifest.spec.ts
new file mode 100644
index 0000000..e8757bb
--- /dev/null
+++ b/__tests__/backupManifest.spec.ts
@@ -0,0 +1,106 @@
+import JSZip from "jszip";
+import {
+ BackupError,
+ buildManifest,
+ countRows,
+ openBackupZip,
+ readManifest,
+} from "@/lib/backup/manifest";
+import { BackupDataSchema } from "@/lib/backup/schema";
+import { APP_CONSTANTS } from "@/lib/constants";
+
+const emptyData = BackupDataSchema.parse({});
+
+async function zipOf(entries: Record<string, string>): Promise<Buffer> {
+ const zip = new JSZip();
+ for (const [name, content] of Object.entries(entries)) zip.file(name, content);
+ return zip.generateAsync({ type: "nodebuffer" });
+}
+
+describe("buildManifest", () => {
+ it("stamps the format version, the source email and per-model counts", () => {
+ const data = BackupDataSchema.parse({
+ Tag: [
+ { id: "t1", label: "A", value: "a" },
+ { id: "t2", label: "B", value: "b" },
+ ],
+ });
+ const manifest = buildManifest(data, "[email protected]");
+ expect(manifest.formatVersion).toBe(1);
+ expect(manifest.sourceEmail).toBe("[email protected]");
+ expect(manifest.counts.Tag).toBe(2);
+ expect(manifest.counts.Job).toBe(0);
+ expect(manifest.appVersion).toMatch(/^\d+\.\d+\.\d+/);
+ expect(() => new Date(manifest.exportedAt).toISOString()).not.toThrow();
+ });
+
+ it("counts the join tables alongside the model groups", () => {
+ const data = BackupDataSchema.parse({
+ _JobToTag: [{ jobId: "j1", tagId: "t1" }],
+ });
+ expect(countRows(data)._JobToTag).toBe(1);
+ });
+});
+
+describe("openBackupZip", () => {
+ it("opens a zip under the caps", async () => {
+ const zip = await openBackupZip(await zipOf({ "manifest.json": "{}" }));
+ expect(zip.file("manifest.json")).not.toBeNull();
+ });
+
+ it("refuses a zip with too many entries", async () => {
+ const entries: Record<string, string> = {};
+ for (let i = 0; i < APP_CONSTANTS.BACKUP_MAX_ENTRIES + 1; i++) {
+ entries[`f${i}.txt`] = "x";
+ }
+ await expect(openBackupZip(await zipOf(entries))).rejects.toBeInstanceOf(
+ BackupError,
+ );
+ });
+
+ it("refuses a file that is not a zip at all", async () => {
+ await expect(
+ openBackupZip(Buffer.from("this is not a zip")),
+ ).rejects.toBeInstanceOf(BackupError);
+ });
+
+ // The actual zip bomb. Without this the uncompressed cap is untested, and
+ // the cap is the one guard standing between an untrusted archive and the
+ // heap — it must fail loudly if the central-directory read ever regresses.
+ it("refuses a zip that expands past the uncompressed cap", async () => {
+ const bomb = "a".repeat(
+ APP_CONSTANTS.BACKUP_MAX_UNCOMPRESSED_BYTES + 1024,
+ );
+ await expect(
+ openBackupZip(await zipOf({ "data.json": bomb })),
+ ).rejects.toBeInstanceOf(BackupError);
+ });
+});
+
+describe("readManifest", () => {
+ it("reads a valid manifest", async () => {
+ const manifest = buildManifest(emptyData, "[email protected]");
+ const zip = await openBackupZip(
+ await zipOf({ "manifest.json": JSON.stringify(manifest) }),
+ );
+ expect((await readManifest(zip)).sourceEmail).toBe("[email protected]");
+ });
+
+ it("refuses a missing manifest", async () => {
+ const zip = await openBackupZip(await zipOf({ "data.json": "{}" }));
+ await expect(readManifest(zip)).rejects.toBeInstanceOf(BackupError);
+ });
+
+ it("refuses malformed JSON", async () => {
+ const zip = await openBackupZip(await zipOf({ "manifest.json": "{oops" }));
+ await expect(readManifest(zip)).rejects.toBeInstanceOf(BackupError);
+ });
+
+ it("names both versions when formatVersion does not match", async () => {
+ const manifest = { ...buildManifest(emptyData, "[email protected]"), formatVersion: 2 };
+ const zip = await openBackupZip(
+ await zipOf({ "manifest.json": JSON.stringify(manifest) }),
+ );
+ await expect(readManifest(zip)).rejects.toThrow(/version 1.*found 2|found 2/i);
+ });
+});
diff --git a/__tests__/backupOrdering.spec.ts b/__tests__/backupOrdering.spec.ts
new file mode 100644
index 0000000..58d342c
--- /dev/null
+++ b/__tests__/backupOrdering.spec.ts
@@ -0,0 +1,86 @@
+import {
+ MODEL_SPECS,
+ INSERT_ORDER,
+ DELETE_ORDER,
+ LOOKUP_MODELS,
+ type BackupModel,
+} from "@/lib/backup/ordering";
+
+describe("backup ordering", () => {
+ it("lists every model in MODEL_SPECS exactly once in INSERT_ORDER", () => {
+ const specKeys = Object.keys(MODEL_SPECS).sort();
+ const orderKeys = [...INSERT_ORDER].sort();
+ expect(orderKeys).toEqual(specKeys);
+ expect(new Set(INSERT_ORDER).size).toBe(INSERT_ORDER.length);
+ });
+
+ it("inserts every foreign-key target before the model that references it", () => {
+ const position = new Map<BackupModel, number>(
+ INSERT_ORDER.map((m, i) => [m, i]),
+ );
+ for (const model of INSERT_ORDER) {
+ for (const [field, target] of Object.entries(MODEL_SPECS[model].fks)) {
+ expect(
+ position.get(target)! < position.get(model)!,
+ `${model}.${field} -> ${target} is inserted too late`,
+ ).toBe(true);
+ }
+ }
+ });
+
+ it("deletes in the exact reverse of the insert order", () => {
+ expect(DELETE_ORDER).toEqual([...INSERT_ORDER].reverse());
+ });
+
+ // The two edges the intuitive reading gets backwards.
+ it("inserts Summary before ResumeSection, because ResumeSection holds summaryId", () => {
+ expect(MODEL_SPECS.ResumeSection.fks.summaryId).toBe("Summary");
+ expect(MODEL_SPECS.Summary.fks).toEqual({});
+ expect(INSERT_ORDER.indexOf("Summary")).toBeLessThan(
+ INSERT_ORDER.indexOf("ResumeSection"),
+ );
+ });
+
+ it("remaps ContactInfo through resumeId, not resumeSectionId", () => {
+ expect(MODEL_SPECS.ContactInfo.fks).toEqual({ resumeId: "Resume" });
+ expect(MODEL_SPECS.ContactInfo.fks).not.toHaveProperty("resumeSectionId");
+ });
+
+ it("marks exactly the six lookup models, all owned by createdBy", () => {
+ expect([...LOOKUP_MODELS].sort()).toEqual([
+ "ActivityType",
+ "Company",
+ "JobSource",
+ "JobTitle",
+ "Location",
+ "Tag",
+ ]);
+ for (const model of LOOKUP_MODELS) {
+ expect(MODEL_SPECS[model].owner).toBe("createdBy");
+ expect(MODEL_SPECS[model].fks).toEqual({});
+ }
+ });
+
+ it("scopes every model to a user, directly or through a relation chain", () => {
+ for (const model of INSERT_ORDER) {
+ const where = MODEL_SPECS[model].scope("user-1");
+ expect(JSON.stringify(where)).toContain("user-1");
+ }
+ });
+
+ it("scopes the models whose ownership chain is easy to get wrong", () => {
+ expect(MODEL_SPECS.File.scope("u1")).toEqual({
+ Resume: { profile: { userId: "u1" } },
+ });
+ expect(MODEL_SPECS.Summary.scope("u1")).toEqual({
+ ResumeSection: { Resume: { profile: { userId: "u1" } } },
+ });
+ expect(MODEL_SPECS.ContactInfo.scope("u1")).toEqual({
+ resume: { profile: { userId: "u1" } },
+ });
+ expect(MODEL_SPECS.Interview.scope("u1")).toEqual({ job: { userId: "u1" } });
+ expect(MODEL_SPECS.AutomationRun.scope("u1")).toEqual({
+ automation: { userId: "u1" },
+ });
+ });
+});
diff --git a/__tests__/backupSchema.spec.ts b/__tests__/backupSchema.spec.ts
new file mode 100644
index 0000000..9a20319
--- /dev/null
+++ b/__tests__/backupSchema.spec.ts
@@ -0,0 +1,104 @@
+import {
+ BACKUP_FORMAT_VERSION,
+ ManifestSchema,
+ BackupDataSchema,
+} from "@/lib/backup/schema";
+import { INSERT_ORDER } from "@/lib/backup/ordering";
+
+const validManifest = {
+ formatVersion: 1,
+ appVersion: "1.1.16",
+ exportedAt: "2026-08-14T10:00:00.000Z",
+ sourceEmail: "[email protected]",
+ counts: { Job: 3, Resume: 1 },
+};
+
+describe("manifest schema", () => {
+ it("pins the format version at 1", () => {
+ expect(BACKUP_FORMAT_VERSION).toBe(1);
+ });
+
+ it("accepts a well-formed manifest", () => {
+ expect(ManifestSchema.parse(validManifest).appVersion).toBe("1.1.16");
+ });
+
+ it("rejects a different formatVersion", () => {
+ const res = ManifestSchema.safeParse({ ...validManifest, formatVersion: 2 });
+ expect(res.success).toBe(false);
+ });
+
+ it("rejects a manifest missing required fields", () => {
+ const { sourceEmail, ...rest } = validManifest;
+ expect(ManifestSchema.safeParse(rest).success).toBe(false);
+ });
+});
+
+describe("data schema", () => {
+ it("defaults every model group to an empty array", () => {
+ const parsed = BackupDataSchema.parse({});
+ for (const model of INSERT_ORDER) {
+ expect(parsed[model]).toEqual([]);
+ }
+ expect(parsed._JobToTag).toEqual([]);
+ expect(parsed._QuestionToTag).toEqual([]);
+ expect(parsed.jobStatuses).toEqual([]);
+ expect(parsed.user).toEqual({ defaultResumeId: null });
+ });
+
+ it("coerces ISO date strings back to Date objects", () => {
+ const parsed = BackupDataSchema.parse({
+ Job: [
+ {
+ id: "j1",
+ jobUrl: null,
+ description: "d",
+ jobType: "full-time",
+ workplaceType: null,
+ createdAt: "2026-01-01T00:00:00.000Z",
+ applied: false,
+ appliedDate: null,
+ dueDate: null,
+ statusValue: "new",
+ jobTitleId: "t1",
+ companyId: "c1",
+ jobSourceId: null,
+ salaryRange: null,
+ locationId: null,
+ resumeId: null,
+ coverLetterId: null,
+ automationId: null,
+ matchScore: null,
+ matchData: null,
+ discoveryStatus: null,
+ discoveredAt: null,
+ createdVia: null,
+ descriptionCompleteness: null,
+ },
+ ],
+ });
+ expect(parsed.Job[0].createdAt).toBeInstanceOf(Date);
+ });
+
+ it("rejects a Job carrying statusId instead of statusValue", () => {
+ const res = BackupDataSchema.safeParse({
+ Job: [{ id: "j1", statusId: "s1", description: "d" }],
+ });
+ expect(res.success).toBe(false);
+ });
+
+ it("parses the join-table groups as id pairs", () => {
+ const parsed = BackupDataSchema.parse({
+ _JobToTag: [{ jobId: "j1", tagId: "t1" }],
+ _QuestionToTag: [{ questionId: "q1", tagId: "t1" }],
+ });
+ expect(parsed._JobToTag).toEqual([{ jobId: "j1", tagId: "t1" }]);
+ expect(parsed._QuestionToTag[0].questionId).toBe("q1");
+ });
+
+ it("carries jobStatuses as label/value pairs", () => {
+ const parsed = BackupDataSchema.parse({
+ jobStatuses: [{ label: "New", value: "new" }],
+ });
+ expect(parsed.jobStatuses[0].value).toBe("new");
+ });
+});
diff --git a/package-lock.json b/package-lock.json
index 264847c..418dc62 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -47,6 +47,7 @@
"clsx": "^2.1.1",
"cmdk": "^1.0.0",
"date-fns": "^3.6.0",
+ "jszip": "^3.10.1",
"lucide-react": "^0.469.0",
"mammoth": "^1.12.0",
"markdown-it": "^14.3.0",
diff --git a/package.json b/package.json
index b4ad0db..b0a5903 100644
--- a/package.json
+++ b/package.json
@@ -60,6 +60,7 @@
"clsx": "^2.1.1",
"cmdk": "^1.0.0",
"date-fns": "^3.6.0",
+ "jszip": "^3.10.1",
"lucide-react": "^0.469.0",
"mammoth": "^1.12.0",
"markdown-it": "^14.3.0",
diff --git a/src/lib/ai/import/extract-text.ts b/src/lib/ai/import/extract-text.ts
index 636c245..ba33bfd 100644
--- a/src/lib/ai/import/extract-text.ts
+++ b/src/lib/ai/import/extract-text.ts
@@ -29,7 +29,7 @@ export function sniffFileType(buf: Buffer): "pdf" | "docx" | null {
}
// Parse ZIP Central Directory to sum uncompressed sizes and count entries
-function preflightZip(buf: Buffer): { entries: number; uncompressedBytes: number } {
+export function preflightZip(buf: Buffer): { entries: number; uncompressedBytes: number } {
const EOCD_SIG = 0x06054b50;
const CD_SIG = 0x02014b50;
diff --git a/src/lib/backup/manifest.ts b/src/lib/backup/manifest.ts
new file mode 100644
index 0000000..4355f94
--- /dev/null
+++ b/src/lib/backup/manifest.ts
@@ -0,0 +1,103 @@
+import JSZip from "jszip";
+import pkg from "../../../package.json";
+import { APP_CONSTANTS } from "@/lib/constants";
+import { preflightZip } from "@/lib/ai/import/extract-text";
+import { INSERT_ORDER } from "./ordering";
+import {
+ BACKUP_FORMAT_VERSION,
+ ManifestSchema,
+ type BackupData,
+ type BackupManifest,
+} from "./schema";
+
+// Carries a message safe to hand straight back to the user. Anything else
+// thrown out of the backup module is an internal error and gets a generic 500.
+export class BackupError extends Error {
+ constructor(public userMessage: string) {
+ super(userMessage);
+ this.name = "BackupError";
+ }
+}
+
+const COUNTED_GROUPS = [...INSERT_ORDER, "_JobToTag", "_QuestionToTag"] as const;
+
+export function countRows(data: BackupData): Record<string, number> {
+ const counts: Record<string, number> = {};
+ for (const group of COUNTED_GROUPS) {
+ counts[group] = (data as unknown as Record<string, unknown[]>)[group].length;
+ }
+ return counts;
+}
+
+export function buildManifest(
+ data: BackupData,
+ sourceEmail: string,
+): BackupManifest {
+ return {
+ formatVersion: BACKUP_FORMAT_VERSION,
+ appVersion: pkg.version,
+ exportedAt: new Date().toISOString(),
+ sourceEmail,
+ counts: countRows(data),
+ };
+}
+
+// Entry count and uncompressed size are read out of the zip's own central
+// directory before JSZip parses anything and before a single byte is inflated
+// — decompressing to measure is the zip bomb, not the guard. preflightZip is
+// the same routine extractDocx already runs on untrusted .docx uploads; it is
+// reused rather than reimplemented, and reusing it is what keeps this file off
+// JSZip's private `_data.uncompressedSize`, which no public API exposes and a
+// minor JSZip release could rename out from under a `?? 0`.
+export async function openBackupZip(bytes: Buffer): Promise<JSZip> {
+ let preflight: { entries: number; uncompressedBytes: number };
+ try {
+ preflight = preflightZip(bytes);
+ } catch {
+ throw new BackupError("That file is not a readable zip archive.");
+ }
+
+ if (preflight.entries > APP_CONSTANTS.BACKUP_MAX_ENTRIES) {
+ throw new BackupError(
+ `Backup has too many entries (${preflight.entries}); the limit is ${APP_CONSTANTS.BACKUP_MAX_ENTRIES}.`,
+ );
+ }
+
+ if (preflight.uncompressedBytes > APP_CONSTANTS.BACKUP_MAX_UNCOMPRESSED_BYTES) {
+ throw new BackupError(
+ "Backup expands to more than the allowed uncompressed size.",
+ );
+ }
+
+ try {
+ return await JSZip.loadAsync(bytes);
+ } catch {
+ throw new BackupError("That file is not a readable zip archive.");
+ }
+}
+
+export async function readManifest(zip: JSZip): Promise<BackupManifest> {
+ const entry = zip.file("manifest.json");
+ if (!entry) {
+ throw new BackupError("Backup is missing manifest.json.");
+ }
+
+ let raw: unknown;
+ try {
+ raw = JSON.parse(await entry.async("string"));
+ } catch {
+ throw new BackupError("manifest.json is not valid JSON.");
+ }
+
+ const found = (raw as { formatVersion?: unknown })?.formatVersion;
+ const parsed = ManifestSchema.safeParse(raw);
+ if (!parsed.success) {
+ if (found !== undefined && found !== BACKUP_FORMAT_VERSION) {
+ throw new BackupError(
+ `This backup was made by a different version of JobSync. Expected format version ${BACKUP_FORMAT_VERSION}, found ${String(found)}.`,
+ );
+ }
+ throw new BackupError("manifest.json is missing required fields.");
+ }
+ return parsed.data;
+}
diff --git a/src/lib/backup/ordering.ts b/src/lib/backup/ordering.ts
new file mode 100644
index 0000000..3aa077e
--- /dev/null
+++ b/src/lib/backup/ordering.ts
@@ -0,0 +1,203 @@
+// The single table that drives export scoping, wipe scoping, FK rewriting and
+// ownership injection. A second list of models anywhere is a bug waiting to
+// happen — everything reads this one.
+
+export type BackupModel =
+ | "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"
+ | "AutomationRun"
+ | "UserSettings";
+
+export interface ModelSpec {
+ // Prisma client delegate key, e.g. prisma[spec.delegate].findMany(...)
+ delegate: string;
+ // Ownership column written from the session user, never read from the file.
+ owner?: "userId" | "createdBy";
+ // Resolved by (value, createdBy) upsert rather than minted fresh.
+ lookup?: boolean;
+ // Foreign-key column -> the model whose ids it points at.
+ fks: Record<string, BackupModel>;
+ // Ownership-scoped where clause, per CLAUDE.md's IDOR rules.
+ scope: (userId: string) => Record<string, unknown>;
+}
+
+const byUser = (userId: string) => ({ userId });
+const byCreatedBy = (userId: string) => ({ createdBy: userId });
+const byProfile = (userId: string) => ({ profile: { userId } });
+const byResume = (userId: string) => ({ Resume: { profile: { userId } } });
+const bySection = (userId: string) => ({
+ ResumeSection: { Resume: { profile: { userId } } },
+});
+
+export const MODEL_SPECS: Record<BackupModel, ModelSpec> = {
+ Company: { delegate: "company", owner: "createdBy", lookup: true, fks: {}, scope: byCreatedBy },
+ JobTitle: { delegate: "jobTitle", owner: "createdBy", lookup: true, fks: {}, scope: byCreatedBy },
+ Location: { delegate: "location", owner: "createdBy", lookup: true, fks: {}, scope: byCreatedBy },
+ JobSource: { delegate: "jobSource", owner: "createdBy", lookup: true, fks: {}, scope: byCreatedBy },
+ Tag: { delegate: "tag", owner: "createdBy", lookup: true, fks: {}, scope: byCreatedBy },
+ ActivityType: { delegate: "activityType", owner: "createdBy", lookup: true, fks: {}, scope: byCreatedBy },
+
+ Profile: { delegate: "profile", owner: "userId", fks: {}, scope: byUser },
+
+ // File holds no foreign key — Resume.FileId points at it — so it is scoped
+ // through the back-relation, matching deleteFile in profile.actions.ts.
+ File: { delegate: "file", fks: {}, scope: byResume },
+
+ Resume: {
+ delegate: "resume",
+ fks: { profileId: "Profile", FileId: "File" },
+ scope: byProfile,
+ },
+
+ // ContactInfo hangs off Resume, not ResumeSection: resumeId @unique, and the
+ // relation field is lower-case `resume` unlike ResumeSection's `Resume`.
+ ContactInfo: { delegate: "contactInfo", fks: { resumeId: "Resume" }, scope: (userId) => ({ resume: { profile: { userId } } }) },
+
+ // Summary holds no foreign key either — ResumeSection.summaryId points at it.
+ Summary: { delegate: "summary", fks: {}, scope: bySection },
+
+ ResumeSection: {
+ delegate: "resumeSection",
+ fks: { resumeId: "Resume", summaryId: "Summary" },
+ scope: byResume,
+ },
+ WorkExperience: {
+ delegate: "workExperience",
+ fks: {
+ companyId: "Company",
+ jobTitleId: "JobTitle",
+ locationId: "Location",
+ resumeSectionId: "ResumeSection",
+ },
+ scope: bySection,
+ },
+ Education: {
+ delegate: "education",
+ fks: { locationId: "Location", resumeSectionId: "ResumeSection" },
+ scope: bySection,
+ },
+ LicenseOrCertification: {
+ delegate: "licenseOrCertification",
+ fks: { resumeSectionId: "ResumeSection" },
+ scope: bySection,
+ },
+ OtherSection: {
+ delegate: "otherSection",
+ fks: { resumeSectionId: "ResumeSection" },
+ scope: bySection,
+ },
+ Skill: {
+ delegate: "skill",
+ fks: { tagId: "Tag", resumeSectionId: "ResumeSection" },
+ scope: bySection,
+ },
+ CoverLetter: { delegate: "coverLetter", fks: { profileId: "Profile" }, scope: byProfile },
+ Automation: {
+ delegate: "automation",
+ owner: "userId",
+ fks: { resumeId: "Resume" },
+ scope: byUser,
+ },
+ Job: {
+ delegate: "job",
+ owner: "userId",
+ fks: {
+ jobTitleId: "JobTitle",
+ companyId: "Company",
+ jobSourceId: "JobSource",
+ locationId: "Location",
+ resumeId: "Resume",
+ coverLetterId: "CoverLetter",
+ automationId: "Automation",
+ },
+ scope: byUser,
+ },
+ Note: { delegate: "note", owner: "userId", fks: { jobId: "Job" }, scope: byUser },
+ Interview: { delegate: "interview", fks: { jobId: "Job" }, scope: (userId) => ({ job: { userId } }) },
+ Contact: {
+ delegate: "contact",
+ owner: "createdBy",
+ fks: { interviewId: "Interview" },
+ scope: byCreatedBy,
+ },
+ Task: {
+ delegate: "task",
+ owner: "userId",
+ fks: { activityTypeId: "ActivityType" },
+ scope: byUser,
+ },
+ Activity: {
+ delegate: "activity",
+ owner: "userId",
+ fks: { activityTypeId: "ActivityType", taskId: "Task" },
+ scope: byUser,
+ },
+ Question: { delegate: "question", owner: "createdBy", fks: {}, scope: byCreatedBy },
+ AutomationRun: {
+ delegate: "automationRun",
+ fks: { automationId: "Automation" },
+ scope: (userId) => ({ automation: { userId } }),
+ },
+ UserSettings: { delegate: "userSettings", owner: "userId", fks: {}, scope: byUser },
+};
+
+export const INSERT_ORDER: BackupModel[] = [
+ "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",
+ "AutomationRun",
+ "UserSettings",
+];
+
+export const DELETE_ORDER: BackupModel[] = [...INSERT_ORDER].reverse();
+
+export const LOOKUP_MODELS: BackupModel[] = INSERT_ORDER.filter(
+ (m) => MODEL_SPECS[m].lookup,
+);
diff --git a/src/lib/backup/schema.ts b/src/lib/backup/schema.ts
new file mode 100644
index 0000000..f9d29ef
--- /dev/null
+++ b/src/lib/backup/schema.ts
@@ -0,0 +1,329 @@
+import { z } from "zod";
+
+export const BACKUP_FORMAT_VERSION = 1;
+
+export const ManifestSchema = z.object({
+ formatVersion: z.literal(BACKUP_FORMAT_VERSION),
+ appVersion: z.string(),
+ exportedAt: z.string(),
+ sourceEmail: z.string(),
+ counts: z.record(z.string(), z.number()),
+});
+
+export type BackupManifest = z.infer<typeof ManifestSchema>;
+
+const id = z.string().min(1);
+const optId = z.string().min(1).nullable();
+const str = z.string();
+const optStr = z.string().nullable();
+const dt = z.coerce.date();
+const optDt = z.coerce.date().nullable();
+const int = z.number().int();
+const optInt = z.number().int().nullable();
+
+const Company = z.object({ id, label: str, value: str, logoUrl: optStr });
+const JobTitle = z.object({ id, label: str, value: str });
+const Location = z.object({
+ id,
+ label: str,
+ value: str,
+ stateProv: optStr,
+ country: optStr,
+});
+const JobSource = z.object({ id, label: str, value: str });
+const Tag = z.object({ id, label: str, value: str });
+const ActivityType = z.object({
+ id,
+ label: str,
+ value: str,
+ description: optStr,
+ createdAt: dt,
+ updatedAt: dt,
+});
+
+const Profile = z.object({ id });
+
+// fileMissing marks a row whose bytes were absent on disk at export time.
+const File = z.object({
+ id,
+ fileName: str,
+ filePath: str,
+ fileType: str,
+ uploadedAt: dt,
+ fileMissing: z.boolean().optional(),
+});
+
+const Resume = z.object({
+ id,
+ profileId: id,
+ title: str,
+ createdAt: dt,
+ updatedAt: dt,
+ FileId: optId,
+ reviewData: optStr,
+});
+
+const ContactInfo = z.object({
+ id,
+ createdAt: dt,
+ updatedAt: dt,
+ resumeId: id,
+ firstName: str,
+ lastName: str,
+ headline: str,
+ email: str,
+ phone: str,
+ address: optStr,
+ url1: optStr,
+ url1Label: optStr,
+ url2: optStr,
+ url2Label: optStr,
+});
+
+const Summary = z.object({ id, createdAt: dt, updatedAt: dt, content: str });
+
+const ResumeSection = z.object({
+ id,
+ resumeId: id,
+ sectionTitle: str,
+ sectionType: str,
+ summaryId: optId,
+});
+
+const WorkExperience = z.object({
+ id,
+ createdAt: dt,
+ updatedAt: dt,
+ companyId: id,
+ jobTitleId: id,
+ startDate: dt,
+ endDate: optDt,
+ description: str,
+ locationId: id,
+ resumeSectionId: optId,
+});
+
+const Education = z.object({
+ id,
+ createdAt: dt,
+ updatedAt: dt,
+ institution: str,
+ degree: str,
+ fieldOfStudy: str,
+ startDate: dt,
+ endDate: optDt,
+ description: optStr,
+ locationId: id,
+ resumeSectionId: optId,
+});
+
+const LicenseOrCertification = z.object({
+ id,
+ title: str,
+ organization: str,
+ issueDate: optDt,
+ expirationDate: optDt,
+ credentialUrl: optStr,
+ resumeSectionId: optId,
+});
+
+const OtherSection = z.object({
+ id,
+ createdAt: dt,
+ updatedAt: dt,
+ title: str,
+ content: str,
+ resumeSectionId: optId,
+});
+
+const Skill = z.object({
+ id,
+ createdAt: dt,
+ updatedAt: dt,
+ category: optStr,
+ order: int,
+ tagId: id,
+ resumeSectionId: id,
+});
+
+const CoverLetter = z.object({
+ id,
+ profileId: id,
+ title: str,
+ content: str,
+ createdAt: dt,
+ updatedAt: dt,
+});
+
+const Automation = z.object({
+ id,
+ name: str,
+ jobBoard: str,
+ keywords: str,
+ location: str,
+ sourceConfig: optStr,
+ resumeId: id,
+ matchThreshold: int,
+ scheduleHour: int,
+ nextRunAt: optDt,
+ lastRunAt: optDt,
+ status: str,
+ createdAt: dt,
+ updatedAt: dt,
+});
+
+const Job = z.object({
+ id,
+ jobUrl: optStr,
+ description: str,
+ jobType: str,
+ workplaceType: optStr,
+ createdAt: dt,
+ applied: z.boolean(),
+ appliedDate: optDt,
+ dueDate: optDt,
+ // The instance-local statusId is replaced by the stable natural key.
+ statusValue: str,
+ jobTitleId: id,
+ companyId: id,
+ jobSourceId: optId,
+ salaryRange: optStr,
+ locationId: optId,
+ resumeId: optId,
+ coverLetterId: optId,
+ automationId: optId,
+ matchScore: optInt,
+ matchData: optStr,
+ discoveryStatus: optStr,
+ discoveredAt: optDt,
+ createdVia: optStr,
+ descriptionCompleteness: optStr,
+});
+
+const Note = z.object({
+ id,
+ jobId: id,
+ content: str,
+ createdAt: dt,
+ updatedAt: dt,
+});
+
+const Interview = z.object({ id, createdAt: dt, jobId: id });
+
+const Contact = z.object({
+ id,
+ name: str,
+ email: str,
+ createdAt: dt,
+ interviewId: optId,
+});
+
+const Task = z.object({
+ id,
+ title: str,
+ description: optStr,
+ status: str,
+ priority: int,
+ percentComplete: int,
+ dueDate: optDt,
+ activityTypeId: optId,
+ createdAt: dt,
+ updatedAt: dt,
+});
+
+const Activity = z.object({
+ id,
+ activityName: str,
+ startTime: dt,
+ endTime: optDt,
+ duration: optInt,
+ breakMinutes: int,
+ breakStartedAt: optDt,
+ breakPlannedMins: optInt,
+ description: optStr,
+ createdAt: dt,
+ updatedAt: dt,
+ activityTypeId: id,
+ taskId: optId,
+});
+
+const Question = z.object({
+ id,
+ question: str,
+ answer: optStr,
+ createdAt: dt,
+ updatedAt: dt,
+ createdVia: optStr,
+});
+
+const AutomationRun = z.object({
+ id,
+ automationId: id,
+ jobsSearched: int,
+ jobsDeduplicated: int,
+ jobsProcessed: int,
+ jobsMatched: int,
+ jobsSaved: int,
+ status: str,
+ errorMessage: optStr,
+ blockedReason: optStr,
+ funnelStats: optStr,
+ startedAt: dt,
+ completedAt: optDt,
+});
+
+const UserSettings = z.object({
+ id,
+ settings: str,
+ createdAt: dt,
+ updatedAt: dt,
+});
+
+const group = <T extends z.ZodTypeAny>(schema: T) =>
+ z.array(schema).default([]);
+
+export const BackupDataSchema = z.object({
+ Company: group(Company),
+ JobTitle: group(JobTitle),
+ Location: group(Location),
+ JobSource: group(JobSource),
+ Tag: group(Tag),
+ ActivityType: group(ActivityType),
+ Profile: group(Profile),
+ File: group(File),
+ Resume: group(Resume),
+ ContactInfo: group(ContactInfo),
+ Summary: group(Summary),
+ ResumeSection: group(ResumeSection),
+ WorkExperience: group(WorkExperience),
+ Education: group(Education),
+ LicenseOrCertification: group(LicenseOrCertification),
+ OtherSection: group(OtherSection),
+ Skill: group(Skill),
+ CoverLetter: group(CoverLetter),
+ Automation: group(Automation),
+ Job: group(Job),
+ Note: group(Note),
+ Interview: group(Interview),
+ Contact: group(Contact),
+ Task: group(Task),
+ Activity: group(Activity),
+ Question: group(Question),
+ AutomationRun: group(AutomationRun),
+ UserSettings: group(UserSettings),
+
+ // Implicit Prisma m2m relations are not models, so they travel as id pairs.
+ _JobToTag: group(z.object({ jobId: id, tagId: id })),
+ _QuestionToTag: group(z.object({ questionId: id, tagId: id })),
+
+ // Natural keys for the only global table in the schema.
+ jobStatuses: group(z.object({ label: str, value: str })),
+
+ // The only User field that travels; applied after Resume rows exist.
+ user: z
+ .object({ defaultResumeId: optId })
+ .default({ defaultResumeId: null }),
+});
+
+export type BackupData = z.infer<typeof BackupDataSchema>;
+export type BackupRow = Record<string, unknown>;
diff --git a/src/lib/constants.ts b/src/lib/constants.ts
index e2c750c..21b1066 100644
--- a/src/lib/constants.ts
+++ b/src/lib/constants.ts
@@ -187,6 +187,22 @@ export const APP_CONSTANTS = {
// File uploads
UPLOADS_DIR: process.env.NODE_ENV !== "production" ? "data" : "/data",
+
+ // Backup caps. Everything is held in RAM at once, so the upload cap is what
+ // bounds memory on a box also running Next and the scheduler; the
+ // uncompressed cap is the zip-bomb guard. 50 MB rather than the spec's 25:
+ // resumes are 5 MB each and PDFs barely deflate, so six of them produce an
+ // export a 25 MB cap would refuse — a backup you cannot restore is worse
+ // than a large one.
+ BACKUP_MAX_UPLOAD_BYTES: 50 * 1024 * 1024,
+ BACKUP_MAX_UNCOMPRESSED_BYTES: 100 * 1024 * 1024,
+ BACKUP_MAX_ENTRIES: 5000,
+ // Pre-import snapshots retained per user. The count alone does not bound
+ // disk — nothing caps one snapshot's size — and these live on the same
+ // volume as the SQLite database, so prune on total bytes as well.
+ BACKUP_SNAPSHOT_KEEP: 5,
+ BACKUP_SNAPSHOT_MAX_TOTAL_BYTES: 250 * 1024 * 1024,
+
MAX_RESUME_FILE_SIZE_BYTES: 5 * 1024 * 1024, // 5 MB
RESUME_ALLOWED_MIME_TYPES: [
"application/pdf",