Report every restored section, disclose export decrypt losses, re-fold on zone change

- The restore summary counts practitioners, encounters, the three link
  tables, and vaccinations — restored in full since 08-01 but absent
  from the report, so a file carrying visits or an Impfpass read as if
  those sections were empty.
- A portable export that cannot open a field's ciphertext still nulls it
  fail-soft, but now names the loss in the file's own decryptFailures
  manifest — an export with a lost emergency note is no longer
  byte-identical to one where the note was never written.
- A timezone change enqueues the medication-compliance re-fold: the
  rollup keys its rows by the local day minted under the OLD zone, and
  the coverage probe compares counts, not keys, so nothing else could
  notice the stale bucketing.
This commit is contained in:
Marc-André Bombeck committed 2026-08-14 06:14:13 +02:00
1 parent ac44b35867
commit 97cb63a77f
7 files changed
+237

No files matched your search

@@ -0,0 +1,81 @@
/**
* v1.37.19 (A6-9) — the portable export's decryptFailures manifest.
*
* Watched red: with the collector dropped from `decryptProfileFieldSoft`
* (the pre-fix fail-soft that only nulled the field), the first case fails
* — an export with an unreadable emergency note was byte-identical to one
* where the note was never written, so the loss was invisible to the
* person restoring elsewhere.
*/
import { describe, expect, it, vi } from "vitest";
vi.mock("@/lib/ai/coach/bytes-codec", () => ({
decryptFromBytes: (buf: Uint8Array) => {
const tag = Buffer.from(buf).toString("utf8");
if (tag === "__bad__") throw new Error("unknown key id");
return `dec:${tag}`;
},
encryptToBytes: (s: string) => new Uint8Array(Buffer.from(s)),
}));
import { buildProfileBackupSection } from "../profile-backup";
function bytes(tag: string): Uint8Array {
return new Uint8Array(Buffer.from(tag, "utf8"));
}
function makePrisma(profileRow: Record<string, unknown> | null) {
return {
userHealthProfile: { findUnique: vi.fn(async () => profileRow) },
customMetric: { findMany: vi.fn(async () => []) },
healthProfileFactRevision: { findMany: vi.fn(async () => []) },
correlationPattern: { findMany: vi.fn(async () => []) },
} as never;
}
const PROFILE = {
id: "hp-1",
aboutMeEncrypted: bytes("about"),
conditionsEncrypted: null,
allergiesEncrypted: null,
coachFocusEncrypted: null,
pendingQuestionsEncrypted: null,
aiIncludedSections: undefined,
emergencyBloodType: null,
organDonorStatus: null,
advanceDirectiveStatus: null,
emergencyContactsEncrypted: null,
emergencyImplantsEncrypted: null,
emergencyNoteEncrypted: bytes("__bad__"),
createdAt: new Date("2026-08-01T00:00:00Z"),
updatedAt: new Date("2026-08-01T00:00:00Z"),
};
describe("buildProfileBackupSection — decryptFailures manifest", () => {
it("discloses an unreadable field in the file instead of a silent null", async () => {
const section = await buildProfileBackupSection(makePrisma(PROFILE), "u1");
// The field is still fail-soft null (one unreadable column must not
// cost the rest of the backup) …
expect(section.healthProfile?.emergencyNote).toBeNull();
expect(section.healthProfile?.aboutMe).toBe("dec:about");
// … but the loss is named in the manifest.
expect(section.decryptFailures).toEqual(["healthProfile.emergencyNote"]);
});
it("reports an empty manifest when everything decrypts", async () => {
const section = await buildProfileBackupSection(
makePrisma({ ...PROFILE, emergencyNoteEncrypted: bytes("note") }),
"u1",
);
expect(section.decryptFailures).toEqual([]);
});
it("never decrypts on the disaster-recovery path (empty manifest)", async () => {
const section = await buildProfileBackupSection(makePrisma(PROFILE), "u1", {
purpose: "disaster-recovery",
});
expect(section.decryptFailures).toEqual([]);
expect(section.healthProfile?.emergencyNote).toBeNull();
});
});
+25
View File
@@ -175,6 +175,16 @@ export interface ProfileBackupSection {
customMetrics: CustomMetricBackupEntry[];
healthProfileFacts: HealthProfileFactBackupEntry[];
correlationPatterns: CorrelationPatternBackupEntry[];
/**
* v1.37.19 (A6-9) — field paths whose ciphertext this instance could not
* open while building a PORTABLE export (fail-soft nulls). Disclosed in
* the file itself so an export with a nulled emergency field no longer
* reads byte-identical to one where the field was never written — the
* person restoring elsewhere can see exactly what was lost. Always empty
* on the disaster-recovery path (DR carries ciphertext verbatim and
* never decrypts).
*/
decryptFailures: string[];
}
export interface ProfileBackupCounts {
@@ -198,6 +208,8 @@ export interface ProfileBackupCounts {
function decryptProfileFieldSoft(
buf: Uint8Array | null,
field: string,
/** v1.37.19 (A6-9) — collector for the file's decryptFailures manifest. */
failures?: string[],
): string | null {
if (!buf || buf.byteLength === 0) return null;
try {
@@ -208,6 +220,7 @@ function decryptProfileFieldSoft(
err instanceof Error ? err.message : String(err)
}`,
);
failures?.push(`healthProfile.${field}`);
return null;
}
}
@@ -235,6 +248,9 @@ export async function buildProfileBackupSection(
options: ProfileBackupOptions = {},
): Promise<ProfileBackupSection> {
const disasterRecovery = options.purpose === "disaster-recovery";
// v1.37.19 (A6-9) — every fail-soft decrypt below records its field path
// here; the list rides the exported file as its decryptFailures manifest.
const decryptFailures: string[] = [];
const [profileRow, metricRows, factRows, patternRows] = await Promise.all([
prisma.userHealthProfile.findUnique({ where: { userId } }),
@@ -296,18 +312,22 @@ export async function buildProfileBackupSection(
aboutMe: decryptProfileFieldSoft(
profileRow.aboutMeEncrypted,
"aboutMe",
decryptFailures,
),
conditions: decryptProfileFieldSoft(
profileRow.conditionsEncrypted,
"conditions",
decryptFailures,
),
allergies: decryptProfileFieldSoft(
profileRow.allergiesEncrypted,
"allergies",
decryptFailures,
),
coachFocus: decryptProfileFieldSoft(
profileRow.coachFocusEncrypted,
"coachFocus",
decryptFailures,
),
aiIncludedSections: (profileRow.aiIncludedSections as
HealthProfileAiSection[] | undefined) ?? [
@@ -319,14 +339,17 @@ export async function buildProfileBackupSection(
emergencyContacts: decryptProfileFieldSoft(
profileRow.emergencyContactsEncrypted,
"emergencyContacts",
decryptFailures,
),
emergencyImplants: decryptProfileFieldSoft(
profileRow.emergencyImplantsEncrypted,
"emergencyImplants",
decryptFailures,
),
emergencyNote: decryptProfileFieldSoft(
profileRow.emergencyNoteEncrypted,
"emergencyNote",
decryptFailures,
),
}
: null;
@@ -353,6 +376,7 @@ export async function buildProfileBackupSection(
const value = decryptProfileFieldSoft(
fact.valueEncrypted,
`fact.${fact.kind}`,
decryptFailures,
);
const kind = fact.kind as HealthProfileFactKind;
if (
@@ -456,6 +480,7 @@ export async function buildProfileBackupSection(
healthProfileFacts,
customMetrics,
correlationPatterns,
decryptFailures,
};
}