feat(export): make the full backup actually full

The full-backup export (plaintext + passphrase-encrypted, and the weekly
auto-backup) only ever covered measurements, medications, mood, and cycle
data. Labs, illness episodes, allergies, family history, and workouts were
silently missing, and the export UI implied "everything" was included.

Adds a shared records-backup section (src/lib/export/records-backup.ts) that
both the on-demand export routes and the weekly data-backup worker read from:
lab results + the biomarker catalog, illness episodes (including flares via
parentConditionId) with their day-logs, allergies, family history, and
workout summaries. Every read is owner-scoped and soft-delete-filtered;
encrypted free-text columns decrypt fail-soft so one bad row never aborts
the whole backup.

Document original files and workout GPS/per-sample time series stay
deliberately out of the JSON payload (size). The payload now carries an
explicit manifest disclosing exactly that, and the export UI states it in
plain text instead of implying completeness. These new domains are
export-only for now — admin restore still only recreates the original
measurements/medications/mood/cycle domains; the payload validates and
reports counts for the rest, but restoring a snapshot does not yet recreate
them.

Also fixes the admin backup-upload total to count every domain, not just
the original four.
This commit is contained in:
Marc-André Bombeck committed 2026-07-18 02:09:33 +02:00
1 parent 837c44e4c2
commit 3dd5dbeb42
22 files changed
+1491 -68

No files matched your search

+236 -1
View File
@@ -18,7 +18,7 @@
* of bubbling out of `prisma.createMany` with a useless message.
*/
import { describe, expect, it } from "vitest";
import { backupPayloadSchema } from "../backup";
import { backupPayloadSchema, summarizeBackup } from "../backup";
const baseEntry = {
date: "2026-05-08",
@@ -148,3 +148,238 @@ describe("backupPayloadSchema — v1.15.0 cycle round-trip", () => {
}
});
});
describe("backupPayloadSchema — v1.28 backup-completeness domains", () => {
it("defaults every records field when a pre-v1.28 blob omits them", () => {
const r = backupPayloadSchema.safeParse({
schemaVersion: "1",
exportedAt: "2026-05-08T07:00:00.000Z",
userId: "u1",
});
expect(r.success).toBe(true);
if (r.success) {
expect(r.data.labResults).toEqual([]);
expect(r.data.biomarkers).toEqual([]);
expect(r.data.illnessEpisodes).toEqual([]);
expect(r.data.allergies).toEqual([]);
expect(r.data.familyHistory).toEqual([]);
expect(r.data.workouts).toEqual([]);
expect(r.data.documents).toEqual([]);
expect(r.data.manifest).toBeNull();
}
});
it("round-trips a lab result cross-referencing a biomarker by name", () => {
const r = backupPayloadSchema.safeParse({
schemaVersion: "1",
exportedAt: "2026-05-08T07:00:00.000Z",
userId: "u1",
biomarkers: [
{
name: "LDL Cholesterol",
unit: "mg/dL",
lowerBound: null,
upperBound: 130,
panel: "Lipid panel",
hidden: false,
context: "Low-density lipoprotein.",
},
],
labResults: [
{
panel: "Lipid panel",
analyte: "LDL Cholesterol",
value: 118,
valueText: null,
unit: "mg/dL",
referenceLow: null,
referenceHigh: 130,
takenAt: "2026-04-01T09:00:00.000Z",
source: "MANUAL",
biomarkerName: "LDL Cholesterol",
note: "Fasted draw.",
},
],
});
expect(r.success).toBe(true);
if (r.success) {
expect(r.data.biomarkers[0].name).toBe("LDL Cholesterol");
expect(r.data.labResults[0].biomarkerName).toBe("LDL Cholesterol");
expect(r.data.labResults[0].note).toBe("Fasted draw.");
}
});
it("round-trips an illness episode with a flare referencing its parent + nested day-logs", () => {
const r = backupPayloadSchema.safeParse({
schemaVersion: "1",
exportedAt: "2026-05-08T07:00:00.000Z",
userId: "u1",
illnessEpisodes: [
{
id: "ep-1",
label: "Migraine",
type: "CHRONIC",
lifecycle: "CHRONIC_ONGOING",
onsetAt: "2026-01-01T00:00:00.000Z",
resolvedAt: null,
parentConditionId: null,
note: null,
dayLogs: [],
},
{
id: "ep-2",
label: "Migraine flare",
type: "CHRONIC",
lifecycle: "FLARE",
onsetAt: "2026-04-10T00:00:00.000Z",
resolvedAt: "2026-04-12T00:00:00.000Z",
parentConditionId: "ep-1",
note: "Triggered by travel.",
dayLogs: [
{
date: "2026-04-10",
functionalImpact: 2,
feverC: null,
symptoms: [{ key: "headache", severity: 3 }],
note: "Bad day.",
},
],
},
],
});
expect(r.success).toBe(true);
if (r.success) {
expect(r.data.illnessEpisodes).toHaveLength(2);
expect(r.data.illnessEpisodes[1].parentConditionId).toBe("ep-1");
expect(r.data.illnessEpisodes[1].dayLogs[0].symptoms[0].key).toBe(
"headache",
);
}
});
it("round-trips allergies, family history, workouts, documents, and the manifest", () => {
const r = backupPayloadSchema.safeParse({
schemaVersion: "1",
exportedAt: "2026-05-08T07:00:00.000Z",
userId: "u1",
allergies: [
{
id: "al-1",
substance: "Penicillin",
category: "MEDICATION",
type: "ALLERGY",
severity: "SEVERE",
status: "ACTIVE",
onsetAt: null,
reaction: "Hives",
note: null,
},
],
familyHistory: [
{
id: "fh-1",
relationship: "MOTHER",
condition: "Type 2 diabetes",
ageAtOnset: 52,
note: null,
},
],
workouts: [
{
sportType: "running",
startedAt: "2026-04-01T07:00:00.000Z",
endedAt: "2026-04-01T08:00:00.000Z",
durationSec: 3600,
totalEnergyKcal: 600,
totalDistanceM: 10000,
avgHeartRate: 150,
maxHeartRate: 175,
minHeartRate: 110,
stepCount: 9000,
elevationM: 80,
pauseDurationSec: 0,
source: "APPLE_HEALTH",
externalId: "hk-1",
},
],
documents: [
{
id: "doc-1",
kind: "LAB_RESULT",
title: "Blood panel",
filename: "panel.pdf",
mimeType: "application/pdf",
byteSize: 12345,
status: "STORED",
reportDate: "2026-03-30",
documentDate: "2026-03-30",
summary: "Routine panel.",
},
],
manifest: {
documents: { included: "metadata-only", note: "Files excluded." },
workouts: { included: "summary-only", note: "Routes excluded." },
},
});
expect(r.success).toBe(true);
if (r.success) {
expect(r.data.allergies[0].substance).toBe("Penicillin");
expect(r.data.familyHistory[0].relationship).toBe("MOTHER");
expect(r.data.workouts[0].sportType).toBe("running");
expect(r.data.documents[0].id).toBe("doc-1");
// A document manifest entry never carries the raw file bytes — the
// schema simply has no field for it, so an attacker-supplied
// `contentEncrypted` key on upload is dropped as passthrough noise,
// never parsed into a typed field a restore path could act on.
expect(r.data.documents[0]).not.toHaveProperty("contentEncrypted");
expect(r.data.manifest?.documents.included).toBe("metadata-only");
expect(r.data.manifest?.workouts.included).toBe("summary-only");
}
});
it("summarizeBackup reports counts for every v1.28 domain, incl. nested day-logs", () => {
const parsed = backupPayloadSchema.parse({
schemaVersion: "1",
exportedAt: "2026-05-08T07:00:00.000Z",
userId: "u1",
labResults: [
{
analyte: "HbA1c",
unit: "%",
takenAt: "2026-04-01T09:00:00.000Z",
source: "MANUAL",
},
],
illnessEpisodes: [
{
id: "ep-1",
label: "Cold",
type: "INFECTION",
lifecycle: "ACUTE",
onsetAt: "2026-04-01T00:00:00.000Z",
dayLogs: [
{ date: "2026-04-01", symptoms: [] },
{ date: "2026-04-02", symptoms: [] },
],
},
],
workouts: [
{
sportType: "cycling",
startedAt: "2026-04-01T07:00:00.000Z",
endedAt: "2026-04-01T08:00:00.000Z",
durationSec: 3600,
source: "MANUAL",
},
],
});
const summary = summarizeBackup(parsed);
expect(summary.labResults).toBe(1);
expect(summary.illnessEpisodes).toBe(1);
expect(summary.illnessDayLogs).toBe(2);
expect(summary.workouts).toBe(1);
expect(summary.allergies).toBe(0);
expect(summary.familyHistory).toBe(0);
expect(summary.documents).toBe(0);
});
});
+192
View File
@@ -177,6 +177,160 @@ const cycleProfileSchema = z
})
.passthrough();
/* ── v1.28 backup-completeness shapes ──────────────────────────────
*
* Labs, illness episodes (+ flares/exacerbations), allergies, family
* history, workouts, and the documents manifest. Written by
* `buildRecordsBackupSection` (`src/lib/export/records-backup.ts`) — shared
* by the on-demand export routes AND the weekly `data-backup` worker.
*
* EXPORT-ONLY today: `POST /api/admin/backups/[id]/restore` does not yet
* recreate these domains on restore (only measurements / medications /
* mood / cycle round-trip). The schemas below exist so the payload
* validates + parses with real types (an admin reviewing an uploaded
* backup sees accurate counts) even though restore ignores them for now.
*/
const labResultBackupSchema = z
.object({
panel: z.string().nullable().optional(),
analyte: z.string().min(1),
value: z.number().nullable().optional(),
valueText: z.string().nullable().optional(),
unit: z.string().min(1),
referenceLow: z.number().nullable().optional(),
referenceHigh: z.number().nullable().optional(),
takenAt: isoDateTime,
source: z.string().min(1),
biomarkerName: z.string().nullable().optional(),
note: z.string().nullable().optional(),
})
.passthrough();
const biomarkerBackupSchema = z
.object({
name: z.string().min(1),
unit: z.string().min(1),
lowerBound: z.number().nullable().optional(),
upperBound: z.number().nullable().optional(),
panel: z.string().nullable().optional(),
hidden: z.boolean().optional(),
context: z.string().nullable().optional(),
})
.passthrough();
const illnessSymptomBackupSchema = z
.object({
key: z.string().min(1),
severity: z.number().int().nullable().optional(),
})
.passthrough();
const illnessDayLogBackupSchema = z
.object({
id: z.string().min(1).optional(),
episodeId: z.string().min(1).optional(),
date: z.string().min(1),
functionalImpact: z.number().int().nullable().optional(),
feverC: z.number().nullable().optional(),
symptoms: z.array(illnessSymptomBackupSchema).default([]),
note: z.string().nullable().optional(),
updatedAt: isoDateTime.optional(),
})
.passthrough();
const illnessEpisodeBackupSchema = z
.object({
id: z.string().min(1),
label: z.string().min(1),
type: z.string().min(1),
lifecycle: z.string().min(1),
onsetAt: isoDateTime,
resolvedAt: isoDateTime.nullable().optional(),
// Self-referencing flare/exacerbation link, carried as the exported
// episode's own id — never resolved against another user's rows.
parentConditionId: z.string().nullable().optional(),
note: z.string().nullable().optional(),
createdAt: isoDateTime.optional(),
updatedAt: isoDateTime.optional(),
dayLogs: z.array(illnessDayLogBackupSchema).default([]),
})
.passthrough();
const allergyBackupSchema = z
.object({
id: z.string().min(1),
substance: z.string().min(1),
category: z.string().min(1),
type: z.string().min(1),
severity: z.string().nullable().optional(),
status: z.string().min(1),
onsetAt: isoDateTime.nullable().optional(),
reaction: z.string().nullable().optional(),
note: z.string().nullable().optional(),
createdAt: isoDateTime.optional(),
updatedAt: isoDateTime.optional(),
})
.passthrough();
const familyHistoryBackupSchema = z
.object({
id: z.string().min(1),
relationship: z.string().min(1),
condition: z.string().min(1),
ageAtOnset: z.number().int().nullable().optional(),
note: z.string().nullable().optional(),
createdAt: isoDateTime.optional(),
updatedAt: isoDateTime.optional(),
})
.passthrough();
const workoutBackupSchema = z
.object({
sportType: z.string().min(1),
startedAt: isoDateTime,
endedAt: isoDateTime,
durationSec: z.number().int(),
totalEnergyKcal: z.number().nullable().optional(),
totalDistanceM: z.number().nullable().optional(),
avgHeartRate: z.number().int().nullable().optional(),
maxHeartRate: z.number().int().nullable().optional(),
minHeartRate: z.number().int().nullable().optional(),
stepCount: z.number().int().nullable().optional(),
elevationM: z.number().nullable().optional(),
pauseDurationSec: z.number().int().nullable().optional(),
source: z.string().min(1),
externalId: z.string().nullable().optional(),
})
.passthrough();
const documentBackupSchema = z
.object({
id: z.string().min(1),
kind: z.string().min(1),
title: z.string().nullable().optional(),
filename: z.string().nullable().optional(),
mimeType: z.string().min(1),
byteSize: z.number().int(),
status: z.string().min(1),
reportDate: z.string().nullable().optional(),
documentDate: z.string().nullable().optional(),
summary: z.string().nullable().optional(),
createdAt: isoDateTime.optional(),
})
.passthrough();
const backupManifestSchema = z
.object({
documents: z
.object({ included: z.string().min(1), note: z.string().min(1) })
.passthrough(),
workouts: z
.object({ included: z.string().min(1), note: z.string().min(1) })
.passthrough(),
})
.passthrough();
/**
* Wire shape — exactly what the pg-boss worker writes today, plus a
* `schemaVersion` field that newer writers stamp explicitly. Older blobs
@@ -196,6 +350,17 @@ export const backupPayloadSchema = z
cycleProfile: cycleProfileSchema.nullable().default(null),
cycles: z.array(cycleSpanSchema).default([]),
cycleDayLogs: z.array(cycleDayLogSchema).default([]),
// v1.28 backup-completeness — export-only for now (see the block
// comment above). Default to empty arrays / null so a pre-v1.28 backup
// (no records keys) still round-trips unchanged.
labResults: z.array(labResultBackupSchema).default([]),
biomarkers: z.array(biomarkerBackupSchema).default([]),
illnessEpisodes: z.array(illnessEpisodeBackupSchema).default([]),
allergies: z.array(allergyBackupSchema).default([]),
familyHistory: z.array(familyHistoryBackupSchema).default([]),
workouts: z.array(workoutBackupSchema).default([]),
documents: z.array(documentBackupSchema).default([]),
manifest: backupManifestSchema.nullable().default(null),
})
.passthrough();
@@ -218,6 +383,22 @@ export interface BackupSummary {
cycles: number;
/** v1.15.0 — cycle day-logs in the backup. */
cycleDayLogs: number;
/** v1.28 — lab results in the backup (export-only, see above). */
labResults: number;
/** v1.28 — biomarker catalog entries in the backup (export-only). */
biomarkers: number;
/** v1.28 — illness episodes, incl. flares/exacerbations (export-only). */
illnessEpisodes: number;
/** v1.28 — illness day-logs across every episode (export-only). */
illnessDayLogs: number;
/** v1.28 — allergy/intolerance records in the backup (export-only). */
allergies: number;
/** v1.28 — family-history entries in the backup (export-only). */
familyHistory: number;
/** v1.28 — workout summary records in the backup (export-only). */
workouts: number;
/** v1.28 — document manifest entries (metadata only, export-only). */
documents: number;
}
export function summarizeBackup(payload: BackupPayload): BackupSummary {
@@ -231,6 +412,17 @@ export function summarizeBackup(payload: BackupPayload): BackupSummary {
moodEntries: payload.moodEntries.length,
cycles: payload.cycles.length,
cycleDayLogs: payload.cycleDayLogs.length,
labResults: payload.labResults.length,
biomarkers: payload.biomarkers.length,
illnessEpisodes: payload.illnessEpisodes.length,
illnessDayLogs: payload.illnessEpisodes.reduce(
(sum, e) => sum + e.dayLogs.length,
0,
),
allergies: payload.allergies.length,
familyHistory: payload.familyHistory.length,
workouts: payload.workouts.length,
documents: payload.documents.length,
};
}