Merge remote-tracking branch 'origin/main' into wip/v140-H

This commit is contained in:
Marc-André Bombeck committed 2026-10-04 00:43:10 +02:00
commit db9618ee7b
54 files changed
+2531 -531

No files matched your search

@@ -561,32 +561,6 @@ describe("GET /api/dashboard/summary", () => {
expect(glucose?.lastSeenAt).toBe(tenDaysAgo.toISOString());
});
it("names the owner's glucose unit on the glucose card", async () => {
// Applied after the summary cache: the unit is the record's own choice
// and the card's numbers are in it (the conversion is pinned in
// `src/lib/dashboard/__tests__/glucose-card.test.ts`).
vi.mocked(getSession).mockResolvedValue({
...SESSION_OK,
user: { ...SESSION_OK.user, glucoseUnit: "mmol/L" },
} as never);
vi.mocked(prisma.measurement.groupBy).mockResolvedValue([
{
type: "BLOOD_GLUCOSE",
_count: { _all: 4 },
_max: { measuredAt: new Date(Date.now() - 10 * 86_400_000) },
},
] as never);
const res = await callGet(makeReq());
const body = (await res.json()) as {
data: { metrics: Array<{ id: string; unit: string | null }> };
};
expect(body.data.metrics.find((m) => m.id === "glucose")?.unit).toBe(
"mmol/L",
);
// Every other card keeps its own unit contract.
expect(body.data.metrics.find((m) => m.id === "weight")?.unit).toBeNull();
});
it("emits the sleep tile as the night TIME-ASLEEP total in hours, not one stage (v1.11.4)", async () => {
// SLEEP_DURATION is stored one row per STAGE per night (minutes). The
// tile must SUM the asleep stages of the latest night and convert to
+1 -9
View File
@@ -75,8 +75,6 @@ import {
} from "@/lib/dashboard/summary-reads";
import { resolveModuleMap } from "@/lib/modules/gate";
import { gateMetricCardsByModules } from "@/lib/dashboard/widget-modules";
import { glucoseCardInDisplayUnit } from "@/lib/dashboard/glucose-card";
import { resolveGlucoseUnit } from "@/lib/glucose";
import {
summarizeSleepNights,
reconstructSleepNights,
@@ -146,9 +144,6 @@ interface MetricCard {
* `latestValue` is a per-NIGHT total expressed in HOURS (a float),
* not the canonical `SLEEP_DURATION` minutes — see the sleep block
* below for why the night total replaced the single-stage value.
* v1.40.0 — the `glucose` tile sets it to the owner's glucose unit
* (`"mg/dL"` or `"mmol/L"`), with its values converted to match
* (`glucoseCardInDisplayUnit`, applied after the cache read).
*/
unit: string | null;
/**
@@ -330,10 +325,7 @@ export const GET = apiHandler(async () => {
// it off. Filtering the cached body makes the toggle effective on the very
// next request.
const modules = await resolveModuleMap(user.id);
const glucoseUnit = resolveGlucoseUnit(user.glucoseUnit);
const metrics = gateMetricCardsByModules(body.metrics, modules).map((card) =>
glucoseCardInDisplayUnit(card, glucoseUnit),
);
const metrics = gateMetricCardsByModules(body.metrics, modules);
annotate({
meta: {
metrics_emitted: metrics.length,
@@ -140,3 +140,26 @@ describe("GET /api/health while the encryption key does not match", () => {
expect(body).toEqual({ status: "ok" });
});
});
describe("GET /api/health under ENCRYPTION_KEY_CHECK=warn", () => {
it("names the mismatch as a warning and stays ok", async () => {
const { setKeyMismatchWarning } =
await import("@/lib/boot/key-mismatch-state");
vi.stubEnv("HEALTHLOG_PROCESS_TYPE", "web");
getGlobalBoss.mockReturnValue({});
setKeyMismatchWarning({
keyIds: ["v1"],
detectedAt: "2026-10-03T00:00:00Z",
});
try {
const { response, body } = await health();
expect(response.status).toBe(200);
expect(body).toEqual({
status: "ok",
warning: "encryption_key_mismatch",
});
} finally {
setKeyMismatchWarning(null);
}
});
});
+9 -1
View File
@@ -7,6 +7,7 @@ import { NextResponse } from "next/server";
import { apiHandler } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import {
getKeyMismatchWarning,
isKeyMismatch,
KEY_MISMATCH_HEALTH_REASON,
} from "@/lib/boot/key-mismatch-state";
@@ -31,6 +32,12 @@ export const GET = apiHandler(async () => {
// it is the one place a catalog install's status page reads.
const keyMismatch = isKeyMismatch();
const reason = keyMismatch ? KEY_MISMATCH_HEALTH_REASON : undefined;
// Under ENCRYPTION_KEY_CHECK=warn the same finding does not refuse; it is
// named as a warning and leaves the status alone.
const warning =
!keyMismatch && getKeyMismatchWarning()
? KEY_MISMATCH_HEALTH_REASON
: undefined;
const status =
!keyMismatch &&
dbOk &&
@@ -51,6 +58,7 @@ export const GET = apiHandler(async () => {
{
status,
...(reason ? { reason } : {}),
...(warning ? { warning } : {}),
timestamp: new Date().toISOString(),
database: dbOk ? "connected" : "disconnected",
worker: worker.running ? "running" : "stopped",
@@ -63,7 +71,7 @@ export const GET = apiHandler(async () => {
}
return NextResponse.json(
{ status, ...(reason ? { reason } : {}) },
{ status, ...(reason ? { reason } : {}), ...(warning ? { warning } : {}) },
{ status: statusCode, headers: cacheHeaders },
);
});
+6
View File
@@ -29,6 +29,7 @@ import { NextRequest } from "next/server";
import { z } from "zod/v4";
import { annotate } from "@/lib/logging/context";
import { refuseOAuthOnKeyMismatch } from "@/lib/boot/key-mismatch-refusal";
import { withBackgroundEvent } from "@/lib/logging/background";
import { auditLog } from "@/lib/auth/audit";
import { getSession } from "@/lib/auth/session";
@@ -344,10 +345,15 @@ function ensureAuthorizeCsp(response: Response): Response {
}
export async function GET(request: NextRequest): Promise<Response> {
// The boot key check refused this process: no grant is issued or stored.
const refusal = refuseOAuthOnKeyMismatch();
if (refusal) return ensureAuthorizeCsp(refusal);
return ensureAuthorizeCsp(await authorizeGet(request));
}
export async function POST(request: NextRequest): Promise<Response> {
const refusal = refuseOAuthOnKeyMismatch();
if (refusal) return ensureAuthorizeCsp(refusal);
return ensureAuthorizeCsp(await authorizePost(request));
}
+5
View File
@@ -16,6 +16,7 @@ import { NextRequest } from "next/server";
import { z } from "zod/v4";
import { annotate } from "@/lib/logging/context";
import { refuseOAuthOnKeyMismatch } from "@/lib/boot/key-mismatch-refusal";
import { withBackgroundEvent } from "@/lib/logging/background";
import { checkAuthSurfaceRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
import { isApiGloballyEnabled } from "@/lib/app-settings";
@@ -68,6 +69,10 @@ function oauthError(
export async function POST(request: NextRequest): Promise<Response> {
return withBackgroundEvent("mcp.oauth.register", async () => {
// The boot key check refused this process: mint nothing, write nothing.
const refusal = refuseOAuthOnKeyMismatch();
if (refusal) return refusal;
const rl = await checkAuthSurfaceRateLimit(
request,
"mcp:oauth:register",
+5
View File
@@ -32,6 +32,7 @@ import { NextRequest } from "next/server";
import type { Prisma } from "@/generated/prisma/client";
import { prisma } from "@/lib/db";
import { annotate } from "@/lib/logging/context";
import { refuseOAuthOnKeyMismatch } from "@/lib/boot/key-mismatch-refusal";
import { withBackgroundEvent } from "@/lib/logging/background";
import { auditLog } from "@/lib/auth/audit";
import { issueApiToken } from "@/lib/auth/issue-token";
@@ -201,6 +202,10 @@ async function finalizeTokenPair(
export async function POST(request: NextRequest): Promise<Response> {
return withBackgroundEvent("mcp.oauth.token", async () => {
// The boot key check refused this process: mint nothing, write nothing.
const refusal = refuseOAuthOnKeyMismatch();
if (refusal) return refusal;
// M1 — fail closed without a pinned origin; M4 — honour the operator's
// global API kill-switch. Either off and the bridge mints no tokens.
if (!isMcpOriginConfigured() || !(await isApiGloballyEnabled())) {
+29 -6
View File
@@ -194,7 +194,8 @@ interface EntryResult {
}
/**
* v1.31.1 — emit one data arrival per workout this batch actually inserted.
* v1.31.1 — emit one data arrival per workout this batch actually inserted,
* and per hand-entered workout whose edit it actually wrote.
*
* `createManyAndReturn` gives the transaction the exact inserted ids. The
* index-keyed map avoids a second lookup and keeps equal external ids from
@@ -541,6 +542,8 @@ async function postBatch(request: NextRequest): Promise<Response> {
let enrichedCount = 0;
let updatedCount = 0;
const insertedIdByIndex = new Map<number, string>();
/** Workout ids of the manual edits this request actually wrote. */
const overwrittenIdByIndex = new Map<number, string>();
if (survivors.length > 0) {
// v1.4.42 W5 — only the write-time dedup survivors are probed
@@ -709,6 +712,19 @@ async function postBatch(request: NextRequest): Promise<Response> {
externalId: o.externalId,
},
});
// The paragraph described the old values (a 12 km run corrected
// to 1.2 km must not keep its 12 km story). It goes with them,
// and the claim is let go of its workout the way a delete does
// (`ON DELETE SET NULL`): the row stays as the day's ledger, so
// the edit buys no slot back, and the arrival emitted below can
// claim a fresh one through the ordinary path, under the same cap.
await tx.workoutInsight.deleteMany({
where: { userId: user.id, workoutId: o.workoutId },
});
await tx.workoutInsightGenerationClaim.updateMany({
where: { userId: user.id, workoutId: o.workoutId },
data: { workoutId: null },
});
}
}
@@ -841,7 +857,10 @@ async function postBatch(request: NextRequest): Promise<Response> {
index: o.index,
status: landed ? "updated" : "duplicate",
};
if (landed) updatedCount += 1;
if (landed) {
updatedCount += 1;
overwrittenIdByIndex.set(o.index, o.workoutId);
}
duplicateCount += 1;
}
}
@@ -914,13 +933,17 @@ async function postBatch(request: NextRequest): Promise<Response> {
invalidateUserMeasurements(user.id);
}
if (insertedCount > 0) {
if (insertedCount > 0 || overwrittenIdByIndex.size > 0) {
// One arrival per exact INSERT ... RETURNING winner. Historical rows still
// stop at the shared salience classifier before any queue work.
// An enrichment raises none: the workout arrived when it was stored.
void emitWorkoutArrivals(user.id, prepared, insertedIdByIndex).catch(
() => {},
);
// A hand-entered workout whose edit landed raises one again, so its
// paragraph (dropped with the old values) is written from the new ones.
void emitWorkoutArrivals(
user.id,
prepared,
new Map([...insertedIdByIndex, ...overwrittenIdByIndex]),
).catch(() => {});
}
return apiSuccess({