feat(export): offer a passphrase-encrypted archive

Add an opt-in to download the full backup as an encrypted archive instead
of a plaintext JSON file. The user supplies a passphrase over the request;
the server derives a 256-bit key with Argon2id and seals the export bytes
with AES-256-GCM into a self-describing HLX1 archive (magic, version, KDF
params, salt, iv, tag, ciphertext), mirroring the off-host backup envelope.

POST /api/export/encrypted returns the binary archive and is step-up gated
for accounts with a second factor; single-factor accounts use a normal
session. The passphrase is never stored and never logged, and there is no
server-side recovery — the UI states this. A standalone decryptor
(scripts/decrypt-export.ts) opens the archive with the passphrase outside
the app. The plaintext full-backup route now shares one payload builder so
both variants emit the same restore-compatible shape.
This commit is contained in:
Marc-André Bombeck committed 2026-06-27 20:27:07 +02:00
1 parent 6d053c3667
commit 0ba77778d5
17 files changed
+999 -125

No files matched your search

@@ -0,0 +1,80 @@
import { describe, it, expect } from "vitest";
import { Buffer } from "node:buffer";
import {
encryptArchive,
decryptArchive,
parseArchiveHeader,
EXPORT_ARGON2_PARAMS,
MIN_EXPORT_PASSPHRASE_LENGTH,
} from "../passphrase-archive";
const PASSPHRASE = "correct horse battery staple";
const PAYLOAD = JSON.stringify({
schemaVersion: 1,
measurements: [{ type: "WEIGHT", value: 81.2, unit: "kg" }],
note: "Zugangsdaten 🔐 € ñ",
});
describe("passphrase-encrypted export archive (HLX1)", () => {
it("round-trips encrypt -> decrypt with the right passphrase", async () => {
const archive = await encryptArchive(PAYLOAD, PASSPHRASE);
const out = await decryptArchive(archive, PASSPHRASE);
expect(out).toBe(PAYLOAD);
});
it("emits the HLX1 magic + version header", async () => {
const archive = await encryptArchive(PAYLOAD, PASSPHRASE);
expect(archive.subarray(0, 4).toString("ascii")).toBe("HLX1");
expect(archive.readUInt8(4)).toBe(0x01); // version
expect(archive.readUInt8(5)).toBe(0x01); // KDF = Argon2id
});
it("carries the Argon2id KDF params + salt in the header", async () => {
const archive = await encryptArchive(PAYLOAD, PASSPHRASE);
const { header, bodyOffset } = parseArchiveHeader(archive);
expect(header.memoryCost).toBe(EXPORT_ARGON2_PARAMS.memoryCost);
expect(header.timeCost).toBe(EXPORT_ARGON2_PARAMS.timeCost);
expect(header.parallelism).toBe(EXPORT_ARGON2_PARAMS.parallelism);
expect(header.salt.length).toBe(16);
expect(bodyOffset).toBe(16 + 16 + 12 + 16); // header + salt + iv + tag
});
it("uses a random salt + iv so two archives of the same input differ", async () => {
const a = await encryptArchive(PAYLOAD, PASSPHRASE);
const b = await encryptArchive(PAYLOAD, PASSPHRASE);
expect(Buffer.compare(a, b)).not.toBe(0);
// ...but both decrypt back to the same plaintext.
expect(await decryptArchive(a, PASSPHRASE)).toBe(PAYLOAD);
expect(await decryptArchive(b, PASSPHRASE)).toBe(PAYLOAD);
});
it("fails cleanly with a wrong passphrase (no plaintext leak)", async () => {
const archive = await encryptArchive(PAYLOAD, PASSPHRASE);
await expect(
decryptArchive(archive, "totally wrong passphrase"),
).rejects.toThrow(/wrong passphrase or corrupt archive/i);
});
it("fails when the ciphertext is tampered", async () => {
const archive = await encryptArchive(PAYLOAD, PASSPHRASE);
const tampered = Buffer.from(archive);
tampered[tampered.length - 1] ^= 0xff; // flip a ciphertext bit
await expect(decryptArchive(tampered, PASSPHRASE)).rejects.toThrow();
});
it("rejects a passphrase shorter than the minimum on encrypt", async () => {
await expect(encryptArchive(PAYLOAD, "short")).rejects.toThrow(
new RegExp(`at least ${MIN_EXPORT_PASSPHRASE_LENGTH}`),
);
});
it("rejects a non-HLX1 buffer", () => {
expect(() => parseArchiveHeader(Buffer.from("not an archive"))).toThrow();
});
it("accepts a Buffer payload, not only a string", async () => {
const buf = Buffer.from(PAYLOAD, "utf8");
const archive = await encryptArchive(buf, PASSPHRASE);
expect(await decryptArchive(archive, PASSPHRASE)).toBe(PAYLOAD);
});
});
+128
View File
@@ -0,0 +1,128 @@
/**
* v1.23 — shared builder for the user-scoped full-backup payload.
*
* Extracted so both the plaintext `GET /api/export/full-backup` route and the
* passphrase-encrypted `POST /api/export/encrypted` route emit the byte-for-byte
* same shape — the one that the pg-boss `data-backup` worker writes and that
* `parseBackupPayload()` round-trips on admin restore. Keep this writer in sync
* with the `data-backup` worker (`src/lib/jobs/reminder-worker.ts`).
*
* The decrypted notes are surfaced here (the backup is the human-readable
* artefact); an admin restore re-encrypts them on re-insert.
*/
import type { PrismaClient } from "@/generated/prisma/client";
import { readNote } from "@/lib/crypto/note-cipher";
import { BACKUP_SCHEMA_VERSION } from "@/lib/validations/backup";
import { buildCycleBackupSection } from "@/lib/cycle/backup";
export interface FullBackupCounts {
measurements: number;
medications: number;
intakeEvents: number;
moodEntries: number;
cycles: number;
cycleDayLogs: number;
}
export interface FullBackupResult {
payload: Record<string, unknown>;
counts: FullBackupCounts;
}
/**
* Build the canonical full-backup payload for `userId`. Soft-deleted rows are
* excluded so a round-trip via admin restore never resurrects deleted records.
*/
export async function buildFullBackupPayload(
prisma: PrismaClient,
userId: string,
): Promise<FullBackupResult> {
const [measurements, medications, intakeEvents, moodEntries, cycle] =
await Promise.all([
prisma.measurement.findMany({
where: { userId, deletedAt: null },
orderBy: { measuredAt: "desc" },
}),
prisma.medication.findMany({
where: { userId },
select: {
name: true,
dose: true,
active: true,
schedules: {
select: {
windowStart: true,
windowEnd: true,
label: true,
dose: true,
},
},
},
}),
prisma.medicationIntakeEvent.findMany({
where: { userId, deletedAt: null },
include: { medication: { select: { name: true } } },
orderBy: { scheduledFor: "desc" },
}),
prisma.moodEntry.findMany({
where: { userId, deletedAt: null },
orderBy: { moodLoggedAt: "desc" },
}),
buildCycleBackupSection(prisma, userId),
]);
const payload = {
schemaVersion: BACKUP_SCHEMA_VERSION,
exportedAt: new Date().toISOString(),
userId,
measurements: measurements.map((m) => ({
type: m.type,
value: m.value,
unit: m.unit,
measuredAt: m.measuredAt.toISOString(),
source: m.source,
notes: readNote(m.notesEncrypted, m.notes),
})),
medications: medications.map((m) => ({
name: m.name,
dose: m.dose,
active: m.active,
schedules: m.schedules.map((s) => ({
windowStart: s.windowStart,
windowEnd: s.windowEnd,
label: s.label,
dose: s.dose,
})),
})),
intakeEvents: intakeEvents.map((e) => ({
medication: e.medication.name,
scheduledFor: e.scheduledFor.toISOString(),
takenAt: e.takenAt?.toISOString() ?? null,
skipped: e.skipped,
source: e.source,
})),
moodEntries: moodEntries.map((e) => ({
date: e.date,
mood: e.mood,
score: e.score,
tags: e.tags,
source: e.source,
loggedAt: e.moodLoggedAt.toISOString(),
})),
cycleProfile: cycle.cycleProfile,
cycles: cycle.cycles,
cycleDayLogs: cycle.cycleDayLogs,
};
return {
payload,
counts: {
measurements: measurements.length,
medications: medications.length,
intakeEvents: intakeEvents.length,
moodEntries: moodEntries.length,
cycles: cycle.cycles.length,
cycleDayLogs: cycle.cycleDayLogs.length,
},
};
}
+227
View File
@@ -0,0 +1,227 @@
/**
* v1.23 — passphrase-encrypted export archive (`HLX1` wire format).
*
* A user can choose to download their export as an encrypted archive instead
* of plaintext JSON. The passphrase the user supplies is run through Argon2id
* to derive a 256-bit key, and the export bytes are sealed with AES-256-GCM.
*
* THREAT MODEL. The data is already plaintext-at-rest on the server (the
* server computes insights / rollups / FHIR over it). What this closes is the
* "plaintext health file lands in Downloads / iCloud / Google-Drive sync"
* path: the file that leaves the server is opaque without the passphrase.
* There is NO server-side recovery — the passphrase is never stored and never
* logged, so a forgotten passphrase means the archive is unrecoverable. The
* UI states this loudly.
*
* Wire format (binary), mirroring the off-host backup `HLBK` envelope so there
* is one decryption mental model in the codebase + docs:
*
* magic(4) = "HLX1"
* version(1) = 0x01
* kdf(1) = 0x01 (Argon2id)
* memoryCost(4) = uint32 BE (KiB; Argon2 `m`)
* timeCost(4) = uint32 BE (Argon2 `t`)
* parallelism(1)= uint8 (Argon2 `p`)
* saltLen(1) = uint8 (= 16)
* salt(saltLen)
* iv(12) (AES-GCM nonce)
* tag(16) (AES-GCM auth tag)
* ciphertext(...)
*
* The Argon2 params travel in the header (self-describing) so a future cost
* bump still decrypts every previously-written archive — the decryptor reads
* `m/t/p` + `salt` from the file, never from a constant. The standalone
* `scripts/decrypt-export.ts` decryptor depends ONLY on this module, so a user
* can open the archive with `pnpm dlx tsx` and their passphrase, app or not.
*
* KDF defaults are the 2025 OWASP minimum for Argon2id (RFC 9106):
* 19 MiB / t=2 / p=1, 32-byte output. Kept independent from the password
* hashing params so tuning one never silently changes the other.
*/
import { hashRaw, type Algorithm } from "@node-rs/argon2";
import {
createCipheriv,
createDecipheriv,
randomBytes,
timingSafeEqual,
} from "node:crypto";
const MAGIC = "HLX1";
const VERSION = 0x01;
const KDF_ARGON2ID = 0x01;
// `Algorithm.Argon2id` is a const enum (= 2); reference the value directly so
// the module compiles under `isolatedModules` without importing the enum.
const ARGON2ID: Algorithm = 2 as Algorithm;
const ALGORITHM = "aes-256-gcm";
const IV_LENGTH = 12;
const TAG_LENGTH = 16;
const SALT_LENGTH = 16;
const KEY_LENGTH = 32;
/**
* Argon2id KDF parameters for newly-written archives. OWASP-minimum for
* 2025 (RFC 9106): 19 MiB memory, 2 passes, single lane, 32-byte key.
* These are written into each archive header, so changing them never
* orphans archives written under the old cost.
*/
export const EXPORT_ARGON2_PARAMS = {
/** Argon2 `m` — memory cost in KiB (19 MiB). */
memoryCost: 19456,
/** Argon2 `t` — iterations. */
timeCost: 2,
/** Argon2 `p` — lanes. */
parallelism: 1,
} as const;
/**
* Minimum passphrase length the encrypt path enforces. A short passphrase
* defeats the KDF; 12 mirrors the account password floor.
*/
export const MIN_EXPORT_PASSPHRASE_LENGTH = 12;
export interface ArchiveHeader {
version: number;
kdf: number;
memoryCost: number;
timeCost: number;
parallelism: number;
salt: Buffer;
}
/** Derive the 256-bit AES key from a passphrase + the archive's KDF params. */
async function deriveKey(
passphrase: string,
params: { memoryCost: number; timeCost: number; parallelism: number },
salt: Buffer,
): Promise<Buffer> {
return hashRaw(passphrase, {
algorithm: ARGON2ID,
memoryCost: params.memoryCost,
timeCost: params.timeCost,
parallelism: params.parallelism,
outputLen: KEY_LENGTH,
salt,
});
}
/**
* Encrypt `plaintext` into an `HLX1` archive sealed with `passphrase`.
* Throws if the passphrase is shorter than `MIN_EXPORT_PASSPHRASE_LENGTH`.
*/
export async function encryptArchive(
plaintext: string | Buffer,
passphrase: string,
): Promise<Buffer> {
if (passphrase.length < MIN_EXPORT_PASSPHRASE_LENGTH) {
throw new Error(
`Passphrase must be at least ${MIN_EXPORT_PASSPHRASE_LENGTH} characters`,
);
}
const salt = randomBytes(SALT_LENGTH);
const key = await deriveKey(passphrase, EXPORT_ARGON2_PARAMS, salt);
const iv = randomBytes(IV_LENGTH);
const cipher = createCipheriv(ALGORITHM, key, iv);
const body =
typeof plaintext === "string" ? Buffer.from(plaintext, "utf8") : plaintext;
const ciphertext = Buffer.concat([cipher.update(body), cipher.final()]);
const tag = cipher.getAuthTag();
const header = Buffer.alloc(4 + 1 + 1 + 4 + 4 + 1 + 1);
header.write(MAGIC, 0, "ascii");
header.writeUInt8(VERSION, 4);
header.writeUInt8(KDF_ARGON2ID, 5);
header.writeUInt32BE(EXPORT_ARGON2_PARAMS.memoryCost, 6);
header.writeUInt32BE(EXPORT_ARGON2_PARAMS.timeCost, 10);
header.writeUInt8(EXPORT_ARGON2_PARAMS.parallelism, 14);
header.writeUInt8(SALT_LENGTH, 15);
return Buffer.concat([header, salt, iv, tag, ciphertext]);
}
/** Parse + validate the fixed `HLX1` header. Throws on any structural fault. */
export function parseArchiveHeader(buf: Buffer): {
header: ArchiveHeader;
bodyOffset: number;
} {
if (buf.length < 16) {
throw new Error("Not an HLX1 archive (too short)");
}
const magic = buf.subarray(0, 4).toString("ascii");
if (!timingSafeEqual(Buffer.from(magic), Buffer.from(MAGIC))) {
throw new Error("Not an HLX1 archive (bad magic)");
}
const version = buf.readUInt8(4);
if (version !== VERSION) {
throw new Error(`Unsupported HLX1 version ${version}`);
}
const kdf = buf.readUInt8(5);
if (kdf !== KDF_ARGON2ID) {
throw new Error(`Unsupported KDF id ${kdf}`);
}
const memoryCost = buf.readUInt32BE(6);
const timeCost = buf.readUInt32BE(10);
const parallelism = buf.readUInt8(14);
const saltLen = buf.readUInt8(15);
const saltStart = 16;
const ivStart = saltStart + saltLen;
const tagStart = ivStart + IV_LENGTH;
const bodyOffset = tagStart + TAG_LENGTH;
if (buf.length < bodyOffset) {
throw new Error("Corrupt HLX1 archive (truncated header)");
}
if (memoryCost < 1 || timeCost < 1 || parallelism < 1 || saltLen < 8) {
throw new Error("Corrupt HLX1 archive (implausible KDF params)");
}
return {
header: {
version,
kdf,
memoryCost,
timeCost,
parallelism,
salt: buf.subarray(saltStart, ivStart),
},
bodyOffset,
};
}
/**
* Decrypt an `HLX1` archive with `passphrase`. A wrong passphrase fails the
* GCM authentication tag and throws a clean, generic error (no oracle about
* which part was wrong). The returned value is the original plaintext (UTF-8).
*/
export async function decryptArchive(
buf: Buffer,
passphrase: string,
): Promise<string> {
const { header, bodyOffset } = parseArchiveHeader(buf);
const saltLen = header.salt.length;
const ivStart = 16 + saltLen;
const tagStart = ivStart + IV_LENGTH;
const iv = buf.subarray(ivStart, tagStart);
const tag = buf.subarray(tagStart, bodyOffset);
const ciphertext = buf.subarray(bodyOffset);
const key = await deriveKey(
passphrase,
{
memoryCost: header.memoryCost,
timeCost: header.timeCost,
parallelism: header.parallelism,
},
Buffer.from(header.salt),
);
try {
const decipher = createDecipheriv(ALGORITHM, key, iv);
decipher.setAuthTag(tag);
const out = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
return out.toString("utf8");
} catch {
// GCM tag mismatch — wrong passphrase or a tampered/corrupt archive.
// Deliberately opaque: never reveal which.
throw new Error("Decryption failed — wrong passphrase or corrupt archive");
}
}