mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-14 06:40:50 +00:00
The GPS track of an outdoor workout was stored readable, and its first and last points are usually the person's front door. The phone number and address in the address book of doctors and practices were readable too, while the note beside them was already encrypted. Migration 0361 adds workout_routes.geometry_encrypted (the geometry loses its NOT NULL) and practitioners.phone_encrypted / location_encrypted, plus partial indexes on the backfill's discovery predicates. A track is sealed as one binary AES-256-GCM value bound to its purpose; the contact fields use the same Bytes codec as the note. The practitioner's name, practice and specialty stay readable, because the picker searches and sorts on them. Every writer stores ciphertext only: workout batch ingest, practitioner create and edit, and both restore formats. Readers prefer the ciphertext and fall back to the old column for rows not yet migrated: the workout detail (map, splits, GPX), the activity insight's climb figure, the practitioner DTO behind the address book, visits and vaccinations. The wire shape does not change. An edit's audit row now names a changed phone number or address without recording either value. free-text-encryption-backfill covers the three columns in the same pass, finding a route through its workout. All three are registered for key rotation (registry, CLI script, and the in-app rotation). A disaster-recovery backup carries the contact fields as ciphertext only; a portable export carries them readable. Workout routes are still not part of a backup, as before. The old columns are marked for removal in a later release.
153 lines
4.8 KiB
TypeScript
153 lines
4.8 KiB
TypeScript
/**
|
|
* `GET /api/practitioners` — the account's own address book of doctors and
|
|
* practices, name-ordered and searchable.
|
|
* `POST /api/practitioners` — add one.
|
|
*
|
|
* No module gate: an address book is core, like the checkups page the visits
|
|
* that reference it live on. The reasoning is written at the `Practitioner`
|
|
* model in `prisma/schema.prisma`.
|
|
*
|
|
* `userId` is narrowed from auth and fed to the Prisma `where`; it is never a
|
|
* body field. The `data` object is built field-by-field, never spread from the
|
|
* parsed body. `note`, `phone` and `location` are encrypted at rest; `name`,
|
|
* `practice` and `specialty` stay plaintext so the picker can search and sort
|
|
* them in SQL.
|
|
*/
|
|
import { NextRequest } from "next/server";
|
|
|
|
import { prisma } from "@/lib/db";
|
|
import { apiHandler, requireRecordAuth } from "@/lib/api-handler";
|
|
import { annotate } from "@/lib/logging/context";
|
|
import { auditLog } from "@/lib/auth/audit";
|
|
import {
|
|
apiSuccess,
|
|
getClientIp,
|
|
returnAllZodIssues,
|
|
safeJson,
|
|
} from "@/lib/api-response";
|
|
import { withIdempotency } from "@/lib/idempotency";
|
|
import { encryptToBytes } from "@/lib/ai/coach/bytes-codec";
|
|
import { encryptNote } from "@/lib/crypto/note-cipher";
|
|
import {
|
|
practitionerCreateSchema,
|
|
practitionerListQuerySchema,
|
|
} from "@/lib/validations/practitioners";
|
|
import { toPractitionerDTO } from "@/lib/practitioners/dto";
|
|
|
|
export const GET = apiHandler(async (request: NextRequest) => {
|
|
const { user } = await requireRecordAuth("read", "profile");
|
|
|
|
const params = new URL(request.url).searchParams;
|
|
const parsed = practitionerListQuerySchema.safeParse({
|
|
q: params.get("q") ?? undefined,
|
|
limit: params.get("limit") ?? undefined,
|
|
});
|
|
if (!parsed.success) {
|
|
return returnAllZodIssues(parsed.error, 422, {
|
|
errorCode: "practitioner.invalid",
|
|
});
|
|
}
|
|
|
|
const rows = await prisma.practitioner.findMany({
|
|
where: {
|
|
userId: user.id,
|
|
deletedAt: null,
|
|
// Three plaintext columns, because a person looks a practice up by
|
|
// whichever they remember: the doctor's name on the referral, the
|
|
// practice name on the door, or the field they need ("Zahnmedizin").
|
|
// Searching only name + practice made the specialty attempt return
|
|
// nothing and read as "not in the address book".
|
|
...(parsed.data.q
|
|
? {
|
|
OR: [
|
|
{
|
|
name: {
|
|
contains: parsed.data.q,
|
|
mode: "insensitive" as const,
|
|
},
|
|
},
|
|
{
|
|
practice: {
|
|
contains: parsed.data.q,
|
|
mode: "insensitive" as const,
|
|
},
|
|
},
|
|
{
|
|
specialty: {
|
|
contains: parsed.data.q,
|
|
mode: "insensitive" as const,
|
|
},
|
|
},
|
|
],
|
|
}
|
|
: {}),
|
|
},
|
|
orderBy: { name: "asc" },
|
|
take: parsed.data.limit ?? 100,
|
|
});
|
|
|
|
annotate({
|
|
action: { name: "practitioner.contact.list", entity_type: "practitioner" },
|
|
meta: { count: rows.length },
|
|
});
|
|
|
|
return apiSuccess(rows.map(toPractitionerDTO));
|
|
});
|
|
|
|
// A double-tap on "save" must not mint a second copy of the same practice.
|
|
export const POST = apiHandler(
|
|
withIdempotency<[NextRequest]>(postPractitioner),
|
|
);
|
|
|
|
async function postPractitioner(request: NextRequest): Promise<Response> {
|
|
const { user } = await requireRecordAuth("write", "profile");
|
|
|
|
const { data: rawBody, error: jsonError } = await safeJson(request, {
|
|
maxBytes: 16 * 1024,
|
|
});
|
|
if (jsonError) return jsonError;
|
|
|
|
const parsed = practitionerCreateSchema.safeParse(rawBody);
|
|
if (!parsed.success) {
|
|
annotate({
|
|
action: { name: "practitioner.contact.validation-failed" },
|
|
meta: { issue_count: parsed.error.issues.length },
|
|
});
|
|
return returnAllZodIssues(parsed.error, 422, {
|
|
errorCode: "practitioner.invalid",
|
|
});
|
|
}
|
|
|
|
const entry = parsed.data;
|
|
|
|
// Field-by-field — never spread the parsed object whole.
|
|
const created = await prisma.practitioner.create({
|
|
data: {
|
|
userId: user.id,
|
|
name: entry.name,
|
|
specialty: entry.specialty ?? null,
|
|
practice: entry.practice ?? null,
|
|
// v1.39.4 — ciphertext only; the readable columns stay NULL.
|
|
locationEncrypted: encryptNote(entry.location),
|
|
phoneEncrypted: encryptNote(entry.phone),
|
|
noteEncrypted: entry.note ? encryptToBytes(entry.note) : null,
|
|
},
|
|
});
|
|
|
|
await auditLog("practitioner.contact.create", {
|
|
userId: user.id,
|
|
ipAddress: getClientIp(request),
|
|
details: { practitionerId: created.id },
|
|
});
|
|
|
|
annotate({
|
|
action: {
|
|
name: "practitioner.contact.create",
|
|
entity_type: "practitioner",
|
|
entity_id: created.id,
|
|
},
|
|
});
|
|
|
|
return apiSuccess(toPractitionerDTO(created), 201);
|
|
}
|