fix(backups): preserve canonical restore identity

This commit is contained in:
Marc-André Bombeck committed 2026-07-20 13:25:37 +02:00
1 parent 8b7cbddd72
commit cd6b5f0cc6
10 files changed
+1722 -215

No files matched your search

@@ -1,4 +1,9 @@
import { describe, expect, it, vi } from "vitest";
import { Buffer } from "node:buffer";
import { encryptToBytes } from "@/lib/ai/coach/bytes-codec";
process.env.ENCRYPTION_KEY =
"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
const mocks = vi.hoisted(() => ({
findMeasurementsPaged: vi.fn(),
@@ -29,11 +34,132 @@ vi.mock("@/lib/export/records-backup", () => ({
import { buildFullBackupPayload } from "../full-backup-payload";
const deletedAt = new Date("2026-07-19T12:00:00.000Z");
const measurementNote = encryptToBytes("canonical measurement note");
const appSettings = {
id: "singleton",
registrationEnabled: false,
mfaRequired: true,
defaultLocale: "en",
telegramGlobal: false,
ntfyGlobal: false,
webPushGlobal: false,
webPushVapidPublicKey: "public-key",
webPushVapidPrivateKeyEncrypted: "encrypted-private-key",
webPushVapidSubject: "mailto:ops@example.test",
apiGlobal: false,
moodLogGlobal: false,
umamiEnabled: true,
umamiScriptUrl: "https://analytics.example.test/script.js",
umamiWebsiteId: "website-id",
glitchtipEnabled: true,
glitchtipDsn: "https://dsn.example.test/1",
glitchtipEnvironment: "recovery",
reminderLateMinutes: 45,
reminderMissedMinutes: 90,
adminAiKeyEncrypted: "encrypted-ai-key",
adminAiModel: "gpt-test",
adminAiBaseUrl: "https://ai.example.test/v1",
adminCodexAccessTokenEncrypted: "encrypted-access",
adminCodexRefreshTokenEncrypted: "encrypted-refresh",
adminCodexAccountIdEncrypted: "encrypted-account",
adminCodexTokenExpiresAt: new Date("2026-07-21T08:00:00.000Z"),
adminCodexConnectedAt: new Date("2026-07-20T08:00:00.000Z"),
adminCodexConnectionStatus: "connected",
adminAiInsightsFeedbackSummary: { helpful: 7, total: 9 },
defaultUserTimezone: "Europe/London",
assistantEnabled: false,
assistantCoachEnabled: false,
assistantBriefingEnabled: false,
assistantInsightStatusEnabled: false,
assistantCorrelationsEnabled: false,
assistantHealthScoreExplainerEnabled: false,
moduleAvailabilityJson: { nutrients: false, insights: true },
documentMaxFileBytes: 12_345_678,
documentQuotaBytes: 9_876_543_210n,
};
function makePrisma() {
return {
medication: { findMany: vi.fn().mockResolvedValue([]) },
medicationIntakeEvent: { findMany: vi.fn().mockResolvedValue([]) },
appSettings: { findUnique: vi.fn().mockResolvedValue(appSettings) },
medication: {
findMany: vi.fn().mockResolvedValue([
{
id: "medication-canonical",
name: "Example",
dose: "2 mg",
treatmentClass: "GENERIC",
dosesPerUnit: 4,
unitsPerDose: { toString: () => "0.5000" },
active: false,
notificationsEnabled: false,
pausedAt: new Date("2026-07-18T10:00:00.000Z"),
snoozedUntil: new Date("2026-07-22T10:00:00.000Z"),
startsOn: new Date("2026-07-01T00:00:00.000Z"),
endsOn: new Date("2026-08-01T00:00:00.000Z"),
oneShot: false,
asNeeded: false,
deliveryForm: "INJECTION",
trackInjectionSites: true,
allowedInjectionSites: ["THIGH_LEFT", "THIGH_RIGHT"],
liveActivityEnabled: true,
criticalAlarmEnabled: true,
atcCode: "A10BX10",
rxNormCode: "12345",
lowStockNotifiedAt: new Date("2026-07-17T10:00:00.000Z"),
lowStockNotifiedThresholdDays: 7,
reorderLeadDays: 3,
externalSource: "APPLE_HEALTH",
externalId: "med-external",
createdAt: new Date("2026-06-01T10:00:00.000Z"),
updatedAt: new Date("2026-07-19T10:00:00.000Z"),
schedules: [
{
id: "schedule-canonical",
windowStart: "08:00",
windowEnd: "10:00",
label: "Morning",
dose: "1 mg",
daysOfWeek: "i2;1,3,5",
timesOfDay: ["08:00", "20:00"],
reminderGraceMinutes: 90,
rrule: "FREQ=WEEKLY;INTERVAL=2;BYDAY=MO,WE,FR",
rollingIntervalDays: null,
scheduleType: "CYCLIC",
cyclicOnWeeks: 3,
cyclicOffWeeks: 1,
doseWindows: [
{ timeOfDay: "08:00", start: "07:30", end: "09:00" },
],
},
],
},
]),
},
medicationIntakeEvent: {
findMany: vi.fn().mockResolvedValue([
{
id: "intake-canonical",
medicationId: "medication-canonical",
medication: { name: "Example" },
scheduledFor: new Date("2026-07-19T08:00:00.000Z"),
takenAt: new Date("2026-07-19T08:05:00.000Z"),
skipped: false,
autoMissed: false,
attributionSource: "USER_PIN",
source: "APPLE_HEALTH",
idempotencyKey: "intake-idempotency",
createdAt: new Date("2026-07-19T08:05:00.000Z"),
injectionSite: "THIGH_LEFT",
doseTaken: "1 mg",
inventoryConsumption: [{ itemId: "pen-1", units: 0.5 }],
externalId: "intake-external",
updatedAt: new Date("2026-07-19T08:06:00.000Z"),
syncVersion: 4,
deletedAt,
},
]),
},
moodEntry: {
findMany: vi.fn().mockResolvedValue([
{
@@ -54,17 +180,29 @@ function makePrisma() {
}
function installSectionMocks() {
void measurementNote;
mocks.findMeasurementsPaged.mockResolvedValue([
{
id: "measurement-tombstone",
type: "WEIGHT",
type: "SLEEP_DURATION",
value: 75,
unit: "kg",
valueMin: 60,
valueMax: 90,
unit: "minutes",
measuredAt: new Date("2026-07-19T07:00:00.000Z"),
source: "MANUAL",
source: "IMPORT",
notes: null,
notesEncrypted: null,
notesEncrypted: measurementNote,
externalId: "oura-stage-deep",
externalSourceVersion: "oura-v3",
glucoseContext: null,
sleepStage: "DEEP",
rhythmClassification: null,
deviceType: "ring",
syncVersion: 7,
deletedAt,
createdAt: new Date("2026-07-19T07:01:00.000Z"),
updatedAt: new Date("2026-07-19T07:02:00.000Z"),
},
]);
mocks.buildCycleBackupSection.mockResolvedValue({
@@ -118,14 +256,63 @@ describe("buildFullBackupPayload disaster-recovery mode", () => {
{ purpose: "disaster-recovery" },
);
expect(payload).toMatchObject({
schemaVersion: "1",
schemaVersion: "2",
exportedAt: "2026-07-20T00:00:00.000Z",
appSettings: {
...appSettings,
adminCodexTokenExpiresAt:
appSettings.adminCodexTokenExpiresAt.toISOString(),
adminCodexConnectedAt: appSettings.adminCodexConnectedAt.toISOString(),
documentQuotaBytes: appSettings.documentQuotaBytes.toString(),
},
measurements: [
{
id: "measurement-tombstone",
type: "SLEEP_DURATION",
value: 75,
valueMin: 60,
valueMax: 90,
unit: "minutes",
measuredAt: "2026-07-19T07:00:00.000Z",
source: "IMPORT",
notesEncrypted: Buffer.from(measurementNote).toString("base64"),
externalId: "oura-stage-deep",
externalSourceVersion: "oura-v3",
glucoseContext: null,
sleepStage: "DEEP",
rhythmClassification: null,
deviceType: "ring",
syncVersion: 7,
deletedAt: deletedAt.toISOString(),
createdAt: "2026-07-19T07:01:00.000Z",
updatedAt: "2026-07-19T07:02:00.000Z",
},
],
medications: [
expect.objectContaining({
id: "medication-canonical",
asNeeded: false,
deliveryForm: "INJECTION",
unitsPerDose: "0.5000",
schedules: [
expect.objectContaining({
id: "schedule-canonical",
rrule: "FREQ=WEEKLY;INTERVAL=2;BYDAY=MO,WE,FR",
scheduleType: "CYCLIC",
cyclicOnWeeks: 3,
cyclicOffWeeks: 1,
}),
],
}),
],
intakeEvents: [
expect.objectContaining({
id: "intake-canonical",
medicationId: "medication-canonical",
syncVersion: 4,
deletedAt: deletedAt.toISOString(),
}),
],
moodEntries: [
{
id: "mood-tombstone",
@@ -234,6 +234,166 @@ describe("buildRecordsBackupSection", () => {
expect(section.documents[0].summary).toBe("Routine panel.");
});
it("preserves every canonical lab, illness, day-log, and allergy field verbatim", async () => {
const prisma = buildMockPrisma();
const deletedAt = new Date("2026-04-13T12:00:00.000Z");
const createdAt = new Date("2026-04-10T01:00:00.000Z");
const updatedAt = new Date("2026-04-12T23:00:00.000Z");
const labNote = encryptNoteToBytes("Canonical lab note");
const illnessNote = encryptToBytes("Canonical illness note");
const dayNote = encryptToBytes("Canonical day note");
const reaction = encryptToBytes("Canonical reaction");
const allergyNote = encryptToBytes("Canonical allergy note");
prisma.labResult.findMany.mockResolvedValueOnce([
{
id: "lab-canonical",
panel: "Lipid panel",
analyte: "LDL",
value: 118,
valueText: null,
unit: "mg/dL",
referenceLow: null,
referenceHigh: 130,
takenAt: new Date("2026-04-01T09:00:00.000Z"),
biomarkerId: "biomarker-canonical",
biomarker: { name: "LDL Cholesterol" },
source: "IMPORT",
noteEncrypted: labNote,
createdAt,
updatedAt,
deletedAt,
},
]);
prisma.illnessEpisode.findMany.mockResolvedValueOnce([
{
id: "episode-canonical",
label: "Migraine",
type: "CHRONIC",
lifecycle: "CHRONIC_ONGOING",
onsetAt: new Date("2026-04-10T00:00:00.000Z"),
resolvedAt: null,
parentConditionId: null,
noteEncrypted: illnessNote,
createdAt,
updatedAt,
deletedAt,
dayLogs: [
{
id: "day-canonical",
episodeId: "episode-canonical",
date: "2026-04-11",
functionalImpact: 2,
feverC: 38.2,
noteEncrypted: dayNote,
tz: "Europe/London",
createdAt,
updatedAt,
deletedAt,
symptomLinks: [{ severity: 3, symptom: { key: "headache" } }],
},
],
},
]);
prisma.allergy.findMany.mockResolvedValueOnce([
{
id: "allergy-canonical",
substance: "Penicillin",
category: "MEDICATION",
type: "ALLERGY",
severity: "SEVERE",
status: "INACTIVE",
onsetAt: new Date("2020-01-01T00:00:00.000Z"),
reactionEncrypted: reaction,
notesEncrypted: allergyNote,
createdAt,
updatedAt,
deletedAt,
},
]);
prisma.biomarker.findMany.mockResolvedValueOnce([]);
prisma.familyHistoryEntry.findMany.mockResolvedValueOnce([]);
prisma.workout.findMany.mockResolvedValueOnce([]);
prisma.inboundDocument.findMany.mockResolvedValueOnce([]);
const section = await buildRecordsBackupSection(prisma as never, USER_ID, {
purpose: "disaster-recovery",
});
const episodeQuery = prisma.illnessEpisode.findMany.mock.calls.at(-1)?.[0];
expect(episodeQuery).toEqual(
expect.objectContaining({ where: { userId: USER_ID } }),
);
expect(episodeQuery.include.dayLogs).not.toHaveProperty("where");
expect(prisma.allergy.findMany).toHaveBeenCalledWith(
expect.objectContaining({ where: { userId: USER_ID } }),
);
expect(section.labResults[0]).toEqual({
id: "lab-canonical",
panel: "Lipid panel",
analyte: "LDL",
value: 118,
valueText: null,
unit: "mg/dL",
referenceLow: null,
referenceHigh: 130,
takenAt: "2026-04-01T09:00:00.000Z",
biomarkerId: "biomarker-canonical",
biomarkerName: "LDL Cholesterol",
source: "IMPORT",
note: null,
noteEncrypted: Buffer.from(labNote).toString("base64"),
createdAt: createdAt.toISOString(),
updatedAt: updatedAt.toISOString(),
deletedAt: deletedAt.toISOString(),
});
expect(section.illnessEpisodes[0]).toEqual({
id: "episode-canonical",
label: "Migraine",
type: "CHRONIC",
lifecycle: "CHRONIC_ONGOING",
onsetAt: "2026-04-10T00:00:00.000Z",
resolvedAt: null,
parentConditionId: null,
note: null,
noteEncrypted: Buffer.from(illnessNote).toString("base64"),
createdAt: createdAt.toISOString(),
updatedAt: updatedAt.toISOString(),
deletedAt: deletedAt.toISOString(),
dayLogs: [
{
id: "day-canonical",
episodeId: "episode-canonical",
date: "2026-04-11",
functionalImpact: 2,
feverC: 38.2,
note: null,
noteEncrypted: Buffer.from(dayNote).toString("base64"),
tz: "Europe/London",
createdAt: createdAt.toISOString(),
updatedAt: updatedAt.toISOString(),
deletedAt: deletedAt.toISOString(),
symptoms: [{ key: "headache", severity: 3 }],
},
],
});
expect(section.allergies[0]).toEqual({
id: "allergy-canonical",
substance: "Penicillin",
category: "MEDICATION",
type: "ALLERGY",
severity: "SEVERE",
status: "INACTIVE",
onsetAt: "2020-01-01T00:00:00.000Z",
reaction: null,
note: null,
reactionEncrypted: Buffer.from(reaction).toString("base64"),
notesEncrypted: Buffer.from(allergyNote).toString("base64"),
createdAt: createdAt.toISOString(),
updatedAt: updatedAt.toISOString(),
deletedAt: deletedAt.toISOString(),
});
});
it("threads an illness flare's parentConditionId and nests its day-log + symptom", async () => {
const prisma = buildMockPrisma();
const section = await buildRecordsBackupSection(prisma as never, USER_ID);