mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-19 08:12:52 +00:00
merge(integrations): honest Polar sleep timeline, shared reconstruction, OAuth returns, status envelope
This commit is contained in:
commit
d7691b6cbe
26 files changed
+1045
-128
No files matched your search
@@ -0,0 +1,79 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
vi.mock("@/lib/api-handler", () => ({
|
||||
apiHandler: <T extends (...args: unknown[]) => unknown>(fn: T) => fn,
|
||||
requireAuth: vi.fn(async () => ({ user: { id: "u1" } })),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
user: { findUnique: vi.fn(), update: vi.fn() },
|
||||
fitbitConnection: { delete: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/logging/context", () => ({ annotate: vi.fn() }));
|
||||
vi.mock("@/lib/crypto", () => ({ encrypt: (s: string) => `enc:${s}` }));
|
||||
vi.mock("@/lib/auth/audit", () => ({ auditLog: vi.fn() }));
|
||||
vi.mock("@/lib/integrations/status", () => ({ markDisconnected: vi.fn() }));
|
||||
|
||||
vi.mock("@/lib/api-response", () => ({
|
||||
apiSuccess: (data: unknown) => ({ data, error: null, status: 200 }),
|
||||
apiError: (error: string, status: number) => ({ data: null, error, status }),
|
||||
safeJson: async (req: NextRequest) => {
|
||||
try {
|
||||
return { data: await req.json(), error: null };
|
||||
} catch {
|
||||
return { data: null, error: { status: 400 } };
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
import { PUT, DELETE } from "../route";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { markDisconnected } from "@/lib/integrations/status";
|
||||
|
||||
const userUpdate = prisma.user.update as ReturnType<typeof vi.fn>;
|
||||
|
||||
function req(body: unknown): NextRequest {
|
||||
return new NextRequest("http://localhost/api/fitbit/credentials", {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(body),
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
describe("/api/fitbit/credentials", () => {
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
it("PUT 422s on missing fields", async () => {
|
||||
const res = (await (
|
||||
PUT as unknown as (r: NextRequest) => Promise<{ status: number }>
|
||||
)(req({ clientId: "" }))) as { status: number };
|
||||
expect(res.status).toBe(422);
|
||||
expect(userUpdate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("DELETE clears credentials, audits the teardown, and parks the ledger (04-L1 parity)", async () => {
|
||||
userUpdate.mockResolvedValue({});
|
||||
(
|
||||
prisma.fitbitConnection.delete as ReturnType<typeof vi.fn>
|
||||
).mockResolvedValue({});
|
||||
const res = (await (DELETE as unknown as () => Promise<{ data: unknown }>)())
|
||||
.data as { deleted: boolean };
|
||||
expect(res.deleted).toBe(true);
|
||||
expect(userUpdate).toHaveBeenCalledWith({
|
||||
where: { id: "u1" },
|
||||
data: {
|
||||
fitbitClientIdEncrypted: null,
|
||||
fitbitClientSecretEncrypted: null,
|
||||
},
|
||||
});
|
||||
expect(auditLog).toHaveBeenCalledWith("fitbit.credentials.delete", {
|
||||
userId: "u1",
|
||||
});
|
||||
expect(markDisconnected).toHaveBeenCalledWith("u1", "fitbit");
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,10 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, apiError, safeJson } from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { encrypt } from "@/lib/crypto";
|
||||
import { markDisconnected } from "@/lib/integrations/status";
|
||||
import { fitbitCredentialsSchema } from "@/lib/validations/fitbit";
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod/v4";
|
||||
@@ -60,6 +62,10 @@ export const PUT = apiHandler(async (request: NextRequest) => {
|
||||
|
||||
/**
|
||||
* Delete Fitbit credentials and the active connection.
|
||||
*
|
||||
* Audits the teardown and parks the integration ledger at `disconnected` for
|
||||
* parity with the Polar / Oura credential-DELETE so a sensitive op leaves a
|
||||
* uniform audit trail and the status snapshot does not linger at a stale state.
|
||||
*/
|
||||
export const DELETE = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
@@ -76,6 +82,8 @@ export const DELETE = apiHandler(async () => {
|
||||
fitbitClientSecretEncrypted: null,
|
||||
},
|
||||
});
|
||||
await auditLog("fitbit.credentials.delete", { userId: user.id });
|
||||
await markDisconnected(user.id, "fitbit");
|
||||
|
||||
return apiSuccess({ deleted: true });
|
||||
});
|
||||
@@ -0,0 +1,115 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("@/lib/api-handler", () => ({
|
||||
apiHandler: <T extends (...args: unknown[]) => unknown>(fn: T) => fn,
|
||||
requireAuth: vi.fn(async () => ({ user: { id: "u1" } })),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
user: { findUnique: vi.fn() },
|
||||
withingsConnection: { findUnique: vi.fn(async () => null) },
|
||||
whoopConnection: { findUnique: vi.fn(async () => null) },
|
||||
fitbitConnection: { findUnique: vi.fn(async () => null) },
|
||||
moodEntry: { count: vi.fn(async () => 0) },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/logging/context", () => ({ annotate: vi.fn() }));
|
||||
|
||||
vi.mock("@/lib/api-response", () => ({
|
||||
apiSuccess: (data: unknown) => ({ data, error: null, status: 200 }),
|
||||
}));
|
||||
|
||||
const ledger: Record<string, unknown> = {
|
||||
state: "connected",
|
||||
lastSuccessAt: null,
|
||||
lastAttemptAt: null,
|
||||
lastError: null,
|
||||
};
|
||||
vi.mock("@/lib/integrations/status", () => ({
|
||||
getIntegrationStatus: vi.fn(async (_u: string, integration: string) => ({
|
||||
integration,
|
||||
...ledger,
|
||||
})),
|
||||
getPersistentFailureThreshold: () => 5,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/withings/client", () => ({ hasActivityScope: () => false }));
|
||||
vi.mock("@/lib/moodlog-secret", () => ({ readMoodLogSecret: () => null }));
|
||||
|
||||
const polarAvailable = vi.fn(async () => true);
|
||||
const ouraAvailable = vi.fn(async () => false);
|
||||
vi.mock("@/lib/polar/credentials", () => ({
|
||||
getPolarClientCredentials: () => polarAvailable(),
|
||||
}));
|
||||
vi.mock("@/lib/oura/credentials", () => ({
|
||||
getOuraClientCredentials: () => ouraAvailable(),
|
||||
}));
|
||||
|
||||
import { GET } from "../route";
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
const userFind = prisma.user.findUnique as ReturnType<typeof vi.fn>;
|
||||
|
||||
type Entry = {
|
||||
integration: string;
|
||||
connected?: boolean;
|
||||
configured?: boolean;
|
||||
available?: boolean;
|
||||
hasOwnCredentials?: boolean;
|
||||
};
|
||||
|
||||
async function fetchEntries(): Promise<Entry[]> {
|
||||
const res = (await (GET as unknown as () => Promise<{ data: unknown }>)())
|
||||
.data as { integrations: Entry[] };
|
||||
return res.integrations;
|
||||
}
|
||||
|
||||
describe("/api/integrations/status — Polar/Oura fold (04-M2)", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
polarAvailable.mockResolvedValue(true);
|
||||
ouraAvailable.mockResolvedValue(false);
|
||||
});
|
||||
|
||||
it("includes polar + oura entries on the consolidated envelope", async () => {
|
||||
userFind.mockResolvedValue({
|
||||
polarAccessTokenEncrypted: "tok",
|
||||
polarClientIdEncrypted: "id",
|
||||
polarClientSecretEncrypted: "sec",
|
||||
ouraAccessTokenEncrypted: null,
|
||||
ouraClientIdEncrypted: null,
|
||||
ouraClientSecretEncrypted: null,
|
||||
});
|
||||
|
||||
const entries = await fetchEntries();
|
||||
const keys = entries.map((e) => e.integration);
|
||||
expect(keys).toEqual(
|
||||
expect.arrayContaining(["polar", "oura"]),
|
||||
);
|
||||
|
||||
const polar = entries.find((e) => e.integration === "polar")!;
|
||||
expect(polar.connected).toBe(true);
|
||||
expect(polar.configured).toBe(true);
|
||||
expect(polar.available).toBe(true);
|
||||
expect(polar.hasOwnCredentials).toBe(true);
|
||||
|
||||
const oura = entries.find((e) => e.integration === "oura")!;
|
||||
expect(oura.connected).toBe(false);
|
||||
expect(oura.available).toBe(false);
|
||||
expect(oura.hasOwnCredentials).toBe(false);
|
||||
});
|
||||
|
||||
it("reports polar disconnected when no access token is stored", async () => {
|
||||
userFind.mockResolvedValue({
|
||||
polarAccessTokenEncrypted: null,
|
||||
polarClientIdEncrypted: null,
|
||||
polarClientSecretEncrypted: null,
|
||||
});
|
||||
const entries = await fetchEntries();
|
||||
const polar = entries.find((e) => e.integration === "polar")!;
|
||||
expect(polar.connected).toBe(false);
|
||||
expect(polar.configured).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -24,6 +24,8 @@ import {
|
||||
getPersistentFailureThreshold,
|
||||
type IntegrationKey,
|
||||
} from "@/lib/integrations/status";
|
||||
import { getOuraClientCredentials } from "@/lib/oura/credentials";
|
||||
import { getPolarClientCredentials } from "@/lib/polar/credentials";
|
||||
import { hasActivityScope } from "@/lib/withings/client";
|
||||
import { readMoodLogSecret } from "@/lib/moodlog-secret";
|
||||
|
||||
@@ -38,16 +40,25 @@ export const GET = apiHandler(async () => {
|
||||
moodLogStatus,
|
||||
whoopStatus,
|
||||
fitbitStatus,
|
||||
polarStatus,
|
||||
ouraStatus,
|
||||
dbUser,
|
||||
withingsConn,
|
||||
whoopConn,
|
||||
fitbitConn,
|
||||
moodLogEntryCount,
|
||||
// v1.17.1 — `available` reports whether usable OAuth credentials resolve
|
||||
// (per-user BYO first, then the shared env app), mirroring the per-card
|
||||
// /api/<provider>/status the consolidated envelope now replaces.
|
||||
polarAvailable,
|
||||
ouraAvailable,
|
||||
] = await Promise.all([
|
||||
getIntegrationStatus(user.id, "withings"),
|
||||
getIntegrationStatus(user.id, "moodlog"),
|
||||
getIntegrationStatus(user.id, "whoop"),
|
||||
getIntegrationStatus(user.id, "fitbit"),
|
||||
getIntegrationStatus(user.id, "polar"),
|
||||
getIntegrationStatus(user.id, "oura"),
|
||||
prisma.user.findUnique({
|
||||
where: { id: user.id },
|
||||
select: {
|
||||
@@ -57,6 +68,12 @@ export const GET = apiHandler(async () => {
|
||||
whoopClientSecretEncrypted: true,
|
||||
fitbitClientIdEncrypted: true,
|
||||
fitbitClientSecretEncrypted: true,
|
||||
polarAccessTokenEncrypted: true,
|
||||
polarClientIdEncrypted: true,
|
||||
polarClientSecretEncrypted: true,
|
||||
ouraAccessTokenEncrypted: true,
|
||||
ouraClientIdEncrypted: true,
|
||||
ouraClientSecretEncrypted: true,
|
||||
moodLogUrlEncrypted: true,
|
||||
moodLogApiKeyEncrypted: true,
|
||||
moodLogEnabled: true,
|
||||
@@ -95,6 +112,8 @@ export const GET = apiHandler(async () => {
|
||||
prisma.moodEntry.count({
|
||||
where: { userId: user.id, deletedAt: null },
|
||||
}),
|
||||
getPolarClientCredentials(user.id).then((c) => !!c),
|
||||
getOuraClientCredentials(user.id).then((c) => !!c),
|
||||
]);
|
||||
|
||||
const now = Date.now();
|
||||
@@ -164,6 +183,28 @@ export const GET = apiHandler(async () => {
|
||||
: null,
|
||||
backfillCompleted: fitbitConn ? !!fitbitConn.backfillCompletedAt : null,
|
||||
} satisfies IntegrationViewModel & FitbitExtras,
|
||||
{
|
||||
...polarStatus,
|
||||
// `connected` = a stored access token; `configured` mirrors it (the
|
||||
// OAuth card has no separate "credentials saved but disconnected" view
|
||||
// beyond `hasOwnCredentials`). The card greys out the connect button
|
||||
// when no usable credentials resolve (`available`).
|
||||
connected: !!dbUser?.polarAccessTokenEncrypted,
|
||||
configured: !!dbUser?.polarAccessTokenEncrypted,
|
||||
available: polarAvailable,
|
||||
hasOwnCredentials:
|
||||
!!dbUser?.polarClientIdEncrypted &&
|
||||
!!dbUser?.polarClientSecretEncrypted,
|
||||
} satisfies IntegrationViewModel & OAuthProviderExtras,
|
||||
{
|
||||
...ouraStatus,
|
||||
connected: !!dbUser?.ouraAccessTokenEncrypted,
|
||||
configured: !!dbUser?.ouraAccessTokenEncrypted,
|
||||
available: ouraAvailable,
|
||||
hasOwnCredentials:
|
||||
!!dbUser?.ouraClientIdEncrypted &&
|
||||
!!dbUser?.ouraClientSecretEncrypted,
|
||||
} satisfies IntegrationViewModel & OAuthProviderExtras,
|
||||
],
|
||||
});
|
||||
});
|
||||
@@ -214,3 +255,13 @@ interface FitbitExtras {
|
||||
tokenExpired: boolean | null;
|
||||
backfillCompleted: boolean | null;
|
||||
}
|
||||
|
||||
// v1.17.1 — Polar / Oura fold into the consolidated envelope. They carry the
|
||||
// per-user BYO-key flags the shared OAuth card reads instead of the dedicated
|
||||
// /api/<provider>/status round-trip the page used to fire per card.
|
||||
interface OAuthProviderExtras {
|
||||
connected: boolean;
|
||||
configured: boolean;
|
||||
available: boolean;
|
||||
hasOwnCredentials: boolean;
|
||||
}
|
||||
@@ -15,6 +15,8 @@ vi.mock("@/lib/db", () => ({
|
||||
|
||||
vi.mock("@/lib/logging/context", () => ({ annotate: vi.fn() }));
|
||||
vi.mock("@/lib/crypto", () => ({ encrypt: (s: string) => `enc:${s}` }));
|
||||
vi.mock("@/lib/auth/audit", () => ({ auditLog: vi.fn() }));
|
||||
vi.mock("@/lib/integrations/status", () => ({ markDisconnected: vi.fn() }));
|
||||
|
||||
vi.mock("@/lib/api-response", () => ({
|
||||
apiSuccess: (data: unknown) => ({ data, error: null, status: 200 }),
|
||||
@@ -30,6 +32,8 @@ vi.mock("@/lib/api-response", () => ({
|
||||
|
||||
import { GET, PUT, DELETE } from "../route";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { markDisconnected } from "@/lib/integrations/status";
|
||||
|
||||
const userFind = prisma.user.findUnique as ReturnType<typeof vi.fn>;
|
||||
const userUpdate = prisma.user.update as ReturnType<typeof vi.fn>;
|
||||
@@ -91,4 +95,16 @@ describe("/api/whoop/credentials", () => {
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("DELETE audits the teardown and parks the ledger (04-L1 parity)", async () => {
|
||||
userUpdate.mockResolvedValue({});
|
||||
(prisma.whoopConnection.delete as ReturnType<typeof vi.fn>).mockResolvedValue(
|
||||
{},
|
||||
);
|
||||
await (DELETE as unknown as () => Promise<unknown>)();
|
||||
expect(auditLog).toHaveBeenCalledWith("whoop.credentials.delete", {
|
||||
userId: "u1",
|
||||
});
|
||||
expect(markDisconnected).toHaveBeenCalledWith("u1", "whoop");
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,10 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiSuccess, apiError, safeJson } from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { encrypt } from "@/lib/crypto";
|
||||
import { markDisconnected } from "@/lib/integrations/status";
|
||||
import { whoopCredentialsSchema } from "@/lib/validations/whoop";
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod/v4";
|
||||
@@ -58,6 +60,10 @@ export const PUT = apiHandler(async (request: NextRequest) => {
|
||||
|
||||
/**
|
||||
* Delete WHOOP credentials and the active connection.
|
||||
*
|
||||
* Audits the teardown and parks the integration ledger at `disconnected` for
|
||||
* parity with the Polar / Oura credential-DELETE so a sensitive op leaves a
|
||||
* uniform audit trail and the status snapshot does not linger at a stale state.
|
||||
*/
|
||||
export const DELETE = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
@@ -74,6 +80,8 @@ export const DELETE = apiHandler(async () => {
|
||||
whoopClientSecretEncrypted: null,
|
||||
},
|
||||
});
|
||||
await auditLog("whoop.credentials.delete", { userId: user.id });
|
||||
await markDisconnected(user.id, "whoop");
|
||||
|
||||
return apiSuccess({ deleted: true });
|
||||
});
|
||||
Reference in new issue
Block a user