chore(release): v1.5.6

Pure-history medication detail page, legacy step consolidation, and the
finish of the outbound-fetch migration.

- /medications/[id] becomes a read-only history surface; every setting
  moves into a new advanced-settings sheet, and the edit trigger becomes
  a two-option picker. The list page is unchanged.
- A pg-boss job folds pre-v1.5.0 granular step rows into one canonical
  daily total per user per day and soft-deletes the originals; migration
  0087 adds a partial index for the converging discovery scan.
- Every remaining server-side fetch routes through safeFetch (Withings,
  Codex OAuth + SSE, bug-report, Umami, GlitchTip, Loki); a new
  healthlog/safe-fetch-required ESLint rule guards the boundary.
- Fixes: intake-edit dialog seeded from real values, consolidation skips
  a unique-constraint day instead of stranding it, avatar upload reads
  the body once under a bounded cap, egress lint rejects absolute URLs.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Marc-André BombeckandClaude Opus 4.7 committed 2026-05-29 22:07:10 +02:00
1 parent d54addd61a
commit 8528c3b4fe
54 files changed
+2343 -324

No files matched your search

@@ -89,15 +89,20 @@ export const POST = apiHandler(async (request: NextRequest) => {
let lastDetails = "";
for (const targetUrl of targetUrls) {
const upstream = await safeFetch(targetUrl, {
method: "POST",
headers: {
"content-type": "application/json",
"user-agent": "healthlog-admin-monitoring-test",
const upstream = await safeFetch(
targetUrl,
{
method: "POST",
headers: {
"content-type": "application/json",
"user-agent": "healthlog-admin-monitoring-test",
},
body: JSON.stringify(payload),
cache: "no-store",
},
body: JSON.stringify(payload),
cache: "no-store",
});
// Operator-configured Umami host — pin the connect-time IP.
{ requirePublicHost: true },
);
if (upstream.ok) {
return apiSuccess({
+1 -1
View File
@@ -159,7 +159,7 @@ export const POST = apiHandler(async (request: NextRequest) => {
// GitHub doesn't support base64 in comments, so we note the limitation
const commentBody = `### Screenshot\n\n![Screenshot](data:image/${ext};base64,${base64Data.slice(0, 100)}...)\n\n*Note: The full screenshot was truncated due to size limits. Please contact the user directly.*`;
await fetch(
await safeFetch(
`https://api.github.com/repos/${ghRepo}/issues/${issue.number}/comments`,
{
method: "POST",
+10 -3
View File
@@ -26,9 +26,16 @@ export const GET = apiHandler(async () => {
});
}
const response = await safeFetch(settings.umamiScriptUrl, {
next: { revalidate: 3600 },
});
const response = await safeFetch(
settings.umamiScriptUrl,
{
next: { revalidate: 3600 },
},
// Operator-configured host — pin the connect-time IP so a low-TTL
// DNS record cannot rebind the fetch at an internal range between
// the input-time `isPublicUrl` accept and the socket connect.
{ requirePublicHost: true },
);
if (!response.ok) {
return new NextResponse(NOOP_SCRIPT, {
status: 200,
+14 -9
View File
@@ -74,16 +74,21 @@ export const POST = apiHandler(async (request: NextRequest) => {
let lastResponseStatus = 404;
for (const targetUrl of targetUrls) {
const upstream = await safeFetch(targetUrl, {
method: "POST",
headers: {
"content-type":
request.headers.get("content-type") || "application/json",
"user-agent": request.headers.get("user-agent") || "healthlog-proxy",
const upstream = await safeFetch(
targetUrl,
{
method: "POST",
headers: {
"content-type":
request.headers.get("content-type") || "application/json",
"user-agent": request.headers.get("user-agent") || "healthlog-proxy",
},
body,
cache: "no-store",
},
body,
cache: "no-store",
});
// Operator-configured Umami host — pin the connect-time IP.
{ requirePublicHost: true },
);
lastResponseStatus = upstream.status;
@@ -146,6 +146,41 @@ describe("POST /api/user/avatar", () => {
expect(prisma.user.update).not.toHaveBeenCalled();
});
it("rejects an oversize chunked upload with no Content-Length at the stream level (413)", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
// Build a multipart body as a streamed ReadableStream with NO
// Content-Length header — the shape a `Transfer-Encoding: chunked`
// upload takes. The bounded stream reader must trip before the body
// is fully buffered.
const boundary = "----healthlogtest";
const head = Buffer.from(
`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="a.png"\r\nContent-Type: image/png\r\n\r\n`,
);
const tail = Buffer.from(`\r\n--${boundary}--\r\n`);
const oversize = Buffer.alloc(2 * 1024 * 1024 + 1, 0x41);
const parts = [head, oversize, tail];
const stream = new ReadableStream<Uint8Array>({
start(controller) {
for (const p of parts) {
controller.enqueue(new Uint8Array(p));
}
controller.close();
},
});
const req = new Request("http://localhost/api/user/avatar", {
method: "POST",
headers: { "content-type": `multipart/form-data; boundary=${boundary}` },
body: stream,
// Node's fetch requires `duplex: "half"` for a streamed body.
duplex: "half",
} as RequestInit & { duplex: "half" });
const res = await post(req);
expect(res.status).toBe(413);
expect(prisma.user.update).not.toHaveBeenCalled();
});
it("rejects an unsupported MIME with 415 (magic-byte sniff)", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
// Plain text content — no JPEG/PNG/WebP magic.
+83 -1
View File
@@ -62,6 +62,67 @@ interface UploadResponse {
updatedAt: string;
}
/** Thrown by `readBoundedBody` when the stream exceeds the byte cap. */
class BodyTooLargeError extends Error {
constructor() {
super("Request body exceeds the configured byte cap");
this.name = "BodyTooLargeError";
}
}
/**
* Read a request body stream into a single buffer while counting bytes,
* throwing `BodyTooLargeError` the moment the running total passes
* `maxBytes`. Bounds the work at the stream level so a chunked /
* unbounded upload cannot park past the cap even when no `Content-Length`
* header is present. The captured bytes are retained (capped at
* `maxBytes`) so the caller can reconstruct `FormData` from them — this
* reads the body exactly once, with no clone and no second parser racing
* the same body, so a cap trip frees the allocation immediately instead
* of leaving a native parse buffering the rest of an oversized upload.
*/
async function readBoundedBody(
body: ReadableStream<Uint8Array> | null,
maxBytes: number,
): Promise<Uint8Array<ArrayBuffer>> {
if (!body) return new Uint8Array(0);
const reader = body.getReader();
const chunks: Uint8Array[] = [];
let retained = 0;
let overflow = false;
try {
for (;;) {
const { done, value } = await reader.read();
if (done) break;
if (overflow) continue;
if (retained + value.byteLength > maxBytes) {
// Past the cap. Drop everything retained so far and stop
// retaining further chunks — memory stays bounded at the cap.
// Keep draining the stream to its natural close rather than
// cancelling it: an abrupt cancel mid-transfer races the
// underlying (undici) producer, which then enqueues into a
// closed controller and surfaces as an unhandled rejection.
chunks.length = 0;
retained = 0;
overflow = true;
continue;
}
chunks.push(value);
retained += value.byteLength;
}
} finally {
reader.releaseLock();
}
if (overflow) throw new BodyTooLargeError();
const out = new Uint8Array(retained);
let offset = 0;
for (const chunk of chunks) {
out.set(chunk, offset);
offset += chunk.byteLength;
}
return out;
}
export const POST = apiHandler(async (request: Request) => {
const { user } = await requireAuth();
@@ -94,10 +155,31 @@ export const POST = apiHandler(async (request: Request) => {
);
}
// Stream-level cap. The Content-Length pre-flight above only fires when
// the header is present; a `Transfer-Encoding: chunked` upload (or any
// client that omits the header) skips it, and `request.formData()`
// would then buffer the whole stream before the post-parse `file.size`
// check can run. Read the body ONCE through a bounded reader that
// aborts on the first byte past AVATAR_MAX_BYTES, then reconstruct the
// FormData from the captured bytes. A single read means the cap trip
// frees the allocation immediately — no clone, no tee, and no native
// parse left buffering the rest of an oversized body. The post-parse
// `file.size` check stays in place as defence-in-depth.
let formData: FormData;
try {
formData = await request.formData();
const bytes = await readBoundedBody(request.body, AVATAR_MAX_BYTES);
formData = await new Response(new Blob([bytes]), {
headers: { "content-type": request.headers.get("content-type") ?? "" },
}).formData();
} catch (err) {
// Surface the most useful failure: a cap overflow always wins.
if (err instanceof BodyTooLargeError) {
annotate({
action: { name: "user.avatar.upload.rejected" },
meta: { reason: "stream_size_exceeded" },
});
return apiError(`Upload exceeds ${AVATAR_MAX_BYTES} byte limit`, 413);
}
return apiError(
`Invalid multipart body: ${err instanceof Error ? err.message : "unknown"}`,
400,
+79 -111
View File
@@ -1,42 +1,31 @@
"use client";
/**
* v1.5.5 D-3 §6 + §9 — medication detail page.
* v1.5.6 G-1 — medication detail page as a pure history surface.
*
* Replaces the v1.5.4 "form retirement" gap that left every action
* (Pausieren / Beenden / Notifications / API tokens / Phasen / CSV
* import / Verlauf löschen / Medikament löschen) reachable only
* through the list-page kebab — which the kebab didn't actually wire
* up. The detail page surfaces every restored action in section
* order; one phone-scroll reaches every one of them.
* Supersedes the v1.5.5 composition that stacked every setting inline.
* The page now reads as a calm "Vergangenheit" view: back link → slim
* header (name / dose / status + a two-option Bearbeiten dropdown) →
* STATIC cadence line → GLP-1 dose-ladder read-only visualisation →
* intake-history table. Every setting — Notifications, API tokens,
* Phasen, CSV import, grace and the destructive zone — moves into the
* `<AdvancedSettingsSheet>`, reached from the dropdown's "Erweiterte
* Einstellungen" item. "Plan bearbeiten" opens the wizard at Step 1.
*
* Recurring variant: 8 sections (header → today's dose → cadence →
* dose ladder / phases → intake history preview → notifications →
* settings → destructive zone).
*
* One-shot variant: 5 sections (header → today's-dose-or-logged →
* cadence static line → intake history single row → destructive
* zone). Per D-3 §6 the wizard handles cadence edit via the header
* pencil so the cadence row hides its own edit affordance.
*
* Paused variant: same as the recurring/one-shot layout; the header
* status pill flips and the today's-dose card disables both buttons
* with a muted helper. Settings and destructive zone keep rendering.
* One-shot variant drops the dose-ladder section and renders the
* static `Einmalig am …` line in place of the cadence summary.
*
* Reads:
*
* - `medicationDetail(id)` for the medication snapshot.
* - `medicationIntakeList(id, …)` for the last-14-grouped preview
* (the v2 list owns its own paging).
* - `notificationsStatus()` + `authMe()` on the notifications
* section.
* - `medicationTitration(id)` on the GLP-1 dose ladder.
* - `medicationIntakeList(id, …)` for `intakeCount`, which the
* sheet's destructive zone needs.
*
* Mutations all cascade through `medicationDependentKeys` (which now
* Mutations all cascade through `medicationDependentKeys` (which
* includes the `compliance-chart-inline` prefix per D-3 §10).
*/
import { use, useEffect, useState } from "react";
import { use, useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { useQuery } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
@@ -49,16 +38,13 @@ import { parseScheduleRecurrence } from "@/lib/medication-schedule";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { DrugLevelChart } from "@/components/medications/DrugLevelChart";
import { TitrationSection } from "@/components/medications/TitrationSection";
import { MedicationDetailHeader } from "@/components/medications/medication-detail-header";
import { TodaysDoseCard } from "@/components/medications/todays-dose-card";
import { CadenceSummaryRow } from "@/components/medications/cadence-summary-row";
import { IntakeHistoryPreview } from "@/components/medications/sections/intake-history-preview";
import { NotificationsSection } from "@/components/medications/sections/notifications-section";
import { SettingsSection } from "@/components/medications/sections/settings-section";
import { DestructiveZoneSection } from "@/components/medications/sections/destructive-zone-section";
import { AdvancedSettingsSheet } from "@/components/medications/advanced-settings-sheet";
import { PhaseConfigSheet } from "@/components/medications/sections/phase-config-sheet";
import { MedicationWizardDialog } from "@/components/medications/wizard/MedicationWizardDialog";
import type { MedicationPayload } from "@/components/medications/wizard/wizard-payload";
@@ -135,16 +121,6 @@ function snapshotToWizardPayload(
};
}
function isToday(iso: string): boolean {
const d = new Date(iso);
const today = new Date();
return (
d.getFullYear() === today.getFullYear() &&
d.getMonth() === today.getMonth() &&
d.getDate() === today.getDate()
);
}
export default function MedicationDetailPage({
params,
}: {
@@ -157,9 +133,8 @@ export default function MedicationDetailPage({
const formatters = useFormatters();
const [wizardOpen, setWizardOpen] = useState(false);
const [wizardIntent, setWizardIntent] = useState<
"cadence" | "name" | undefined
>(undefined);
const [advancedOpen, setAdvancedOpen] = useState(false);
const [phaseSheetOpen, setPhaseSheetOpen] = useState(false);
const [importOpen, setImportOpen] = useState(false);
useEffect(() => {
@@ -201,6 +176,14 @@ export default function MedicationDetailPage({
enabled: isAuthenticated && !!medication,
});
// v1.5.6 F-1 M-2 — memoise the wizard payload so the header dropdown
// + wizard mount share one object identity per medication snapshot
// instead of recomputing it on every render.
const wizardPayload = useMemo<MedicationPayload | null>(
() => (medication ? snapshotToWizardPayload(medication) : null),
[medication],
);
if (authLoading || isLoading) {
return (
<div
@@ -246,23 +229,18 @@ export default function MedicationDetailPage({
}
const oneShot = medication.oneShot === true;
const todayEvent = intakeList?.events.find(
(e) =>
(e.takenAt && isToday(e.takenAt)) ||
(e.skipped && isToday(e.scheduledFor)),
);
const intakeCount = intakeList?.meta.total ?? 0;
const primaryGrace =
medication.schedules[0]?.reminderGraceMinutes ?? null;
// `wizardPayload` is non-null here — the early returns above bail
// before this point whenever `medication` is undefined.
const payload = wizardPayload as MedicationPayload;
function openWizardWithIntent(intent: "cadence" | "name") {
setWizardIntent(intent);
setWizardOpen(true);
}
function closeWizard() {
setWizardOpen(false);
setWizardIntent(undefined);
// v1.5.6 G-1 §5 — sibling-swap: close the advanced sheet first, then
// open the phase sheet so the two never stack (modal depth ≤ 2).
function openPhaseSheet() {
setAdvancedOpen(false);
setPhaseSheetOpen(true);
}
return (
@@ -279,30 +257,21 @@ export default function MedicationDetailPage({
</Link>
</Button>
{/* §9.1 — Header band */}
{/* G-1 §3.2 — Header band. The Bearbeiten dropdown owns the
wizard ("Plan bearbeiten") + the advanced sheet ("Erweiterte
Einstellungen"); the page owns both open-states. */}
<MedicationDetailHeader
name={medication.name}
dose={medication.dose}
active={medication.active}
endsOn={medication.endsOn}
onEdit={() => openWizardWithIntent("name")}
onEditPlan={() => setWizardOpen(true)}
onOpenAdvanced={() => setAdvancedOpen(true)}
/>
{/* §9.2 — Today's dose card */}
<TodaysDoseCard
medicationId={id}
active={medication.active}
oneShot={oneShot}
scheduledForToday={!oneShot || !todayEvent}
alreadyTakenAt={
todayEvent && !todayEvent.skipped ? todayEvent.takenAt : null
}
alreadySkipped={Boolean(todayEvent?.skipped)}
/>
{/* §9.3 — Cadence summary. One-shot: static line; the
`hideEdit` flag suppresses the row's own edit affordance
because the header pencil routes the wizard. */}
{/* G-1 §3.3 — Static cadence line. One-shot collapses to the
`Einmalig am …` card; recurring renders the summary row with
`hideEdit` (cadence editing lives in the wizard). */}
{oneShot ? (
<Card
className="p-5 sm:p-6"
@@ -318,13 +287,14 @@ export default function MedicationDetailPage({
</Card>
) : (
<CadenceSummaryRow
medication={snapshotToWizardPayload(medication)}
onEdit={() => openWizardWithIntent("cadence")}
medication={payload}
hideEdit
onEdit={() => {}}
/>
)}
{/* §9.4 — Dose ladder / Phasen (GLP-1 only, recurring path
only — one-shot variant drops this) */}
{/* G-1 §3.4 — Dose ladder / Phasen visualisation (read-only,
GLP-1 recurring only). The editor lives in the sheet. */}
{!oneShot && medication.treatmentClass === "GLP1" && (
<>
<DrugLevelChart
@@ -338,54 +308,52 @@ export default function MedicationDetailPage({
</>
)}
{/* §9.5 — Intake history preview */}
{/* G-1 §3.5 — Intake history table (primary surface). */}
<IntakeHistoryPreview
medicationId={id}
importOpen={importOpen}
onImportOpenChange={setImportOpen}
/>
{/* §9.6 + §9.7 — Notifications + Settings: recurring path only. */}
{!oneShot && (
<>
<NotificationsSection
medicationId={id}
notificationsEnabled={medication.notificationsEnabled}
/>
<Separator className="opacity-0" />
<SettingsSection
medicationId={id}
medicationName={medication.name}
treatmentClass={medication.treatmentClass}
startsOn={medication.startsOn}
endsOn={medication.endsOn}
reminderGraceMinutes={primaryGrace}
/>
</>
)}
{/* §9.8 — Verwaltung & Gefahrenzone */}
<DestructiveZoneSection
{/* G-1 §5 — Advanced settings sheet. Hosts Notifications →
Settings → destructive zone. The Phasen button sibling-swaps
to the phase sheet below. */}
<AdvancedSettingsSheet
open={advancedOpen}
onOpenChange={setAdvancedOpen}
medicationId={id}
medicationName={medication.name}
treatmentClass={medication.treatmentClass}
active={medication.active}
startsOn={medication.startsOn}
endsOn={medication.endsOn}
notificationsEnabled={medication.notificationsEnabled}
reminderGraceMinutes={primaryGrace}
intakeCount={intakeCount}
onRequestPhaseSheet={openPhaseSheet}
/>
{/* Wizard mount — edit-only on the detail page. Intent flips
between "name" (header pencil → Step 1) and "cadence"
(cadence row pencil → Step 5). Cancel returns to the detail
page (the success branch refreshes the medication detail
via the `medicationDependentKeys` cascade). */}
{/* G-1 §5 — phase sheet mounted as a sibling of the advanced
sheet so they never stack (GLP-1 + course window only). */}
{!oneShot &&
medication.treatmentClass === "GLP1" &&
Boolean(medication.startsOn) &&
Boolean(medication.endsOn) && (
<PhaseConfigSheet
medicationId={id}
open={phaseSheetOpen}
onOpenChange={setPhaseSheetOpen}
/>
)}
{/* Wizard mount — edit-only, lands on Step 1 (no landing
intent). Cancel + success both close via the cascade. */}
<MedicationWizardDialog
open={wizardOpen}
onOpenChange={(open) => {
if (!open) closeWizard();
}}
onOpenChange={setWizardOpen}
mode="edit"
initial={snapshotToWizardPayload(medication)}
landingIntent={wizardIntent}
onSuccess={() => closeWizard()}
initial={payload}
onSuccess={() => setWizardOpen(false)}
/>
</div>
);
@@ -0,0 +1,48 @@
/**
* v1.5.6 G-1 §3 — the `/medications/[id]` detail page is a pure
* history surface.
*
* Source-level guards (the page is a client component with `use()`
* + hooks, so a full render is heavier than the contract warrants):
* - no `TodaysDoseCard` import or render (removed from the detail
* page; it lives only on the list page);
* - no `isToday` / `todayEvent` derivations (dead once the card is
* gone);
* - no `landingIntent` / `wizardIntent` / `openWizardWithIntent`
* plumbing (the header dropdown is the only wizard entry, landing
* on Step 1);
* - the page hosts the `AdvancedSettingsSheet` and renders the
* cadence row with `hideEdit`.
*/
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
const source = readFileSync(
join(process.cwd(), "src/app/medications/[id]/page.tsx"),
"utf8",
);
describe("medication detail page is a pure history surface (G-1 §3)", () => {
it("does not import or render TodaysDoseCard", () => {
expect(source).not.toContain("TodaysDoseCard");
expect(source).not.toContain("todays-dose-card");
});
it("drops the dead isToday / todayEvent derivations", () => {
expect(source).not.toContain("isToday");
expect(source).not.toContain("todayEvent");
});
it("drops the landingIntent plumbing", () => {
expect(source).not.toContain("landingIntent");
expect(source).not.toContain("wizardIntent");
expect(source).not.toContain("openWizardWithIntent");
});
it("hosts the AdvancedSettingsSheet and the static cadence row", () => {
expect(source).toContain("AdvancedSettingsSheet");
expect(source).toContain("hideEdit");
});
});