mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 23:33:29 +00:00
test(integration): move notification channel and workout route tests onto Postgres
The channel settings routes, their test-message routes, the reminder thresholds and the workout detail, delete and batch-scope tests run through the real handlers against the database. Only the far ends are faked (the relay, the ntfy server, the Telegram Bot API, SMTP), and the tests assert what those received. The private-origin source guard stays a unit test and now points at the two files that carry its runtime proof.
This commit is contained in:
1 parent
ff9ef0883b
commit
43b86e46da
16 files changed
+2868
-3247
No files matched your search
@@ -1,311 +0,0 @@
|
||||
/**
|
||||
* Who may call `POST /api/workouts/batch` (#1054).
|
||||
*
|
||||
* The route names `workouts:write`, so the set of credentials it admits is:
|
||||
* a cookie session, a wildcard (`["*"]`) token, and a narrow token carrying
|
||||
* exactly that scope. Every other narrow token — `measurements:write`
|
||||
* included, however adjacent it looks — is refused 403 by the fail-closed
|
||||
* default.
|
||||
*
|
||||
* The real `requireAuth` and the real `resolveBearerToken` run here; only the
|
||||
* token row lookup is stubbed, so the admission decision under test is the
|
||||
* production one rather than a re-implementation of it.
|
||||
*
|
||||
* The second half pins what a scoped caller writes: its rows are `EXTERNAL`,
|
||||
* resolved from the credential, and a body naming any source is refused 422
|
||||
* rather than relabelled. A session and a wildcard token keep the source they
|
||||
* send.
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
apiToken: { findUnique: vi.fn(), update: vi.fn() },
|
||||
user: { findUnique: vi.fn() },
|
||||
workout: {
|
||||
findMany: vi.fn(),
|
||||
createManyAndReturn: vi.fn(),
|
||||
},
|
||||
workoutRoute: { createMany: vi.fn() },
|
||||
workoutSamples: { createManyAndReturn: vi.fn() },
|
||||
$transaction: vi.fn(async (fn: unknown) => {
|
||||
if (typeof fn === "function") {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return (fn as any)(prisma as unknown as { workout: unknown });
|
||||
}
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
|
||||
vi.mock("@/lib/auth/audit", () => ({
|
||||
auditLog: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
|
||||
vi.mock("@/lib/db-compat", () => ({
|
||||
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
vi.mock("@/lib/rate-limit", () => ({ checkRateLimit: vi.fn() }));
|
||||
vi.mock("@/lib/jobs/pr-detection", () => ({
|
||||
enqueuePrDetection: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
vi.mock("@/lib/arrivals/emit-shared", () => ({
|
||||
emitDataArrival: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
vi.mock("next/headers", () => ({
|
||||
headers: vi.fn(async () => ({ get: () => null })),
|
||||
cookies: vi.fn(async () => ({
|
||||
get: () => undefined,
|
||||
set: () => {},
|
||||
delete: () => {},
|
||||
})),
|
||||
}));
|
||||
|
||||
import { POST } from "../batch/route";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
import { headers } from "next/headers";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { MEASUREMENTS_WRITE_SCOPE } from "@/lib/measurements/scopes";
|
||||
import { DOCUMENTS_WRITE_SCOPE } from "@/lib/documents/scopes";
|
||||
import { WORKOUTS_WRITE_SCOPE } from "@/lib/workouts/scopes";
|
||||
|
||||
const USER = {
|
||||
id: "user-1",
|
||||
username: "tester",
|
||||
role: "USER" as const,
|
||||
sourcePriorityJson: null,
|
||||
};
|
||||
const TOKEN = "hlk_" + "c".repeat(64);
|
||||
|
||||
function makeRequest(body: unknown): NextRequest {
|
||||
return new NextRequest("http://localhost/api/workouts/batch", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
function workout(
|
||||
externalId: string,
|
||||
overrides: Record<string, unknown> = {},
|
||||
): Record<string, unknown> {
|
||||
return {
|
||||
sportType: "running",
|
||||
startedAt: "2026-09-20T06:30:00.000Z",
|
||||
endedAt: "2026-09-20T07:15:00.000Z",
|
||||
externalId,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
/** Present `TOKEN` as a Bearer whose row carries `permissions`. */
|
||||
function armToken(permissions: string[]) {
|
||||
vi.mocked(getSession).mockResolvedValue(null as never);
|
||||
vi.mocked(headers).mockResolvedValue({
|
||||
get: (name: string) =>
|
||||
name.toLowerCase() === "authorization" ? `Bearer ${TOKEN}` : null,
|
||||
} as never);
|
||||
vi.mocked(prisma.apiToken.findUnique).mockResolvedValue({
|
||||
id: "tok-1",
|
||||
userId: USER.id,
|
||||
permissions,
|
||||
revoked: false,
|
||||
expiresAt: new Date(Date.now() + 86_400_000),
|
||||
} as never);
|
||||
}
|
||||
|
||||
function armSession() {
|
||||
vi.mocked(getSession).mockResolvedValue({
|
||||
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
|
||||
user: USER,
|
||||
} as never);
|
||||
}
|
||||
|
||||
/** The rows the route handed to `INSERT ... RETURNING`. */
|
||||
function insertedRows(): Array<Record<string, unknown>> {
|
||||
return vi
|
||||
.mocked(prisma.workout.createManyAndReturn)
|
||||
.mock.calls.flatMap(([args]) => {
|
||||
const data = (args as { data: unknown }).data;
|
||||
return (Array.isArray(data) ? data : [data]) as Array<
|
||||
Record<string, unknown>
|
||||
>;
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.stubEnv("API_TOKEN_HMAC_KEY", "k".repeat(64));
|
||||
vi.mocked(headers).mockResolvedValue({ get: () => null } as never);
|
||||
vi.mocked(getSession).mockResolvedValue(null as never);
|
||||
vi.mocked(checkRateLimit).mockResolvedValue({
|
||||
allowed: true,
|
||||
limit: 60,
|
||||
remaining: 60,
|
||||
resetAt: Date.now() + 60_000,
|
||||
});
|
||||
vi.mocked(prisma.apiToken.update).mockResolvedValue({} as never);
|
||||
// The refusal path chains `.catch` on the audit write, so the reset mock
|
||||
// has to hand back a promise again.
|
||||
vi.mocked(auditLog).mockResolvedValue(undefined as never);
|
||||
// One row serves both lookups: the resolver's user fetch and the route's
|
||||
// source-priority read.
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue(USER as never);
|
||||
vi.mocked(prisma.workout.findMany).mockResolvedValue([]);
|
||||
vi.mocked(prisma.workout.createManyAndReturn).mockImplementation(
|
||||
(async (args: { data: Array<Record<string, unknown>> }) =>
|
||||
args.data.map((row, index) => ({
|
||||
id: `w-${index}`,
|
||||
source: row.source,
|
||||
externalId: row.externalId,
|
||||
}))) as never,
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
describe("POST /api/workouts/batch — which credentials it admits", () => {
|
||||
it("admits a narrow workouts:write token", async () => {
|
||||
armToken([WORKOUTS_WRITE_SCOPE]);
|
||||
const res = await POST(makeRequest({ workouts: [workout("s-1")] }));
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json();
|
||||
expect(body.data.inserted).toBe(1);
|
||||
});
|
||||
|
||||
it("still admits a cookie session", async () => {
|
||||
armSession();
|
||||
const res = await POST(
|
||||
makeRequest({ workouts: [workout("s-1", { source: "APPLE_HEALTH" })] }),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it("still admits a wildcard token", async () => {
|
||||
armToken(["*"]);
|
||||
const res = await POST(
|
||||
makeRequest({ workouts: [workout("s-1", { source: "APPLE_HEALTH" })] }),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["measurements:write", [MEASUREMENTS_WRITE_SCOPE]],
|
||||
["documents:write", [DOCUMENTS_WRITE_SCOPE]],
|
||||
["medication:ingest", ["medication:ingest", "medication:m-1:ingest"]],
|
||||
["health:read", ["health:read"]],
|
||||
])("refuses a %s token with 403 and writes nothing", async (_, perms) => {
|
||||
armToken(perms);
|
||||
const res = await POST(makeRequest({ workouts: [workout("s-1")] }));
|
||||
expect(res.status).toBe(403);
|
||||
expect(prisma.workout.createManyAndReturn).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/workouts/batch — rate limit buckets", () => {
|
||||
function lastBucket(): string {
|
||||
const calls = vi.mocked(checkRateLimit).mock.calls;
|
||||
return calls[calls.length - 1][0] as string;
|
||||
}
|
||||
|
||||
it("counts a workouts:write token apart from the phone", async () => {
|
||||
armToken([WORKOUTS_WRITE_SCOPE]);
|
||||
await POST(makeRequest({ workouts: [workout("s-1")] }));
|
||||
const bridge = lastBucket();
|
||||
|
||||
armToken(["*"]);
|
||||
await POST(
|
||||
makeRequest({ workouts: [workout("s-2", { source: "APPLE_HEALTH" })] }),
|
||||
);
|
||||
const phone = lastBucket();
|
||||
|
||||
expect(bridge).not.toBe(phone);
|
||||
expect(bridge).toContain(USER.id);
|
||||
expect(phone).toContain(USER.id);
|
||||
});
|
||||
|
||||
it("keeps a session and a wildcard token in the same bucket", async () => {
|
||||
armSession();
|
||||
await POST(
|
||||
makeRequest({ workouts: [workout("s-1", { source: "APPLE_HEALTH" })] }),
|
||||
);
|
||||
const session = lastBucket();
|
||||
armToken(["*"]);
|
||||
await POST(
|
||||
makeRequest({ workouts: [workout("s-2", { source: "APPLE_HEALTH" })] }),
|
||||
);
|
||||
expect(lastBucket()).toBe(session);
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/workouts/batch — what a scoped caller writes", () => {
|
||||
it("attributes its rows to EXTERNAL", async () => {
|
||||
armToken([WORKOUTS_WRITE_SCOPE]);
|
||||
// Two sessions of the day: EXTERNAL ranks on the workout ladder, so two
|
||||
// rows of one session would land once.
|
||||
const res = await POST(
|
||||
makeRequest({
|
||||
workouts: [
|
||||
workout("s-1"),
|
||||
workout("s-2", {
|
||||
startedAt: "2026-09-20T18:00:00.000Z",
|
||||
endedAt: "2026-09-20T18:45:00.000Z",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
const rows = insertedRows();
|
||||
expect(rows).toHaveLength(2);
|
||||
expect(rows.map((r) => r.source)).toEqual(["EXTERNAL", "EXTERNAL"]);
|
||||
});
|
||||
|
||||
it("probes for duplicates in the EXTERNAL namespace", async () => {
|
||||
armToken([WORKOUTS_WRITE_SCOPE]);
|
||||
await POST(makeRequest({ workouts: [workout("s-1")] }));
|
||||
const probe = vi
|
||||
.mocked(prisma.workout.findMany)
|
||||
.mock.calls.map(([args]) => args as { where?: { OR?: unknown } })
|
||||
.find((args) => args.where?.OR !== undefined);
|
||||
expect(probe?.where?.OR).toEqual([
|
||||
{ source: "EXTERNAL", externalId: "s-1" },
|
||||
]);
|
||||
});
|
||||
|
||||
it.each(["APPLE_HEALTH", "MANUAL"])(
|
||||
"refuses a body naming %s with 422 and writes nothing",
|
||||
async (source) => {
|
||||
armToken([WORKOUTS_WRITE_SCOPE]);
|
||||
const res = await POST(
|
||||
makeRequest({
|
||||
workouts: [workout("s-1"), workout("s-2", { source })],
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(422);
|
||||
const body = await res.json();
|
||||
expect(body.meta?.errorCode).toBe("workout.batch.source_not_permitted");
|
||||
expect(prisma.workout.createManyAndReturn).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it("leaves the source a wildcard caller sends alone", async () => {
|
||||
armToken(["*"]);
|
||||
await POST(
|
||||
makeRequest({ workouts: [workout("s-1", { source: "APPLE_HEALTH" })] }),
|
||||
);
|
||||
expect(insertedRows().map((r) => r.source)).toEqual(["APPLE_HEALTH"]);
|
||||
});
|
||||
|
||||
it("leaves the source a session sends alone", async () => {
|
||||
armSession();
|
||||
await POST(
|
||||
makeRequest({ workouts: [workout("s-1", { source: "MANUAL" })] }),
|
||||
);
|
||||
expect(insertedRows().map((r) => r.source)).toEqual(["MANUAL"]);
|
||||
});
|
||||
});
|
||||
@@ -1,213 +0,0 @@
|
||||
/**
|
||||
* Unit suite for `DELETE /api/workouts/{id}`.
|
||||
*
|
||||
* Pins:
|
||||
* - a workout entered by hand is removed, with the personal records keyed
|
||||
* on it, and a silent detection pass re-derives the previous best;
|
||||
* - a synced workout answers 409 and nothing is touched, because the next
|
||||
* sync would write it back;
|
||||
* - another user's row and a missing row answer 404;
|
||||
* - no session answers 401.
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
const tx = {
|
||||
$queryRaw: vi.fn(async () => []),
|
||||
personalRecord: { deleteMany: vi.fn() },
|
||||
workout: { delete: vi.fn() },
|
||||
};
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
workout: { findUnique: vi.fn() },
|
||||
$transaction: vi.fn(async (fn: (client: typeof tx) => unknown) => fn(tx)),
|
||||
},
|
||||
}));
|
||||
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
|
||||
vi.mock("@/lib/auth/audit", () => ({
|
||||
auditLog: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
|
||||
vi.mock("@/lib/cache/invalidate", () => ({
|
||||
invalidateUserMeasurements: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/lib/jobs/pr-detection", () => ({
|
||||
enqueuePrDetection: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
vi.mock("next/headers", () => ({
|
||||
headers: vi.fn(async () => ({ get: () => null })),
|
||||
cookies: vi.fn(async () => ({
|
||||
get: () => undefined,
|
||||
set: () => {},
|
||||
delete: () => {},
|
||||
})),
|
||||
}));
|
||||
|
||||
import { DELETE } from "../[id]/route";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { enqueuePrDetection } from "@/lib/jobs/pr-detection";
|
||||
import { invalidateUserMeasurements } from "@/lib/cache/invalidate";
|
||||
|
||||
const SESSION_OK = {
|
||||
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
|
||||
user: { id: "user-1", username: "testuser", role: "USER" as const },
|
||||
};
|
||||
|
||||
const MANUAL_ROW = {
|
||||
id: "w-1",
|
||||
userId: "user-1",
|
||||
source: "MANUAL" as const,
|
||||
externalId: "manual:5b0f3c1e-1111-4222-8333-444455556666",
|
||||
startedAt: new Date("2026-09-01T07:00:00Z"),
|
||||
sportType: "running",
|
||||
};
|
||||
|
||||
function del(id = "w-1") {
|
||||
return DELETE(
|
||||
new NextRequest(`http://localhost/api/workouts/${id}`, {
|
||||
method: "DELETE",
|
||||
}),
|
||||
{ params: Promise.resolve({ id }) },
|
||||
);
|
||||
}
|
||||
|
||||
describe("DELETE /api/workouts/{id}", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
tx.personalRecord.deleteMany.mockResolvedValue({ count: 0 });
|
||||
tx.workout.delete.mockResolvedValue({ id: "w-1" });
|
||||
});
|
||||
|
||||
it("removes a workout entered by hand", async () => {
|
||||
vi.mocked(prisma.workout.findUnique).mockResolvedValue(MANUAL_ROW as never);
|
||||
|
||||
const res = await del();
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({ data: { deleted: true }, error: null });
|
||||
expect(tx.workout.delete).toHaveBeenCalledWith({ where: { id: "w-1" } });
|
||||
expect(auditLog).toHaveBeenCalledWith(
|
||||
"workout.delete",
|
||||
expect.objectContaining({ userId: "user-1" }),
|
||||
);
|
||||
expect(invalidateUserMeasurements).toHaveBeenCalledWith("user-1", {
|
||||
evict: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("takes the personal records the workout set with it and re-derives the best", async () => {
|
||||
vi.mocked(prisma.workout.findUnique).mockResolvedValue(MANUAL_ROW as never);
|
||||
tx.personalRecord.deleteMany.mockResolvedValue({ count: 2 });
|
||||
|
||||
const res = await del();
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(tx.personalRecord.deleteMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
userId: "user-1",
|
||||
metricSlot: { not: null },
|
||||
source: "MANUAL",
|
||||
externalId: MANUAL_ROW.externalId,
|
||||
},
|
||||
});
|
||||
expect(enqueuePrDetection).toHaveBeenCalledWith("user-1", {
|
||||
silent: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("keys a record without an external id on the session's start", async () => {
|
||||
vi.mocked(prisma.workout.findUnique).mockResolvedValue({
|
||||
...MANUAL_ROW,
|
||||
externalId: null,
|
||||
} as never);
|
||||
|
||||
await del();
|
||||
|
||||
expect(tx.personalRecord.deleteMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
userId: "user-1",
|
||||
source: "MANUAL",
|
||||
// Only the running slots: a cycling record set at the same instant
|
||||
// is not this workout's.
|
||||
metricSlot: {
|
||||
in: [
|
||||
"longest_run_duration",
|
||||
"longest_distance_run",
|
||||
"fastest_5km_time",
|
||||
],
|
||||
},
|
||||
externalId: null,
|
||||
achievedAt: MANUAL_ROW.startedAt,
|
||||
},
|
||||
});
|
||||
// Nothing was removed, so nothing needs re-deriving.
|
||||
expect(enqueuePrDetection).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("takes the personal-records lock before it deletes anything", async () => {
|
||||
vi.mocked(prisma.workout.findUnique).mockResolvedValue(MANUAL_ROW as never);
|
||||
|
||||
await del();
|
||||
|
||||
expect(tx.$queryRaw).toHaveBeenCalledTimes(1);
|
||||
const lockOrder = tx.$queryRaw.mock.invocationCallOrder[0];
|
||||
expect(lockOrder).toBeLessThan(
|
||||
tx.personalRecord.deleteMany.mock.invocationCallOrder[0],
|
||||
);
|
||||
expect(lockOrder).toBeLessThan(
|
||||
tx.workout.delete.mock.invocationCallOrder[0],
|
||||
);
|
||||
});
|
||||
|
||||
it.each(["APPLE_HEALTH", "WITHINGS", "WHOOP", "EXTERNAL"])(
|
||||
"refuses a %s workout with 409 and touches nothing",
|
||||
async (source) => {
|
||||
vi.mocked(prisma.workout.findUnique).mockResolvedValue({
|
||||
...MANUAL_ROW,
|
||||
source,
|
||||
} as never);
|
||||
|
||||
const res = await del();
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
const body = await res.json();
|
||||
expect(body.data).toBeNull();
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled();
|
||||
expect(tx.workout.delete).not.toHaveBeenCalled();
|
||||
expect(auditLog).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it("answers 404 for another user's workout", async () => {
|
||||
vi.mocked(prisma.workout.findUnique).mockResolvedValue({
|
||||
...MANUAL_ROW,
|
||||
userId: "someone-else",
|
||||
} as never);
|
||||
|
||||
const res = await del();
|
||||
|
||||
expect(res.status).toBe(404);
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("answers 404 when there is no such workout", async () => {
|
||||
vi.mocked(prisma.workout.findUnique).mockResolvedValue(null);
|
||||
|
||||
const res = await del("missing");
|
||||
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it("answers 401 without a session", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(null);
|
||||
|
||||
const res = await del();
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
expect(prisma.workout.findUnique).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,774 +0,0 @@
|
||||
/**
|
||||
* Unit suite for `GET /api/workouts/{id}` — single-workout detail.
|
||||
*
|
||||
* v1.4.32 — paired with the list endpoint so the iOS detail screen +
|
||||
* the `/insights/workouts/[id]` web page consume one envelope per
|
||||
* workout. The test pins:
|
||||
* - 200 + iOS-contract field names for a row the caller owns;
|
||||
* - 401 without a session;
|
||||
* - 404 (existence-channel sealed) when the row belongs to another
|
||||
* user;
|
||||
* - 404 when no row exists;
|
||||
* - `canonicalId` resolves to the cluster winner — the requested id
|
||||
* when the row is the canonical pick, the winner id when it is a
|
||||
* non-canonical twin;
|
||||
* - the optional `route` field flows through GeoJSON geometry when a
|
||||
* `WorkoutRoute` row is attached, and is null when missing;
|
||||
* - `aiInsight` is a pure READ: it serves a stored paragraph when one
|
||||
* exists, null when none does, and never generates one;
|
||||
* - `dayKey` dates the session in the user's timezone, so a session that
|
||||
* starts late in the UTC evening lands on the local day the person
|
||||
* actually trained on.
|
||||
*/
|
||||
import { afterEach, describe, expect, it, vi, beforeEach } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
import { _resetCryptoCacheForTests } from "@/lib/crypto";
|
||||
import { encryptRouteGeometry } from "@/lib/workouts/route-geometry-cipher";
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
workout: {
|
||||
findUnique: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
user: {
|
||||
findUnique: vi.fn(),
|
||||
},
|
||||
measurement: {
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
|
||||
vi.mock("@/lib/auth/audit", () => ({
|
||||
auditLog: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
|
||||
vi.mock("next/headers", () => ({
|
||||
headers: vi.fn(async () => ({ get: () => null })),
|
||||
cookies: vi.fn(async () => ({
|
||||
get: () => undefined,
|
||||
set: () => {},
|
||||
delete: () => {},
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/modules/gate", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/lib/modules/gate")>();
|
||||
return {
|
||||
...actual,
|
||||
resolveModuleMap: vi.fn(async () => ({})),
|
||||
requireModuleEnabled: vi.fn(async () => ({ enabled: true })),
|
||||
};
|
||||
});
|
||||
|
||||
// The Activity Insight paragraph follows the `workoutInsights` capability.
|
||||
vi.mock("@/lib/ai/capabilities/gate", () => ({ aiCapabilityToServe: vi.fn() }));
|
||||
|
||||
import { GET } from "../[id]/route";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
import { requireModuleEnabled } from "@/lib/modules/gate";
|
||||
import { aiCapabilityToServe } from "@/lib/ai/capabilities/gate";
|
||||
import {
|
||||
AI_AVAILABLE,
|
||||
aiUnavailable,
|
||||
} from "@/__tests__/helpers/ai-capability-fixtures";
|
||||
import { invalidateUserTimezone } from "@/lib/tz/resolver";
|
||||
|
||||
const SESSION_OK = {
|
||||
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
|
||||
user: { id: "user-1", username: "testuser", role: "USER" as const },
|
||||
};
|
||||
|
||||
function makeRequest(): NextRequest {
|
||||
return new NextRequest("http://localhost/api/workouts/w-1", {
|
||||
method: "GET",
|
||||
});
|
||||
}
|
||||
|
||||
function makeParams(id: string) {
|
||||
return { params: Promise.resolve({ id }) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Session day, ten days before the test run. The detail route's HR-curve
|
||||
* enrichment only reaches the pulse-window fallback inside the 90-day
|
||||
* dense-intraday retention horizon (`DENSE_INTRADAY_RETENTION_DAYS`), so a
|
||||
* fixed calendar day silently ages out of that branch and leaves the
|
||||
* fallback assertions green without exercising it.
|
||||
*/
|
||||
const SESSION_DAY = new Date(Date.now() - 10 * 24 * 60 * 60 * 1000)
|
||||
.toISOString()
|
||||
.slice(0, 10);
|
||||
|
||||
const BASE_ROW = {
|
||||
id: "w-1",
|
||||
userId: "user-1",
|
||||
sportType: "RUNNING",
|
||||
startedAt: new Date(`${SESSION_DAY}T07:00:00Z`),
|
||||
endedAt: new Date(`${SESSION_DAY}T07:30:00Z`),
|
||||
durationSec: 1800,
|
||||
totalDistanceM: 5000,
|
||||
totalEnergyKcal: 320,
|
||||
avgHeartRate: 145,
|
||||
maxHeartRate: 170,
|
||||
minHeartRate: 110,
|
||||
stepCount: 5800,
|
||||
elevationM: 12.5,
|
||||
pauseDurationSec: null,
|
||||
source: "APPLE_HEALTH" as const,
|
||||
externalId: "ext-w-1",
|
||||
externalSourceVersion: null,
|
||||
metadata: { hkVersion: "1" },
|
||||
createdAt: new Date(`${SESSION_DAY}T07:30:00Z`),
|
||||
updatedAt: new Date(`${SESSION_DAY}T07:30:00Z`),
|
||||
route: null,
|
||||
insight: null,
|
||||
};
|
||||
|
||||
describe("GET /api/workouts/{id}", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({
|
||||
sourcePriorityJson: null,
|
||||
dateOfBirth: null,
|
||||
} as never);
|
||||
// #67 — the enrichment reads: the HR-curve pulse-window fallback
|
||||
// (`measurement.findMany`) and the sport-context average (a SECOND
|
||||
// `workout.findMany`). Default both to empty; each test's
|
||||
// `mockResolvedValueOnce` still wins for the cluster call.
|
||||
vi.mocked(prisma.workout.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(prisma.measurement.findMany).mockResolvedValue([] as never);
|
||||
// clearAllMocks wipes the factory default; re-seed the gate to pass.
|
||||
vi.mocked(requireModuleEnabled).mockResolvedValue({
|
||||
enabled: true,
|
||||
} as never);
|
||||
vi.mocked(aiCapabilityToServe).mockResolvedValue(AI_AVAILABLE);
|
||||
// The timezone resolver caches per user for 60 s in process; drop the
|
||||
// entry so a test that pins a zone is not served the previous one.
|
||||
invalidateUserTimezone(SESSION_OK.user.id);
|
||||
});
|
||||
|
||||
it("returns the workout with iOS-contract field names", async () => {
|
||||
vi.mocked(prisma.workout.findUnique).mockResolvedValueOnce(
|
||||
BASE_ROW as never,
|
||||
);
|
||||
vi.mocked(prisma.workout.findMany).mockResolvedValueOnce([
|
||||
{
|
||||
id: "w-1",
|
||||
source: "APPLE_HEALTH",
|
||||
startedAt: BASE_ROW.startedAt,
|
||||
sportType: "RUNNING",
|
||||
},
|
||||
] as never);
|
||||
|
||||
const res = await GET(makeRequest(), makeParams("w-1"));
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(body.data.id).toBe("w-1");
|
||||
expect(body.data.distanceM).toBe(5000);
|
||||
expect(body.data.activeEnergyKcal).toBe(320);
|
||||
expect(body.data.avgHr).toBe(145);
|
||||
expect(body.data.maxHr).toBe(170);
|
||||
expect(body.data.canonicalId).toBe("w-1");
|
||||
expect(body.data.route).toBeNull();
|
||||
// Nothing older on record: absence, not a link to nowhere.
|
||||
expect(body.data.previousWorkoutId).toBeNull();
|
||||
});
|
||||
|
||||
it("points previousWorkoutId at the canonical session before this one", async () => {
|
||||
vi.mocked(prisma.workout.findUnique).mockResolvedValueOnce(
|
||||
BASE_ROW as never,
|
||||
);
|
||||
vi.mocked(prisma.workout.findMany)
|
||||
// 1) the deep-link cluster
|
||||
.mockResolvedValueOnce([
|
||||
{
|
||||
id: "w-1",
|
||||
source: "APPLE_HEALTH",
|
||||
startedAt: BASE_ROW.startedAt,
|
||||
sportType: "RUNNING",
|
||||
},
|
||||
] as never)
|
||||
// 2) the sport-context baseline
|
||||
.mockResolvedValueOnce([] as never)
|
||||
// 3) the older sessions, newest first
|
||||
.mockResolvedValueOnce([
|
||||
{
|
||||
id: "w-0",
|
||||
source: "APPLE_HEALTH",
|
||||
startedAt: new Date("2026-05-13T07:00:00Z"),
|
||||
sportType: "RUNNING",
|
||||
durationSec: 1800,
|
||||
avgHeartRate: null,
|
||||
maxHeartRate: null,
|
||||
metadata: null,
|
||||
},
|
||||
// The same session as seen by the second watch. It must never win
|
||||
// the link — the list would never show it.
|
||||
{
|
||||
id: "w-0-twin",
|
||||
source: "WITHINGS",
|
||||
startedAt: new Date("2026-05-13T07:01:00Z"),
|
||||
sportType: "RUNNING",
|
||||
durationSec: 1800,
|
||||
avgHeartRate: null,
|
||||
maxHeartRate: null,
|
||||
metadata: null,
|
||||
},
|
||||
{
|
||||
id: "w-older",
|
||||
source: "APPLE_HEALTH",
|
||||
startedAt: new Date("2026-05-10T07:00:00Z"),
|
||||
sportType: "RUNNING",
|
||||
durationSec: 1800,
|
||||
avgHeartRate: null,
|
||||
maxHeartRate: null,
|
||||
metadata: null,
|
||||
},
|
||||
] as never);
|
||||
|
||||
const res = await GET(makeRequest(), makeParams("w-1"));
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(body.data.previousWorkoutId).toBe("w-0");
|
||||
});
|
||||
|
||||
it("dates the session by the user's timezone, not by UTC", async () => {
|
||||
// 20:00 UTC is already the NEXT calendar day in Auckland. A client that
|
||||
// sliced the ISO timestamp would read the session's UTC day and pull the wrong
|
||||
// day's pulse, sleep and mood around the session.
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({
|
||||
sourcePriorityJson: null,
|
||||
dateOfBirth: null,
|
||||
timezone: "Pacific/Auckland",
|
||||
} as never);
|
||||
vi.mocked(prisma.workout.findUnique).mockResolvedValueOnce({
|
||||
...BASE_ROW,
|
||||
startedAt: new Date(`${SESSION_DAY}T20:00:00Z`),
|
||||
endedAt: new Date(`${SESSION_DAY}T20:30:00Z`),
|
||||
} as never);
|
||||
vi.mocked(prisma.workout.findMany).mockResolvedValueOnce([
|
||||
{
|
||||
id: "w-1",
|
||||
source: "APPLE_HEALTH",
|
||||
startedAt: new Date(`${SESSION_DAY}T20:00:00Z`),
|
||||
sportType: "RUNNING",
|
||||
},
|
||||
] as never);
|
||||
|
||||
const res = await GET(makeRequest(), makeParams("w-1"));
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const nextLocalDay = new Date(
|
||||
new Date(`${SESSION_DAY}T00:00:00Z`).getTime() + 24 * 60 * 60 * 1000,
|
||||
)
|
||||
.toISOString()
|
||||
.slice(0, 10);
|
||||
expect(body.data.dayKey).toBe(nextLocalDay);
|
||||
});
|
||||
|
||||
it("enriches the Apple winner with only matched WHOOP HR and zones", async () => {
|
||||
const routeGeometry = {
|
||||
type: "LineString",
|
||||
coordinates: [
|
||||
[11.0, 49.0],
|
||||
[11.01, 49.01],
|
||||
],
|
||||
};
|
||||
vi.mocked(prisma.workout.findUnique).mockResolvedValueOnce({
|
||||
...BASE_ROW,
|
||||
avgHeartRate: null,
|
||||
maxHeartRate: null,
|
||||
metadata: { hkVersion: "1", owner: "apple" },
|
||||
route: {
|
||||
id: "wr-apple",
|
||||
geometry: routeGeometry,
|
||||
sampleTimestamps: null,
|
||||
createdAt: BASE_ROW.createdAt,
|
||||
},
|
||||
} as never);
|
||||
vi.mocked(prisma.workout.findMany).mockResolvedValueOnce([
|
||||
{
|
||||
id: "w-1",
|
||||
source: "APPLE_HEALTH",
|
||||
startedAt: BASE_ROW.startedAt,
|
||||
sportType: "RUNNING",
|
||||
avgHeartRate: null,
|
||||
maxHeartRate: null,
|
||||
metadata: { hkVersion: "1", owner: "apple" },
|
||||
},
|
||||
{
|
||||
id: "w-whoop",
|
||||
source: "WHOOP",
|
||||
startedAt: new Date(BASE_ROW.startedAt.getTime() + 30_000),
|
||||
sportType: "RUNNING",
|
||||
avgHeartRate: 148,
|
||||
maxHeartRate: 181,
|
||||
metadata: {
|
||||
zoneDurations: {
|
||||
zone_one_milli: 60_000,
|
||||
zone_two_milli: 300_000,
|
||||
},
|
||||
whoopWorkoutStrain: 12.3,
|
||||
},
|
||||
},
|
||||
] as never);
|
||||
|
||||
const res = await GET(makeRequest(), makeParams("w-1"));
|
||||
const body = await res.json();
|
||||
|
||||
expect(body.data).toMatchObject({
|
||||
id: "w-1",
|
||||
source: "APPLE_HEALTH",
|
||||
canonicalId: "w-1",
|
||||
avgHr: 148,
|
||||
maxHr: 181,
|
||||
route: { geometry: routeGeometry },
|
||||
metadata: { hkVersion: "1", owner: "apple" },
|
||||
});
|
||||
expect(body.data.metadata).not.toHaveProperty("whoopWorkoutStrain");
|
||||
expect(body.data.metadata).not.toHaveProperty("zoneDurations");
|
||||
expect(body.data.zones.model).toBe("whoop");
|
||||
expect(body.data.hrSeries).toBeNull();
|
||||
});
|
||||
|
||||
it("does not overwrite the canonical winner's existing HR values", async () => {
|
||||
vi.mocked(prisma.workout.findUnique).mockResolvedValueOnce(
|
||||
BASE_ROW as never,
|
||||
);
|
||||
vi.mocked(prisma.workout.findMany).mockResolvedValueOnce([
|
||||
{
|
||||
id: "w-1",
|
||||
source: "APPLE_HEALTH",
|
||||
startedAt: BASE_ROW.startedAt,
|
||||
sportType: "RUNNING",
|
||||
avgHeartRate: BASE_ROW.avgHeartRate,
|
||||
maxHeartRate: BASE_ROW.maxHeartRate,
|
||||
metadata: BASE_ROW.metadata,
|
||||
},
|
||||
{
|
||||
id: "w-whoop",
|
||||
source: "WHOOP",
|
||||
startedAt: new Date(BASE_ROW.startedAt.getTime() + 30_000),
|
||||
sportType: "RUNNING",
|
||||
avgHeartRate: 155,
|
||||
maxHeartRate: 190,
|
||||
metadata: null,
|
||||
},
|
||||
] as never);
|
||||
|
||||
const res = await GET(makeRequest(), makeParams("w-1"));
|
||||
const body = await res.json();
|
||||
|
||||
expect(body.data.avgHr).toBe(145);
|
||||
expect(body.data.maxHr).toBe(170);
|
||||
});
|
||||
|
||||
it("returns 401 without a session", async () => {
|
||||
vi.mocked(getSession).mockResolvedValueOnce(null);
|
||||
const res = await GET(makeRequest(), makeParams("w-1"));
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("returns 403 module.disabled when the workouts module is off", async () => {
|
||||
vi.mocked(requireModuleEnabled).mockResolvedValueOnce({
|
||||
enabled: false,
|
||||
response: new Response(
|
||||
JSON.stringify({ data: null, error: "Module disabled" }),
|
||||
{ status: 403 },
|
||||
),
|
||||
} as never);
|
||||
const res = await GET(makeRequest(), makeParams("w-1"));
|
||||
expect(res.status).toBe(403);
|
||||
// The detail query never runs once the gate refuses.
|
||||
expect(prisma.workout.findUnique).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns 404 when the row belongs to another user", async () => {
|
||||
vi.mocked(prisma.workout.findUnique).mockResolvedValueOnce({
|
||||
...BASE_ROW,
|
||||
userId: "user-2",
|
||||
} as never);
|
||||
|
||||
const res = await GET(makeRequest(), makeParams("w-1"));
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it("returns 404 when no row exists", async () => {
|
||||
vi.mocked(prisma.workout.findUnique).mockResolvedValueOnce(null);
|
||||
const res = await GET(makeRequest(), makeParams("w-1"));
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it("resolves canonicalId to the Apple Health twin when the requested row is the Withings sibling", async () => {
|
||||
// Same 5-minute slot + sportType, but the caller asked for the
|
||||
// Withings row. The picker's default ladder makes Apple Health win
|
||||
// the cluster, so canonicalId points at the Apple row.
|
||||
const withingsRow = {
|
||||
...BASE_ROW,
|
||||
id: "w-withings",
|
||||
source: "WITHINGS" as const,
|
||||
externalId: "withings-1",
|
||||
};
|
||||
vi.mocked(prisma.workout.findUnique).mockResolvedValueOnce(
|
||||
withingsRow as never,
|
||||
);
|
||||
vi.mocked(prisma.workout.findMany).mockResolvedValueOnce([
|
||||
{
|
||||
id: "w-apple",
|
||||
source: "APPLE_HEALTH",
|
||||
startedAt: BASE_ROW.startedAt,
|
||||
sportType: "RUNNING",
|
||||
},
|
||||
{
|
||||
id: "w-withings",
|
||||
source: "WITHINGS",
|
||||
startedAt: BASE_ROW.startedAt,
|
||||
sportType: "RUNNING",
|
||||
},
|
||||
] as never);
|
||||
|
||||
const res = await GET(makeRequest(), makeParams("w-withings"));
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(body.data.id).toBe("w-withings");
|
||||
expect(body.data.canonicalId).toBe("w-apple");
|
||||
});
|
||||
|
||||
it("adds the #67 enrichment fields and strips raw blobs under compact=1", async () => {
|
||||
const startMs = BASE_ROW.startedAt.getTime();
|
||||
const storedSamples = Array.from({ length: 40 }, (_, i) => ({
|
||||
t: new Date(startMs + i * 45_000).toISOString(),
|
||||
hr: 140 + (i % 6),
|
||||
}));
|
||||
vi.mocked(prisma.workout.findUnique).mockResolvedValueOnce({
|
||||
...BASE_ROW,
|
||||
// WHOOP device zones win → zones render even without profile age.
|
||||
metadata: {
|
||||
zoneDurations: {
|
||||
zone_one_milli: 60_000,
|
||||
zone_two_milli: 300_000,
|
||||
zone_three_milli: 600_000,
|
||||
zone_four_milli: 200_000,
|
||||
zone_five_milli: 40_000,
|
||||
},
|
||||
},
|
||||
route: {
|
||||
id: "wr-1",
|
||||
geometry: {
|
||||
type: "LineString",
|
||||
coordinates: [
|
||||
[11, 49],
|
||||
[11.01, 49.01],
|
||||
],
|
||||
},
|
||||
sampleTimestamps: [
|
||||
`${SESSION_DAY}T07:00:00Z`,
|
||||
`${SESSION_DAY}T07:01:00Z`,
|
||||
],
|
||||
createdAt: BASE_ROW.createdAt,
|
||||
},
|
||||
samples: { sampleCount: storedSamples.length, samples: storedSamples },
|
||||
} as never);
|
||||
vi.mocked(prisma.workout.findMany).mockResolvedValueOnce([
|
||||
{
|
||||
id: "w-1",
|
||||
source: "APPLE_HEALTH",
|
||||
startedAt: BASE_ROW.startedAt,
|
||||
sportType: "RUNNING",
|
||||
},
|
||||
] as never);
|
||||
|
||||
const res = await GET(
|
||||
new NextRequest("http://localhost/api/workouts/w-1?compact=1", {
|
||||
method: "GET",
|
||||
}),
|
||||
makeParams("w-1"),
|
||||
);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
// Stored series wins → provenance is the native workout series.
|
||||
expect(body.data.hrSeries.source).toBe("workout_series");
|
||||
expect(body.data.hrSeries.points.length).toBeGreaterThanOrEqual(2);
|
||||
// WHOOP device zones.
|
||||
expect(body.data.zones.model).toBe("whoop");
|
||||
// Additive keys present; reserved seam is null.
|
||||
expect(body.data).toHaveProperty("splits");
|
||||
expect(body.data).toHaveProperty("sportContext");
|
||||
expect(body.data.aiInsight).toBeNull();
|
||||
// compact=1 drops the raw blobs but keeps count + geometry.
|
||||
expect(body.data.samples.sampleCount).toBe(40);
|
||||
expect(body.data.samples.samples).toBeNull();
|
||||
expect(body.data.route.geometry).not.toBeNull();
|
||||
expect(body.data.route.sampleTimestamps).toBeNull();
|
||||
});
|
||||
|
||||
it("exposes the WorkoutRoute geometry when present", async () => {
|
||||
const routeGeometry = {
|
||||
type: "LineString",
|
||||
coordinates: [
|
||||
[11.0, 49.0],
|
||||
[11.01, 49.01],
|
||||
],
|
||||
};
|
||||
vi.mocked(prisma.workout.findUnique).mockResolvedValueOnce({
|
||||
...BASE_ROW,
|
||||
route: {
|
||||
id: "wr-1",
|
||||
geometry: routeGeometry,
|
||||
sampleTimestamps: [
|
||||
`${SESSION_DAY}T07:00:00Z`,
|
||||
`${SESSION_DAY}T07:01:00Z`,
|
||||
],
|
||||
createdAt: BASE_ROW.createdAt,
|
||||
},
|
||||
} as never);
|
||||
vi.mocked(prisma.workout.findMany).mockResolvedValueOnce([
|
||||
{
|
||||
id: "w-1",
|
||||
source: "APPLE_HEALTH",
|
||||
startedAt: BASE_ROW.startedAt,
|
||||
sportType: "RUNNING",
|
||||
},
|
||||
] as never);
|
||||
|
||||
const res = await GET(makeRequest(), makeParams("w-1"));
|
||||
const body = await res.json();
|
||||
|
||||
expect(body.data.route).not.toBeNull();
|
||||
expect(body.data.route.geometry).toEqual(routeGeometry);
|
||||
expect(body.data.route.sampleTimestamps).toEqual([
|
||||
`${SESSION_DAY}T07:00:00Z`,
|
||||
`${SESSION_DAY}T07:01:00Z`,
|
||||
]);
|
||||
});
|
||||
|
||||
describe("v1.39.4 — sealed track", () => {
|
||||
const TEST_KEY = "c".repeat(64);
|
||||
const routeGeometry = {
|
||||
type: "LineString",
|
||||
coordinates: [
|
||||
[11.0, 49.0],
|
||||
[11.005, 49.0],
|
||||
[11.01, 49.0],
|
||||
],
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv("ENCRYPTION_KEYS", "");
|
||||
vi.stubEnv("ENCRYPTION_ACTIVE_KEY_ID", "");
|
||||
vi.stubEnv("ENCRYPTION_KEY", TEST_KEY);
|
||||
_resetCryptoCacheForTests();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
_resetCryptoCacheForTests();
|
||||
});
|
||||
|
||||
function mockRoute(route: Record<string, unknown>) {
|
||||
vi.mocked(prisma.workout.findUnique).mockResolvedValueOnce({
|
||||
...BASE_ROW,
|
||||
route: {
|
||||
id: "wr-1",
|
||||
sampleTimestamps: [
|
||||
`${SESSION_DAY}T07:00:00Z`,
|
||||
`${SESSION_DAY}T07:02:00Z`,
|
||||
`${SESSION_DAY}T07:04:00Z`,
|
||||
],
|
||||
createdAt: BASE_ROW.createdAt,
|
||||
...route,
|
||||
},
|
||||
} as never);
|
||||
vi.mocked(prisma.workout.findMany).mockResolvedValueOnce([
|
||||
{
|
||||
id: "w-1",
|
||||
source: "APPLE_HEALTH",
|
||||
startedAt: BASE_ROW.startedAt,
|
||||
sportType: "RUNNING",
|
||||
},
|
||||
] as never);
|
||||
}
|
||||
|
||||
it("serves a sealed track in the same shape as a readable one, splits included", async () => {
|
||||
mockRoute({ geometry: routeGeometry, geometryEncrypted: null });
|
||||
const legacy = (
|
||||
await (await GET(makeRequest(), makeParams("w-1"))).json()
|
||||
).data;
|
||||
|
||||
mockRoute({
|
||||
geometry: null,
|
||||
geometryEncrypted: encryptRouteGeometry(routeGeometry),
|
||||
});
|
||||
const sealed = (
|
||||
await (await GET(makeRequest(), makeParams("w-1"))).json()
|
||||
).data;
|
||||
|
||||
expect(sealed.route).toEqual(legacy.route);
|
||||
expect(sealed.route.geometry).toEqual(routeGeometry);
|
||||
expect(sealed.splits).toEqual(legacy.splits);
|
||||
});
|
||||
|
||||
it("prefers the ciphertext over a readable column on the same row", async () => {
|
||||
mockRoute({
|
||||
geometry: { type: "LineString", coordinates: [[0, 0]] },
|
||||
geometryEncrypted: encryptRouteGeometry(routeGeometry),
|
||||
});
|
||||
const body = await (await GET(makeRequest(), makeParams("w-1"))).json();
|
||||
expect(body.data.route.geometry).toEqual(routeGeometry);
|
||||
});
|
||||
|
||||
it("selects the sealed column", async () => {
|
||||
mockRoute({ geometry: routeGeometry, geometryEncrypted: null });
|
||||
await GET(makeRequest(), makeParams("w-1"));
|
||||
const args = vi.mocked(prisma.workout.findUnique).mock.calls.at(-1)?.[0];
|
||||
expect(
|
||||
(args as { include: { route: { select: Record<string, boolean> } } })
|
||||
.include.route.select.geometryEncrypted,
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* The Activity-Insight read.
|
||||
*
|
||||
* The load-bearing property is what is ABSENT: this route has no enqueue, no
|
||||
* provider resolution and no fallback. A workout with no stored row serves null
|
||||
* and the page renders nothing — which is every workout that predates the
|
||||
* feature, every re-synced one, and every one on a provider-less install.
|
||||
*/
|
||||
describe("GET /api/workouts/{id} — aiInsight", () => {
|
||||
// A throwaway test key. The route decrypts a stored paragraph, so the suite
|
||||
// needs a configured cipher; `_resetCryptoCacheForTests` keeps the stubbed
|
||||
// key from leaking into the neighbouring describes.
|
||||
const TEST_KEY =
|
||||
"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.stubEnv("ENCRYPTION_KEY", TEST_KEY);
|
||||
_resetCryptoCacheForTests();
|
||||
vi.mocked(aiCapabilityToServe).mockResolvedValue(AI_AVAILABLE);
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({
|
||||
sourcePriorityJson: null,
|
||||
dateOfBirth: null,
|
||||
} as never);
|
||||
vi.mocked(prisma.measurement.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(prisma.workout.findMany).mockResolvedValue([
|
||||
{
|
||||
id: "w-1",
|
||||
source: "APPLE_HEALTH",
|
||||
startedAt: BASE_ROW.startedAt,
|
||||
sportType: "RUNNING",
|
||||
},
|
||||
] as never);
|
||||
});
|
||||
|
||||
async function get() {
|
||||
return GET(
|
||||
new NextRequest("http://localhost/api/workouts/w-1?compact=1", {
|
||||
method: "GET",
|
||||
}),
|
||||
makeParams("w-1"),
|
||||
);
|
||||
}
|
||||
|
||||
it("serves null when the workout has no stored paragraph", async () => {
|
||||
vi.mocked(prisma.workout.findUnique).mockResolvedValue({
|
||||
...BASE_ROW,
|
||||
insight: null,
|
||||
} as never);
|
||||
|
||||
const body = await (await get()).json();
|
||||
expect(body.data.aiInsight).toBeNull();
|
||||
});
|
||||
|
||||
it("serves the decrypted paragraph when one exists", async () => {
|
||||
const { encryptToBytes } = await import("@/lib/ai/coach/bytes-codec");
|
||||
const generatedAt = new Date(`${SESSION_DAY}T07:35:00Z`);
|
||||
vi.mocked(prisma.workout.findUnique).mockResolvedValue({
|
||||
...BASE_ROW,
|
||||
insight: {
|
||||
paragraphEncrypted: encryptToBytes("A steady, aerobic-leaning run."),
|
||||
generatedAt,
|
||||
},
|
||||
} as never);
|
||||
|
||||
const body = await (await get()).json();
|
||||
expect(body.data.aiInsight).toEqual({
|
||||
paragraph: "A steady, aerobic-leaning run.",
|
||||
generatedAt: generatedAt.toISOString(),
|
||||
});
|
||||
expect(aiCapabilityToServe).toHaveBeenCalledWith(
|
||||
"user-1",
|
||||
"workoutInsights",
|
||||
);
|
||||
expect(body.data.ai).toEqual(AI_AVAILABLE);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"operator_disabled",
|
||||
"user_disabled",
|
||||
"module_disabled",
|
||||
"consent_required",
|
||||
"no_provider",
|
||||
] as const)(
|
||||
"does not read or expose the stored paragraph while workoutInsights is %s",
|
||||
async (reason) => {
|
||||
vi.mocked(aiCapabilityToServe).mockResolvedValue(aiUnavailable(reason));
|
||||
vi.mocked(prisma.workout.findUnique).mockResolvedValue({
|
||||
...BASE_ROW,
|
||||
insight: {
|
||||
paragraphEncrypted: new Uint8Array([1, 2, 3]),
|
||||
generatedAt: new Date(`${SESSION_DAY}T07:35:00Z`),
|
||||
},
|
||||
} as never);
|
||||
|
||||
const body = await (await get()).json();
|
||||
expect(body.data.aiInsight).toBeNull();
|
||||
expect(body.data.ai).toEqual(aiUnavailable(reason));
|
||||
expect(prisma.workout.findUnique).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
include: expect.objectContaining({ insight: false }),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("degrades to no card rather than failing the page on an undecryptable row", async () => {
|
||||
// `decrypt` is fail-closed by design. A key rotated away must not turn the
|
||||
// whole workout-detail page into a 500 over a garnish field.
|
||||
vi.mocked(prisma.workout.findUnique).mockResolvedValue({
|
||||
...BASE_ROW,
|
||||
insight: {
|
||||
paragraphEncrypted: new Uint8Array([0, 1, 2, 3]),
|
||||
generatedAt: new Date(`${SESSION_DAY}T07:35:00Z`),
|
||||
},
|
||||
} as never);
|
||||
|
||||
const res = await get();
|
||||
const body = await res.json();
|
||||
expect(res.status).toBe(200);
|
||||
expect(body.data.aiInsight).toBeNull();
|
||||
// The rest of the payload is untouched — the failure is scoped to the field.
|
||||
expect(body.data.id).toBe("w-1");
|
||||
expect(body.data.durationSec).toBe(1800);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
_resetCryptoCacheForTests();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user