mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-09 13:01:00 +00:00
Merge the auth and integration route groups
Two component-id collisions, both from the same cause: two paths that
are two doors onto one action, documented independently.
DELETE /api/devices/{id} and DELETE /api/auth/me/devices/{id} both call
revokeDeviceCascade and answer with the same shape. Each grew its own
DeviceRevokeResponse, which the emitter refuses outright. The response
moves to shared.ts so neither module owns it and the next door onto the
same call finds it; the two envelopes keep separate names because an
envelope names an operation.
The settings module took both halves by hand rather than by keep-both:
one side added nine paths, the other three, with no overlap but a shared
import block and a shared reminder-thresholds entry that a mechanical
union duplicated.
This commit is contained in:
commit
30930b46d0
34 files changed
+4292
-143
No files matched your search
@@ -2,6 +2,7 @@ import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { apiSuccess, apiError } from "@/lib/api-response";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { readSyncTriggerBody } from "@/lib/integrations/sync-request";
|
||||
import { syncUserFitbit } from "@/lib/fitbit/sync";
|
||||
import { resolveSyncOutcome } from "@/lib/outcome/written-outcome";
|
||||
import { NextRequest } from "next/server";
|
||||
@@ -30,18 +31,9 @@ export const POST = apiHandler(async (request: NextRequest) => {
|
||||
});
|
||||
}
|
||||
|
||||
let fullSync = false;
|
||||
try {
|
||||
const raw = await request.text();
|
||||
// Flag-only payload — cap the parse cost (mirrors safeJson maxBytes).
|
||||
if (raw.length > 64 * 1024) {
|
||||
return apiError(`Request body exceeds ${64 * 1024} bytes`, 413);
|
||||
}
|
||||
const body = JSON.parse(raw);
|
||||
fullSync = body?.fullSync === true;
|
||||
} catch {
|
||||
// no body provided -> default incremental sync
|
||||
}
|
||||
const body = await readSyncTriggerBody(request);
|
||||
if (body.error) return body.error;
|
||||
const { fullSync } = body;
|
||||
|
||||
// The full-history walk is the expensive path (four paginated resource
|
||||
// walkers); cap it well below the incremental bucket so a re-trigger loop
|
||||
|
||||
@@ -6,21 +6,10 @@ 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 { googleHealthCredentialsSchema } from "@/lib/validations/google-health";
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
/**
|
||||
* Per-user Google Health BYO-key credentials. Each self-hoster registers their
|
||||
* own Google Cloud OAuth client (the Restricted-scope brand verification + CASA
|
||||
* assessment is per-OAuth-client, so a single shared app is unworkable for a
|
||||
* multi-operator product) and pastes the client id/secret into Settings. Stored
|
||||
* encrypted on `User`.
|
||||
*/
|
||||
const googleHealthCredentialsSchema = z.object({
|
||||
clientId: z.string().min(1).max(200),
|
||||
clientSecret: z.string().min(1).max(200),
|
||||
});
|
||||
|
||||
/**
|
||||
* Check whether the user has Google Health BYO-key credentials stored
|
||||
* (v1.26.0).
|
||||
|
||||
@@ -2,6 +2,7 @@ import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { apiSuccess, apiError } from "@/lib/api-response";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { readSyncTriggerBody } from "@/lib/integrations/sync-request";
|
||||
import { syncUserGoogleHealth } from "@/lib/google-health/sync";
|
||||
import type {
|
||||
GoogleHealthReasonCode,
|
||||
@@ -83,18 +84,9 @@ export const POST = apiHandler(async (request: NextRequest) => {
|
||||
});
|
||||
}
|
||||
|
||||
let fullSync = false;
|
||||
try {
|
||||
const raw = await request.text();
|
||||
// Flag-only payload — cap the parse cost (mirrors safeJson maxBytes).
|
||||
if (raw.length > 64 * 1024) {
|
||||
return apiError(`Request body exceeds ${64 * 1024} bytes`, 413);
|
||||
}
|
||||
const body = JSON.parse(raw);
|
||||
fullSync = body?.fullSync === true;
|
||||
} catch {
|
||||
// no body provided -> default incremental sync
|
||||
}
|
||||
const body = await readSyncTriggerBody(request);
|
||||
if (body.error) return body.error;
|
||||
const { fullSync } = body;
|
||||
|
||||
// The full-history walk is the expensive path; cap it well below the
|
||||
// incremental bucket so a re-trigger loop cannot churn the Google quota.
|
||||
|
||||
@@ -70,10 +70,19 @@ type Entry = {
|
||||
metricFreshness?: Array<{ type: string; lastSeenAt: string; stale: boolean }>;
|
||||
};
|
||||
|
||||
async function fetchEnvelope(): Promise<{
|
||||
integrations: Entry[];
|
||||
metricFreshnessDegraded: boolean;
|
||||
}> {
|
||||
return (await (GET as unknown as () => Promise<{ data: unknown }>)())
|
||||
.data as {
|
||||
integrations: Entry[];
|
||||
metricFreshnessDegraded: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
async function fetchEntries(): Promise<Entry[]> {
|
||||
const res = (await (GET as unknown as () => Promise<{ data: unknown }>)())
|
||||
.data as { integrations: Entry[] };
|
||||
return res.integrations;
|
||||
return (await fetchEnvelope()).integrations;
|
||||
}
|
||||
|
||||
describe("/api/integrations/status — Polar/Oura fold (04-M2)", () => {
|
||||
@@ -277,3 +286,61 @@ describe("/api/integrations/status — a provider that has delivered nothing for
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* The freshness read is fail-soft, and it used to be fail-silent with it.
|
||||
*
|
||||
* `getSourceMetricFreshness` is one query for all eight providers, wrapped in a
|
||||
* `.catch(() => ({}))` so a groupBy hiccup never 500s the whole settings
|
||||
* surface. The fallback makes every entry's `metricFreshness` an empty array —
|
||||
* which is byte-identical to what a user with nothing recorded sees. So the
|
||||
* honesty signal built to say "this metric has gone quiet" answered "nothing
|
||||
* has gone quiet" when it had in fact failed to look.
|
||||
*
|
||||
* `metricFreshnessDegraded` separates the two. It stays a flag rather than a
|
||||
* nullable array per entry because the query fails for all eight providers at
|
||||
* once or for none of them.
|
||||
*/
|
||||
describe("/api/integrations/status — the freshness read failed", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
for (const key of Object.keys(perIntegrationLedger)) {
|
||||
delete perIntegrationLedger[key];
|
||||
}
|
||||
userFind.mockResolvedValue({});
|
||||
whoopFind.mockResolvedValue(null);
|
||||
polarAvailable.mockResolvedValue(true);
|
||||
ouraAvailable.mockResolvedValue(false);
|
||||
});
|
||||
|
||||
it("reports the degradation instead of passing an empty list off as an answer", async () => {
|
||||
(prisma.measurement.groupBy as ReturnType<typeof vi.fn>).mockRejectedValue(
|
||||
new Error("statement timeout"),
|
||||
);
|
||||
|
||||
const envelope = await fetchEnvelope();
|
||||
|
||||
expect(envelope.metricFreshnessDegraded).toBe(true);
|
||||
// Still fail-soft: the rest of the envelope survives, all eight entries
|
||||
// present, because a freshness hiccup is never worth the settings surface.
|
||||
expect(envelope.integrations).toHaveLength(8);
|
||||
for (const entry of envelope.integrations) {
|
||||
expect(entry.metricFreshness).toEqual([]);
|
||||
}
|
||||
});
|
||||
|
||||
it("reports no degradation when the read simply found nothing", async () => {
|
||||
(prisma.measurement.groupBy as ReturnType<typeof vi.fn>).mockResolvedValue(
|
||||
[],
|
||||
);
|
||||
(prisma.workout.groupBy as ReturnType<typeof vi.fn>).mockResolvedValue([]);
|
||||
|
||||
const envelope = await fetchEnvelope();
|
||||
|
||||
// The same empty lists as above, and this is the case they honestly mean.
|
||||
expect(envelope.metricFreshnessDegraded).toBe(false);
|
||||
for (const entry of envelope.integrations) {
|
||||
expect(entry.metricFreshness).toEqual([]);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -149,9 +149,20 @@ export const GET = apiHandler(async () => {
|
||||
// single metric type has gone silent even while the integration reads green
|
||||
// ("connected · 5 min ago"). Fail-soft: this is an honesty signal, never worth
|
||||
// 500-ing the whole Settings card, so a groupBy hiccup degrades to no data.
|
||||
const metricFreshness = await getSourceMetricFreshness(user.id).catch(
|
||||
() => ({}) as Partial<Record<IntegrationKey, MetricFreshnessSample[]>>,
|
||||
);
|
||||
//
|
||||
// The degradation is REPORTED rather than swallowed. Falling back to `{}`
|
||||
// makes every entry's `metricFreshness` an empty array, which is exactly what
|
||||
// a user with nothing recorded also sees — so "no metric has gone quiet" and
|
||||
// "we could not tell whether a metric has gone quiet" were the same answer on
|
||||
// the wire, and the honesty signal quietly became the thing it was built to
|
||||
// prevent. `metricFreshnessDegraded` separates them. One flag rather than a
|
||||
// nullable array per entry, because this is ONE query for all eight providers
|
||||
// — it fails for all of them or for none.
|
||||
let metricFreshnessDegraded = false;
|
||||
const metricFreshness = await getSourceMetricFreshness(user.id).catch(() => {
|
||||
metricFreshnessDegraded = true;
|
||||
return {} as Partial<Record<IntegrationKey, MetricFreshnessSample[]>>;
|
||||
});
|
||||
|
||||
const now = Date.now();
|
||||
const whoopConnected = !!whoopConn?.whoopUserId;
|
||||
@@ -243,8 +254,13 @@ export const GET = apiHandler(async () => {
|
||||
const stravaConnected = !!dbUser?.stravaAccessTokenEncrypted;
|
||||
const nightscoutConfigured = !!dbUser?.nightscoutUrlEncrypted;
|
||||
|
||||
if (metricFreshnessDegraded) {
|
||||
annotate({ meta: { integrations_metric_freshness_degraded: true } });
|
||||
}
|
||||
|
||||
return apiSuccess({
|
||||
threshold: getPersistentFailureThreshold(),
|
||||
metricFreshnessDegraded,
|
||||
integrations: [
|
||||
{
|
||||
...publish(withingsStatus),
|
||||
|
||||
@@ -18,7 +18,6 @@
|
||||
* every REST write) — it only admits the confirmed in-process write tools.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import {
|
||||
@@ -33,16 +32,11 @@ import { issueApiToken } from "@/lib/auth/issue-token";
|
||||
import { isApiGloballyEnabled } from "@/lib/app-settings";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { SCOPE_HEALTH_READ, SCOPE_HEALTH_WRITE } from "@/lib/mcp/oauth/config";
|
||||
|
||||
const createSchema = z.object({
|
||||
name: z.string().min(1, "Name required").max(100),
|
||||
expiresInDays: z.number().int().min(1).max(365).optional(),
|
||||
// The ONLY two scope shapes this endpoint will mint. `read` (default) is the
|
||||
// least-privilege read token; `read_write` adds `health:write` so the
|
||||
// confirmed `/mcp` write tools become available. Anything else is rejected
|
||||
// by the enum — the endpoint can never mint a wildcard or arbitrary grant.
|
||||
scope: z.enum(["read", "read_write"]).optional().default("read"),
|
||||
});
|
||||
// The ONLY two scope shapes this endpoint will mint. `read` (default) is the
|
||||
// least-privilege read token; `read_write` adds `health:write` so the confirmed
|
||||
// `/mcp` write tools become available. Anything else is rejected by the enum —
|
||||
// the endpoint can never mint a wildcard or arbitrary grant.
|
||||
import { createMcpTokenSchema } from "@/lib/validations/mcp";
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
@@ -89,7 +83,7 @@ export const POST = apiHandler(async (request: NextRequest) => {
|
||||
});
|
||||
if (jsonError) return jsonError;
|
||||
|
||||
const parsed = createSchema.safeParse(body);
|
||||
const parsed = createMcpTokenSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return returnAllZodIssues(parsed.error, 422);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod/v4";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
@@ -7,6 +6,7 @@ import { apiSuccess, apiError } from "@/lib/api-response";
|
||||
import { CHANNEL_TYPE_LABELS, EVENT_TYPES } from "@/lib/notifications/types";
|
||||
import type { ChannelType, EventType } from "@/lib/notifications/types";
|
||||
import { reEnableChannel } from "@/lib/notifications/channel-state";
|
||||
import { reEnableChannelSchema } from "@/lib/validations/notifications";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@@ -131,10 +131,6 @@ export const GET = apiHandler(async () => {
|
||||
return apiSuccess({ channels: data, events });
|
||||
});
|
||||
|
||||
const reEnableSchema = z.object({
|
||||
channelId: z.string().min(1).max(64),
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /api/notifications/status
|
||||
*
|
||||
@@ -159,7 +155,7 @@ export const POST = apiHandler(async (request: NextRequest) => {
|
||||
return apiError("Invalid JSON data", 422);
|
||||
}
|
||||
|
||||
const parsed = reEnableSchema.safeParse(body);
|
||||
const parsed = reEnableChannelSchema.safeParse(body);
|
||||
if (!parsed.success) return apiError("Invalid data", 422);
|
||||
|
||||
const channel = await prisma.notificationChannel.findFirst({
|
||||
|
||||
@@ -111,12 +111,23 @@ describe("DELETE /api/oura/credentials", () => {
|
||||
expect(markDisconnected).toHaveBeenCalledWith("u1", "oura");
|
||||
});
|
||||
|
||||
it("skips audit + ledger update when nothing was connected", async () => {
|
||||
/**
|
||||
* This case used to assert the opposite, and the assertion was the defect.
|
||||
*
|
||||
* Auditing only when a token happened to be present meant that tearing down
|
||||
* a stored credential pair which had never completed OAuth left no trail at
|
||||
* all — and a credential teardown is exactly the event an operator reads the
|
||||
* audit trail for. The Polar twin has always done both unconditionally; the
|
||||
* old expectation pinned the divergence rather than catching it.
|
||||
*/
|
||||
it("audits + marks disconnected even when nothing was connected", async () => {
|
||||
userFind.mockResolvedValue({ ouraAccessTokenEncrypted: null });
|
||||
const res = await del();
|
||||
expect(res.data).toEqual({ deleted: true });
|
||||
expect(clearMock).toHaveBeenCalledWith("u1");
|
||||
expect(auditLog).not.toHaveBeenCalled();
|
||||
expect(markDisconnected).not.toHaveBeenCalled();
|
||||
expect(auditLog).toHaveBeenCalledWith("oura.credentials.delete", {
|
||||
userId: "u1",
|
||||
});
|
||||
expect(markDisconnected).toHaveBeenCalledWith("u1", "oura");
|
||||
});
|
||||
});
|
||||
@@ -67,20 +67,21 @@ export const PUT = apiHandler(async (request: NextRequest) => {
|
||||
* Delete Oura credentials and the active connection.
|
||||
*
|
||||
* Deleting the BYO credentials drops a live connection (a token minted against
|
||||
* the deleted app is now orphaned), so when an access token was present this
|
||||
* mirrors `/api/oura/disconnect`: audit the event and park the integration
|
||||
* ledger at `disconnected` rather than leaving it stale at its last state.
|
||||
* the deleted app is now orphaned), so this mirrors `/api/oura/disconnect`:
|
||||
* audit the event and park the integration ledger at `disconnected` rather than
|
||||
* leaving it stale at its last state.
|
||||
*
|
||||
* Both are unconditional, matching the Polar twin. They used to run only when
|
||||
* an access token happened to be present, so tearing down a stored credential
|
||||
* pair that had never been connected left no audit row at all — and a
|
||||
* credential teardown is exactly the event an operator reads the trail for. The
|
||||
* ledger park is idempotent, so running it for an already-disconnected provider
|
||||
* costs one write and changes nothing.
|
||||
*/
|
||||
export const DELETE = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "oura.credentials.delete" } });
|
||||
|
||||
const dbUser = await prisma.user.findUnique({
|
||||
where: { id: user.id },
|
||||
select: { ouraAccessTokenEncrypted: true },
|
||||
});
|
||||
const wasConnected = !!dbUser?.ouraAccessTokenEncrypted;
|
||||
|
||||
await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: {
|
||||
@@ -90,10 +91,8 @@ export const DELETE = apiHandler(async () => {
|
||||
});
|
||||
await clearOuraClientCredentials(user.id);
|
||||
|
||||
if (wasConnected) {
|
||||
await auditLog("oura.credentials.delete", { userId: user.id });
|
||||
await markDisconnected(user.id, "oura");
|
||||
}
|
||||
await auditLog("oura.credentials.delete", { userId: user.id });
|
||||
await markDisconnected(user.id, "oura");
|
||||
|
||||
return apiSuccess({ deleted: true });
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* `DELETE /api/strava/credentials` — the teardown always leaves a trail.
|
||||
*
|
||||
* The audit row and the ledger park used to run only when an access token
|
||||
* happened to be present, so removing a stored credential pair that had never
|
||||
* completed OAuth was invisible afterwards: no audit row, and a ledger left at
|
||||
* whatever state it last held. The Polar twin has always done both
|
||||
* unconditionally. Strava had no test file at all, which is why this one
|
||||
* exists.
|
||||
*/
|
||||
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(), update: vi.fn() } },
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/logging/context", () => ({ annotate: vi.fn() }));
|
||||
vi.mock("@/lib/auth/audit", () => ({ auditLog: vi.fn() }));
|
||||
vi.mock("@/lib/integrations/status", () => ({ markDisconnected: vi.fn() }));
|
||||
|
||||
const { storeMock, clearMock } = vi.hoisted(() => ({
|
||||
storeMock: vi.fn(),
|
||||
clearMock: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/lib/strava/credentials", () => ({
|
||||
storeStravaClientCredentials: storeMock,
|
||||
clearStravaClientCredentials: clearMock,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/api-response", () => ({
|
||||
apiSuccess: (data: unknown) => ({ data, error: null, status: 200 }),
|
||||
apiError: (error: string, status: number) => ({ data: null, error, status }),
|
||||
safeJson: vi.fn(),
|
||||
}));
|
||||
|
||||
import { 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>;
|
||||
|
||||
type RouteResult = { data: unknown; error: string | null; status: number };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
userFind.mockResolvedValue(null);
|
||||
userUpdate.mockResolvedValue({});
|
||||
clearMock.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
describe("DELETE /api/strava/credentials", () => {
|
||||
const del = DELETE as unknown as () => Promise<RouteResult>;
|
||||
|
||||
it("audits + marks disconnected when a live token was present", async () => {
|
||||
userFind.mockResolvedValue({ stravaAccessTokenEncrypted: "enc:tok" });
|
||||
const res = await del();
|
||||
expect(res.data).toEqual({ deleted: true });
|
||||
expect(clearMock).toHaveBeenCalledWith("u1");
|
||||
expect(auditLog).toHaveBeenCalledWith("strava.credentials.delete", {
|
||||
userId: "u1",
|
||||
});
|
||||
expect(markDisconnected).toHaveBeenCalledWith("u1", "strava");
|
||||
});
|
||||
|
||||
it("audits + marks disconnected even when nothing was connected", async () => {
|
||||
userFind.mockResolvedValue({ stravaAccessTokenEncrypted: null });
|
||||
const res = await del();
|
||||
expect(res.data).toEqual({ deleted: true });
|
||||
expect(clearMock).toHaveBeenCalledWith("u1");
|
||||
expect(auditLog).toHaveBeenCalledWith("strava.credentials.delete", {
|
||||
userId: "u1",
|
||||
});
|
||||
expect(markDisconnected).toHaveBeenCalledWith("u1", "strava");
|
||||
});
|
||||
|
||||
it("clears the athlete id alongside both tokens", async () => {
|
||||
await del();
|
||||
expect(userUpdate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: {
|
||||
stravaAccessTokenEncrypted: null,
|
||||
stravaRefreshTokenEncrypted: null,
|
||||
stravaAthleteId: null,
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -68,20 +68,25 @@ export const PUT = apiHandler(async (request: NextRequest) => {
|
||||
* Delete Strava credentials and the active connection.
|
||||
*
|
||||
* Deleting the BYO credentials drops a live connection (a token minted against
|
||||
* the deleted app is now orphaned), so when an access token was present this
|
||||
* mirrors `/api/strava/disconnect`: audit the event and park the integration
|
||||
* ledger at `disconnected` rather than leaving it stale at its last state.
|
||||
* the deleted app is now orphaned), so this mirrors `/api/strava/disconnect`:
|
||||
* audit the event and park the integration ledger at `disconnected` rather than
|
||||
* leaving it stale at its last state.
|
||||
*
|
||||
* Both are unconditional, matching the Polar twin. They used to run only when
|
||||
* an access token happened to be present, so tearing down a stored credential
|
||||
* pair that had never been connected left no audit row at all — and a
|
||||
* credential teardown is exactly the event an operator reads the trail for. The
|
||||
* ledger park is idempotent, so running it for an already-disconnected provider
|
||||
* costs one write and changes nothing.
|
||||
*
|
||||
* Note that this route still does NOT deauthorize at Strava; only
|
||||
* `POST /api/strava/disconnect` does. Removing the keys here therefore leaves
|
||||
* the app authorised on the user's Strava account.
|
||||
*/
|
||||
export const DELETE = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "strava.credentials.delete" } });
|
||||
|
||||
const dbUser = await prisma.user.findUnique({
|
||||
where: { id: user.id },
|
||||
select: { stravaAccessTokenEncrypted: true },
|
||||
});
|
||||
const wasConnected = !!dbUser?.stravaAccessTokenEncrypted;
|
||||
|
||||
await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: {
|
||||
@@ -92,10 +97,8 @@ export const DELETE = apiHandler(async () => {
|
||||
});
|
||||
await clearStravaClientCredentials(user.id);
|
||||
|
||||
if (wasConnected) {
|
||||
await auditLog("strava.credentials.delete", { userId: user.id });
|
||||
await markDisconnected(user.id, "strava");
|
||||
}
|
||||
await auditLog("strava.credentials.delete", { userId: user.id });
|
||||
await markDisconnected(user.id, "strava");
|
||||
|
||||
return apiSuccess({ deleted: true });
|
||||
});
|
||||
@@ -8,15 +8,14 @@ vi.mock("@/lib/api-handler", () => ({
|
||||
|
||||
vi.mock("@/lib/logging/context", () => ({ annotate: vi.fn() }));
|
||||
vi.mock("@/lib/whoop/sync", () => ({ syncUserWhoop: vi.fn() }));
|
||||
|
||||
vi.mock("@/lib/api-response", () => ({
|
||||
apiSuccess: (data: unknown) => ({ data, error: null }),
|
||||
}));
|
||||
vi.mock("@/lib/rate-limit", () => ({ checkRateLimit: vi.fn() }));
|
||||
|
||||
import { POST } from "../route";
|
||||
import { syncUserWhoop } from "@/lib/whoop/sync";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
|
||||
const sync = syncUserWhoop as ReturnType<typeof vi.fn>;
|
||||
const limit = checkRateLimit as ReturnType<typeof vi.fn>;
|
||||
|
||||
function req(body?: unknown): NextRequest {
|
||||
return new NextRequest("http://localhost/api/whoop/sync", {
|
||||
@@ -26,25 +25,92 @@ function req(body?: unknown): NextRequest {
|
||||
});
|
||||
}
|
||||
|
||||
function raw(body: string): NextRequest {
|
||||
return new NextRequest("http://localhost/api/whoop/sync", {
|
||||
method: "POST",
|
||||
body,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
const post = POST as unknown as (r: NextRequest) => Promise<Response>;
|
||||
|
||||
describe("POST /api/whoop/sync", () => {
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
limit.mockResolvedValue({ allowed: true });
|
||||
});
|
||||
|
||||
it("triggers an incremental sync by default", async () => {
|
||||
sync.mockResolvedValue({ imported: 7, failed: false });
|
||||
const res = (await (
|
||||
POST as unknown as (r: NextRequest) => Promise<{ data: unknown }>
|
||||
)(req({}))) as { data: { imported: number; fullSync: boolean } };
|
||||
expect(res.data.imported).toBe(7);
|
||||
expect(res.data.fullSync).toBe(false);
|
||||
const res = await post(req({}));
|
||||
const json = (await res.json()) as {
|
||||
data: { imported: number; fullSync: boolean };
|
||||
};
|
||||
expect(json.data.imported).toBe(7);
|
||||
expect(json.data.fullSync).toBe(false);
|
||||
expect(sync).toHaveBeenCalledWith("u1", { fullSync: false });
|
||||
});
|
||||
|
||||
it("treats an absent body as an incremental run", async () => {
|
||||
sync.mockResolvedValue({ imported: 1, failed: false });
|
||||
const res = await post(req());
|
||||
expect(res.status).toBe(200);
|
||||
expect(sync).toHaveBeenCalledWith("u1", { fullSync: false });
|
||||
});
|
||||
|
||||
it("honours fullSync: true", async () => {
|
||||
sync.mockResolvedValue({ imported: 99, failed: false });
|
||||
const res = (await (
|
||||
POST as unknown as (r: NextRequest) => Promise<{ data: unknown }>
|
||||
)(req({ fullSync: true }))) as { data: { fullSync: boolean } };
|
||||
expect(res.data.fullSync).toBe(true);
|
||||
const res = await post(req({ fullSync: true }));
|
||||
const json = (await res.json()) as { data: { fullSync: boolean } };
|
||||
expect(json.data.fullSync).toBe(true);
|
||||
expect(sync).toHaveBeenCalledWith("u1", { fullSync: true });
|
||||
});
|
||||
|
||||
/**
|
||||
* WHOOP and Withings were the two manual syncs with no limiter at all, while
|
||||
* `fullSync` drives the full four-resource history walk against WHOOP's
|
||||
* per-user budget. The Fitbit route's own comment records that it was "the
|
||||
* outlier" until it got one; these two were never brought along.
|
||||
*/
|
||||
it("refuses once the baseline 5/60s bucket is spent", async () => {
|
||||
limit.mockResolvedValueOnce({ allowed: false });
|
||||
const res = await post(req({}));
|
||||
expect(res.status).toBe(429);
|
||||
expect(sync).not.toHaveBeenCalled();
|
||||
expect(limit).toHaveBeenCalledWith("whoop-sync:u1", 5, 60_000);
|
||||
});
|
||||
|
||||
it("caps the full-history walk at one per hour on its own bucket", async () => {
|
||||
limit
|
||||
.mockResolvedValueOnce({ allowed: true })
|
||||
.mockResolvedValueOnce({ allowed: false });
|
||||
const res = await post(req({ fullSync: true }));
|
||||
expect(res.status).toBe(429);
|
||||
expect(sync).not.toHaveBeenCalled();
|
||||
expect(limit).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
"whoop-sync-full:u1",
|
||||
1,
|
||||
3_600_000,
|
||||
);
|
||||
});
|
||||
|
||||
it("does not consult the full-sync bucket for an incremental run", async () => {
|
||||
sync.mockResolvedValue({ imported: 0, failed: false });
|
||||
await post(req({ fullSync: false }));
|
||||
expect(limit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("refuses a present-but-unparseable body instead of syncing", async () => {
|
||||
const res = await post(raw("{ fullSync"));
|
||||
expect(res.status).toBe(400);
|
||||
expect(sync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("refuses a mistyped fullSync instead of silently going incremental", async () => {
|
||||
const res = await post(req({ fullSync: "true" }));
|
||||
expect(res.status).toBe(422);
|
||||
expect(sync).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,8 @@
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { apiSuccess, apiError } from "@/lib/api-response";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { readSyncTriggerBody } from "@/lib/integrations/sync-request";
|
||||
import { resolveSyncOutcome } from "@/lib/outcome/written-outcome";
|
||||
import { syncUserWhoop } from "@/lib/whoop/sync";
|
||||
import { NextRequest } from "next/server";
|
||||
@@ -10,22 +12,40 @@ import { NextRequest } from "next/server";
|
||||
*
|
||||
* Mirrors the Withings manual-sync route: incremental by default, full
|
||||
* history when `{ fullSync: true }` is posted.
|
||||
*
|
||||
* Rate-limited on both arms, matching the Fitbit / Google Health siblings.
|
||||
* This route and the Withings one were the two that never got a limiter, while
|
||||
* `fullSync` drives the full four-resource history walk against WHOOP's
|
||||
* per-user budget: a tight loop or a stolen native token could exhaust it and
|
||||
* pin Prisma. A baseline 5/60s bucket gates the route and the expensive
|
||||
* `fullSync` path carries a tighter 1/hour bucket of its own.
|
||||
*/
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "whoop.sync" } });
|
||||
|
||||
let fullSync = false;
|
||||
try {
|
||||
const raw = await request.text();
|
||||
// Flag-only payload — cap the parse cost (mirrors safeJson maxBytes).
|
||||
if (raw.length > 64 * 1024) {
|
||||
return apiError(`Request body exceeds ${64 * 1024} bytes`, 413);
|
||||
const rl = await checkRateLimit(`whoop-sync:${user.id}`, 5, 60_000);
|
||||
if (!rl.allowed) {
|
||||
return apiError("Too many sync requests", 429, {
|
||||
errorCode: "rate_limited_self",
|
||||
});
|
||||
}
|
||||
|
||||
const body = await readSyncTriggerBody(request);
|
||||
if (body.error) return body.error;
|
||||
const { fullSync } = body;
|
||||
|
||||
if (fullSync) {
|
||||
const fullRl = await checkRateLimit(
|
||||
`whoop-sync-full:${user.id}`,
|
||||
1,
|
||||
60 * 60_000,
|
||||
);
|
||||
if (!fullRl.allowed) {
|
||||
return apiError("Full sync is limited to once per hour", 429, {
|
||||
errorCode: "rate_limited_self",
|
||||
});
|
||||
}
|
||||
const body = JSON.parse(raw);
|
||||
fullSync = body?.fullSync === true;
|
||||
} catch {
|
||||
// no body provided -> default incremental sync
|
||||
}
|
||||
|
||||
// Resolved server-side so the card and the native client cannot disagree on
|
||||
|
||||
@@ -24,6 +24,9 @@ vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
|
||||
vi.mock("@/lib/auth/audit", () => ({
|
||||
auditLog: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
vi.mock("@/lib/integrations/status", () => ({
|
||||
markDisconnected: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
|
||||
vi.mock("@/lib/db-compat", () => ({
|
||||
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
|
||||
@@ -40,6 +43,8 @@ vi.mock("next/headers", () => ({
|
||||
import { DELETE } from "../route";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { markDisconnected } from "@/lib/integrations/status";
|
||||
|
||||
const SESSION_OK = {
|
||||
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
|
||||
@@ -93,4 +98,41 @@ describe("DELETE /api/withings/credentials", () => {
|
||||
// the encrypted OAuth tokens survive is the worst of both states.
|
||||
expect(prisma.user.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
/**
|
||||
* Withings was the one provider whose credential DELETE wrote no audit row
|
||||
* and left the ledger alone. Fitbit, Google Health and WHOOP all park theirs,
|
||||
* and three of them say in their own comments that they do it for parity —
|
||||
* with a list that never included Withings. The visible cost was a client
|
||||
* reading `state` after the teardown and being told `connected` about a
|
||||
* connection that no longer existed.
|
||||
*/
|
||||
it("audits the teardown and parks the ledger at disconnected", async () => {
|
||||
vi.mocked(prisma.withingsConnection.delete).mockResolvedValue({} as never);
|
||||
const res = await DELETE();
|
||||
expect(res.status).toBe(200);
|
||||
expect(auditLog).toHaveBeenCalledWith("withings.credentials.delete", {
|
||||
userId: "user-1",
|
||||
});
|
||||
expect(markDisconnected).toHaveBeenCalledWith("user-1", "withings");
|
||||
});
|
||||
|
||||
it("still audits and parks when the connection row was already gone", async () => {
|
||||
vi.mocked(prisma.withingsConnection.delete).mockRejectedValue(p2025());
|
||||
const res = await DELETE();
|
||||
expect(res.status).toBe(200);
|
||||
expect(auditLog).toHaveBeenCalledWith("withings.credentials.delete", {
|
||||
userId: "user-1",
|
||||
});
|
||||
expect(markDisconnected).toHaveBeenCalledWith("user-1", "withings");
|
||||
});
|
||||
|
||||
it("does not audit or park when the teardown itself failed", async () => {
|
||||
vi.mocked(prisma.withingsConnection.delete).mockRejectedValue(
|
||||
new Error("connection terminated unexpectedly"),
|
||||
);
|
||||
await DELETE();
|
||||
expect(auditLog).not.toHaveBeenCalled();
|
||||
expect(markDisconnected).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,9 @@ import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { apiSuccess, apiError, safeJson } from "@/lib/api-response";
|
||||
import { isP2025 } from "@/lib/prisma-errors";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { markDisconnected } from "@/lib/integrations/status";
|
||||
import { encrypt } from "@/lib/crypto";
|
||||
import { withingsCredentialsSchema } from "@/lib/validations/withings";
|
||||
import { NextRequest } from "next/server";
|
||||
@@ -60,6 +62,13 @@ export const PUT = apiHandler(async (request: NextRequest) => {
|
||||
|
||||
/**
|
||||
* Delete Withings credentials and disconnect.
|
||||
*
|
||||
* Audits the teardown and parks the integration ledger at `disconnected`, for
|
||||
* parity with the Fitbit / Google Health / WHOOP credential-DELETE. Withings
|
||||
* was the one provider that did neither: the connection row went, the
|
||||
* credential columns went, and the ledger kept whatever state it last held —
|
||||
* so a client reading `state` afterwards was told `connected` about a
|
||||
* connection that no longer existed, and a sensitive teardown left no trail.
|
||||
*/
|
||||
export const DELETE = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
@@ -84,5 +93,8 @@ export const DELETE = apiHandler(async () => {
|
||||
},
|
||||
});
|
||||
|
||||
await auditLog("withings.credentials.delete", { userId: user.id });
|
||||
await markDisconnected(user.id, "withings");
|
||||
|
||||
return apiSuccess({ deleted: true });
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* `POST /api/withings/sync` — the limiter and the honest body parse.
|
||||
*
|
||||
* Withings and WHOOP were the two manual syncs that never got a rate limiter,
|
||||
* while `fullSync` drives the full measure-history walk against the provider's
|
||||
* per-user budget. Withings had no test file at all, which is why this one
|
||||
* exists; the WHOOP twin carries the same shape.
|
||||
*/
|
||||
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/logging/context", () => ({ annotate: vi.fn() }));
|
||||
vi.mock("@/lib/withings/sync", () => ({ syncUserMeasurements: vi.fn() }));
|
||||
vi.mock("@/lib/rate-limit", () => ({ checkRateLimit: vi.fn() }));
|
||||
|
||||
import { POST } from "../route";
|
||||
import { syncUserMeasurements } from "@/lib/withings/sync";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
|
||||
const sync = syncUserMeasurements as ReturnType<typeof vi.fn>;
|
||||
const limit = checkRateLimit as ReturnType<typeof vi.fn>;
|
||||
|
||||
function req(body?: unknown): NextRequest {
|
||||
return new NextRequest("http://localhost/api/withings/sync", {
|
||||
method: "POST",
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
function raw(body: string): NextRequest {
|
||||
return new NextRequest("http://localhost/api/withings/sync", {
|
||||
method: "POST",
|
||||
body,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
const post = POST as unknown as (r: NextRequest) => Promise<Response>;
|
||||
|
||||
describe("POST /api/withings/sync", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
limit.mockResolvedValue({ allowed: true });
|
||||
});
|
||||
|
||||
it("triggers an incremental sync by default", async () => {
|
||||
sync.mockResolvedValue({ imported: 4, failed: false });
|
||||
const res = await post(req({}));
|
||||
const json = (await res.json()) as {
|
||||
data: { imported: number; fullSync: boolean };
|
||||
};
|
||||
expect(json.data.imported).toBe(4);
|
||||
expect(json.data.fullSync).toBe(false);
|
||||
expect(sync).toHaveBeenCalledWith("u1", { fullSync: false });
|
||||
});
|
||||
|
||||
it("treats an absent body as an incremental run", async () => {
|
||||
sync.mockResolvedValue({ imported: 0, failed: false });
|
||||
const res = await post(req());
|
||||
expect(res.status).toBe(200);
|
||||
expect(sync).toHaveBeenCalledWith("u1", { fullSync: false });
|
||||
});
|
||||
|
||||
it("honours fullSync: true", async () => {
|
||||
sync.mockResolvedValue({ imported: 120, failed: false });
|
||||
const res = await post(req({ fullSync: true }));
|
||||
const json = (await res.json()) as { data: { fullSync: boolean } };
|
||||
expect(json.data.fullSync).toBe(true);
|
||||
expect(sync).toHaveBeenCalledWith("u1", { fullSync: true });
|
||||
});
|
||||
|
||||
it("refuses once the baseline 5/60s bucket is spent", async () => {
|
||||
limit.mockResolvedValueOnce({ allowed: false });
|
||||
const res = await post(req({}));
|
||||
expect(res.status).toBe(429);
|
||||
expect(sync).not.toHaveBeenCalled();
|
||||
expect(limit).toHaveBeenCalledWith("withings-sync:u1", 5, 60_000);
|
||||
});
|
||||
|
||||
it("caps the full-history walk at one per hour on its own bucket", async () => {
|
||||
limit
|
||||
.mockResolvedValueOnce({ allowed: true })
|
||||
.mockResolvedValueOnce({ allowed: false });
|
||||
const res = await post(req({ fullSync: true }));
|
||||
expect(res.status).toBe(429);
|
||||
expect(sync).not.toHaveBeenCalled();
|
||||
expect(limit).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
"withings-sync-full:u1",
|
||||
1,
|
||||
3_600_000,
|
||||
);
|
||||
});
|
||||
|
||||
it("does not consult the full-sync bucket for an incremental run", async () => {
|
||||
sync.mockResolvedValue({ imported: 0, failed: false });
|
||||
await post(req({ fullSync: false }));
|
||||
expect(limit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("refuses a present-but-unparseable body instead of syncing", async () => {
|
||||
const res = await post(raw("{ fullSync"));
|
||||
expect(res.status).toBe(400);
|
||||
expect(sync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("refuses a mistyped fullSync instead of silently going incremental", async () => {
|
||||
const res = await post(req({ fullSync: "true" }));
|
||||
expect(res.status).toBe(422);
|
||||
expect(sync).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,28 +1,48 @@
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { apiSuccess, apiError } from "@/lib/api-response";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { readSyncTriggerBody } from "@/lib/integrations/sync-request";
|
||||
import { resolveSyncOutcome } from "@/lib/outcome/written-outcome";
|
||||
import { syncUserMeasurements } from "@/lib/withings/sync";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
/**
|
||||
* Manually trigger a Withings sync for the current user.
|
||||
*
|
||||
* Rate-limited on both arms, matching the Fitbit / Google Health siblings.
|
||||
* This route and the WHOOP one were the two that never got a limiter, while
|
||||
* `fullSync` drives the full measure-history walk against Withings' per-user
|
||||
* budget: a tight loop or a stolen native token could exhaust it and pin
|
||||
* Prisma. A baseline 5/60s bucket gates the route and the expensive `fullSync`
|
||||
* path carries a tighter 1/hour bucket of its own.
|
||||
*/
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "withings.sync" } });
|
||||
|
||||
let fullSync = false;
|
||||
try {
|
||||
const raw = await request.text();
|
||||
// Flag-only payload — cap the parse cost (mirrors safeJson maxBytes).
|
||||
if (raw.length > 64 * 1024) {
|
||||
return apiError(`Request body exceeds ${64 * 1024} bytes`, 413);
|
||||
const rl = await checkRateLimit(`withings-sync:${user.id}`, 5, 60_000);
|
||||
if (!rl.allowed) {
|
||||
return apiError("Too many sync requests", 429, {
|
||||
errorCode: "rate_limited_self",
|
||||
});
|
||||
}
|
||||
|
||||
const body = await readSyncTriggerBody(request);
|
||||
if (body.error) return body.error;
|
||||
const { fullSync } = body;
|
||||
|
||||
if (fullSync) {
|
||||
const fullRl = await checkRateLimit(
|
||||
`withings-sync-full:${user.id}`,
|
||||
1,
|
||||
60 * 60_000,
|
||||
);
|
||||
if (!fullRl.allowed) {
|
||||
return apiError("Full sync is limited to once per hour", 429, {
|
||||
errorCode: "rate_limited_self",
|
||||
});
|
||||
}
|
||||
const body = JSON.parse(raw);
|
||||
fullSync = body?.fullSync === true;
|
||||
} catch {
|
||||
// no body provided -> default incremental sync
|
||||
}
|
||||
|
||||
const result = await syncUserMeasurements(user.id, { fullSync });
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* The manual-sync trigger body tells its three cases apart.
|
||||
*
|
||||
* Before this helper, all four provider sync routes shared one `try { … }
|
||||
* catch { /* no body provided -> default incremental sync *\/ }` block, and the
|
||||
* comment was true for only one of the three ways to reach it. A body that was
|
||||
* present and unparseable, and a body carrying `"fullSync": "true"` as a
|
||||
* string, both came out as `fullSync = false` with a 200 — so a client that
|
||||
* asked for full history and got the type wrong was told the incremental run it
|
||||
* never requested had succeeded.
|
||||
*
|
||||
* The absent-body case is load-bearing in the other direction: it is the
|
||||
* documented shape and the tests below pin it, so tightening the wrong two
|
||||
* cases cannot take it with them.
|
||||
*/
|
||||
import { describe, it, expect } from "vitest";
|
||||
|
||||
import { readSyncTriggerBody } from "../sync-request";
|
||||
|
||||
function req(body?: BodyInit, contentType = "application/json"): Request {
|
||||
return new Request("http://localhost/api/whoop/sync", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": contentType },
|
||||
...(body === undefined ? {} : { body }),
|
||||
});
|
||||
}
|
||||
|
||||
async function envelope(res: Response) {
|
||||
return (await res.json()) as {
|
||||
data: null;
|
||||
error: string;
|
||||
details?: { issues?: unknown[] };
|
||||
};
|
||||
}
|
||||
|
||||
describe("readSyncTriggerBody", () => {
|
||||
it("reads an absent body as an incremental run", async () => {
|
||||
const out = await readSyncTriggerBody(req());
|
||||
expect(out.error).toBeUndefined();
|
||||
expect(out.fullSync).toBe(false);
|
||||
});
|
||||
|
||||
it("reads a whitespace-only body as an incremental run", async () => {
|
||||
const out = await readSyncTriggerBody(req("\n"));
|
||||
expect(out.error).toBeUndefined();
|
||||
expect(out.fullSync).toBe(false);
|
||||
});
|
||||
|
||||
it("reads an empty object as an incremental run", async () => {
|
||||
const out = await readSyncTriggerBody(req("{}"));
|
||||
expect(out.error).toBeUndefined();
|
||||
expect(out.fullSync).toBe(false);
|
||||
});
|
||||
|
||||
it("honours an explicit fullSync: true", async () => {
|
||||
const out = await readSyncTriggerBody(
|
||||
req(JSON.stringify({ fullSync: true })),
|
||||
);
|
||||
expect(out.error).toBeUndefined();
|
||||
expect(out.fullSync).toBe(true);
|
||||
});
|
||||
|
||||
it("honours an explicit fullSync: false", async () => {
|
||||
const out = await readSyncTriggerBody(
|
||||
req(JSON.stringify({ fullSync: false })),
|
||||
);
|
||||
expect(out.error).toBeUndefined();
|
||||
expect(out.fullSync).toBe(false);
|
||||
});
|
||||
|
||||
it("ignores unknown keys rather than refusing them", async () => {
|
||||
const out = await readSyncTriggerBody(
|
||||
req(JSON.stringify({ fullSync: true, since: "2026-01-01" })),
|
||||
);
|
||||
expect(out.error).toBeUndefined();
|
||||
expect(out.fullSync).toBe(true);
|
||||
});
|
||||
|
||||
it("refuses a present-but-unparseable body with 400", async () => {
|
||||
const out = await readSyncTriggerBody(req("{ fullSync: true"));
|
||||
expect(out.fullSync).toBeUndefined();
|
||||
expect(out.error?.status).toBe(400);
|
||||
expect((await envelope(out.error!)).error).toBe("Invalid JSON body");
|
||||
});
|
||||
|
||||
/**
|
||||
* The case the old catch-all hid: a string where a boolean belongs used to
|
||||
* read as "the user asked for an incremental sync", and the 200 said so.
|
||||
*/
|
||||
it("refuses a string fullSync with 422 rather than reading it as false", async () => {
|
||||
const out = await readSyncTriggerBody(
|
||||
req(JSON.stringify({ fullSync: "true" })),
|
||||
);
|
||||
expect(out.fullSync).toBeUndefined();
|
||||
expect(out.error?.status).toBe(422);
|
||||
const body = await envelope(out.error!);
|
||||
expect(body.error).toBe("Validation failed");
|
||||
expect(body.details?.issues?.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("refuses a JSON scalar body with 422", async () => {
|
||||
const out = await readSyncTriggerBody(req("null"));
|
||||
expect(out.fullSync).toBeUndefined();
|
||||
expect(out.error?.status).toBe(422);
|
||||
});
|
||||
|
||||
it("refuses a body over the 64 KiB cap with 413", async () => {
|
||||
const out = await readSyncTriggerBody(
|
||||
req(JSON.stringify({ fullSync: true, pad: "x".repeat(70 * 1024) })),
|
||||
);
|
||||
expect(out.fullSync).toBeUndefined();
|
||||
expect(out.error?.status).toBe(413);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* The manual-sync trigger body, read once for every provider.
|
||||
*
|
||||
* Four sync routes each carried their own copy of this:
|
||||
*
|
||||
* let fullSync = false;
|
||||
* try {
|
||||
* const raw = await request.text();
|
||||
* if (raw.length > 64 * 1024) return apiError(…, 413);
|
||||
* const body = JSON.parse(raw);
|
||||
* fullSync = body?.fullSync === true;
|
||||
* } catch {
|
||||
* // no body provided -> default incremental sync
|
||||
* }
|
||||
*
|
||||
* The comment is only true for one of the three cases that reach the catch. An
|
||||
* absent body means an incremental run, and that is the documented and used
|
||||
* shape. But a body that is present and unparseable, and a body that is present
|
||||
* and carries `"fullSync": "true"` as a string, both landed in the same place:
|
||||
* `fullSync = false`, a 200, and a response that reads to the client as a
|
||||
* successful incremental sync. A caller could ask for full history, get a typo
|
||||
* wrong, and be told it worked.
|
||||
*
|
||||
* This separates the three. Absent still means incremental. Present and
|
||||
* unparseable is a 400, present and failing the schema is a 422 with the
|
||||
* multi-issue envelope the rest of the surface uses. No caller that sends
|
||||
* nothing, `{}`, or a well-formed `{ "fullSync": <bool> }` sees any change; the
|
||||
* only requests that now fail are the ones that were already being misread.
|
||||
*/
|
||||
import { apiError, returnAllZodIssues } from "@/lib/api-response";
|
||||
import { syncTriggerSchema } from "@/lib/validations/sync-trigger";
|
||||
|
||||
/** Matches the per-route cap the four copies each applied by hand. */
|
||||
export const SYNC_TRIGGER_MAX_BYTES = 64 * 1024;
|
||||
|
||||
export type SyncTriggerBody =
|
||||
{ fullSync: boolean; error?: never } | { fullSync?: never; error: Response };
|
||||
|
||||
/**
|
||||
* Resolve `fullSync` from the request body, refusing a body that is present
|
||||
* and wrong instead of silently reading it as `false`.
|
||||
*/
|
||||
export async function readSyncTriggerBody(
|
||||
request: Request,
|
||||
): Promise<SyncTriggerBody> {
|
||||
let raw: string;
|
||||
try {
|
||||
raw = await request.text();
|
||||
} catch {
|
||||
return { error: apiError("Invalid request body", 400) };
|
||||
}
|
||||
|
||||
if (raw.length > SYNC_TRIGGER_MAX_BYTES) {
|
||||
return {
|
||||
error: apiError(
|
||||
`Request body exceeds ${SYNC_TRIGGER_MAX_BYTES} bytes`,
|
||||
413,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
// An absent body is the documented way to ask for an incremental run, and
|
||||
// stays one. Whitespace-only counts as absent: some HTTP clients send a
|
||||
// newline for a bodyless POST, and refusing that would be a refusal of the
|
||||
// shape this branch exists to keep working.
|
||||
if (raw.trim() === "") return { fullSync: false };
|
||||
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(raw);
|
||||
} catch {
|
||||
return { error: apiError("Invalid JSON body", 400) };
|
||||
}
|
||||
|
||||
const result = syncTriggerSchema.safeParse(parsed);
|
||||
if (!result.success) return { error: returnAllZodIssues(result.error, 422) };
|
||||
|
||||
return { fullSync: result.data.fullSync === true };
|
||||
}
|
||||
@@ -7,7 +7,12 @@
|
||||
*/
|
||||
import { z } from "zod/v4";
|
||||
import type { ZodOpenApiObject } from "zod-openapi";
|
||||
import { dataEnvelope, errorEnvelope, stdResponses } from "./shared";
|
||||
import {
|
||||
dataEnvelope,
|
||||
deviceRevokeResponse,
|
||||
errorEnvelope,
|
||||
stdResponses,
|
||||
} from "./shared";
|
||||
|
||||
const deviceRegisterRequest = z
|
||||
.object({
|
||||
@@ -92,4 +97,40 @@ export const devicePaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
},
|
||||
},
|
||||
},
|
||||
"/api/devices/{id}": {
|
||||
delete: {
|
||||
tags: ["Devices"],
|
||||
summary: "Revoke a device and everything bound to it",
|
||||
description:
|
||||
"Deletes the device and, in one transaction, revokes every refresh and access token bound to it — the cleanup a native client runs when it rotates its own registration. The counts come back so the caller can log what the cascade actually killed. Scoped to the caller's own devices: an id belonging to somebody else is indistinguishable from one that does not exist. This is a second URL for `DELETE /api/auth/me/devices/{id}`; the two share one transactional helper and behave identically, and the duplication exists so the native rotation loop has a path that is not the settings-surface one. Auth via cookie or Bearer.",
|
||||
parameters: [
|
||||
{
|
||||
name: "id",
|
||||
in: "path",
|
||||
required: true,
|
||||
schema: { type: "string" },
|
||||
description: "Device id.",
|
||||
},
|
||||
],
|
||||
responses: {
|
||||
"200": {
|
||||
description: "The device and its tokens were revoked.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
deviceRevokeResponse,
|
||||
"DeviceRevokeEnvelope",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
"404": {
|
||||
description:
|
||||
"No such device for this caller — also the answer for one already revoked, so a retry after a successful revoke is a 404 rather than an idempotent 200.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -65,12 +65,15 @@ import {
|
||||
medicationResource,
|
||||
medicationDoseHistoryImportFatalReasonEnum,
|
||||
} from "./medications";
|
||||
import { mcpPaths } from "./mcp";
|
||||
import { metaPaths } from "./meta";
|
||||
import { moodPaths } from "./mood";
|
||||
import { notificationTransportPaths } from "./notifications-transport";
|
||||
import { notificationChannelPaths } from "./notifications";
|
||||
import { nutrientPaths } from "./nutrients";
|
||||
import { onboardingPaths } from "./onboarding";
|
||||
import { profilePaths } from "./profile";
|
||||
import { recordSettingsPaths } from "./record-settings";
|
||||
import { settingsPaths } from "./settings";
|
||||
import { syncPaths } from "./sync";
|
||||
import { workoutPaths } from "./workouts";
|
||||
@@ -133,6 +136,18 @@ export const openApiPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
// lifecycle and the per-channel self-tests (appended, spread order is
|
||||
// load-bearing).
|
||||
...notificationTransportPaths,
|
||||
// Notification channels + MCP connector credentials: both families answered
|
||||
// the native client for several releases while being absent from the
|
||||
// registry, because `openapi:check` compares the registry against the YAML
|
||||
// and never the routes against the registry (appended, spread order is
|
||||
// load-bearing).
|
||||
...notificationChannelPaths,
|
||||
...mcpPaths,
|
||||
// The managed record's own configuration tree. Kept out of the sharing module
|
||||
// because it is the one surface fenced by `requireGuardianAuth`, and its 403
|
||||
// therefore has to be the shared refusal sentence rather than the neighbouring
|
||||
// module's local wording (appended, spread order is load-bearing).
|
||||
...recordSettingsPaths,
|
||||
};
|
||||
|
||||
export const openApiComponents: NonNullable<ZodOpenApiObject["components"]> = {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,276 @@
|
||||
/**
|
||||
* OpenAPI route table — MCP connector credentials.
|
||||
*
|
||||
* Part of the OpenAPI route table; aggregated in `./index.ts`. The request
|
||||
* body comes from `src/lib/validations/mcp.ts` so the wire contract stays
|
||||
* single-source; the response DTOs mirror the handlers under
|
||||
* `src/app/api/mcp/*`.
|
||||
*
|
||||
* Two credential families reach the `/mcp` endpoint and both are managed here,
|
||||
* because a user revoking access needs one place that lists everything that can
|
||||
* read their record over MCP:
|
||||
*
|
||||
* - A **connection** is what the OAuth bridge (`/api/mcp/oauth/*`) creates
|
||||
* for a remote connector. It outlives the 60-minute access tokens it
|
||||
* issues, so revoking the connection ends the whole refresh chain.
|
||||
* - A **connector token** is the manual / stdio path: a `hlk_` Bearer minted
|
||||
* here, scoped `health:read` (optionally plus `health:write`), never the
|
||||
* `["*"]` wildcard.
|
||||
*
|
||||
* The OAuth routes themselves are deliberately absent: they answer RFC-format
|
||||
* error bodies rather than the standard envelope, and they are described by the
|
||||
* OAuth metadata documents, not by this contract.
|
||||
*/
|
||||
import { z } from "zod/v4";
|
||||
import type { ZodOpenApiObject } from "zod-openapi";
|
||||
|
||||
import { createMcpTokenSchema } from "@/lib/validations/mcp";
|
||||
import { dataEnvelope, errorEnvelope, stdResponses } from "./shared";
|
||||
|
||||
/**
|
||||
* The operator kill switch. `isApiGloballyEnabled()` gates every route in this
|
||||
* module, so an instance with the API turned off refuses connector management
|
||||
* as well as connector traffic — a valid session does not get past it.
|
||||
*/
|
||||
const apiDisabledResponse = {
|
||||
"403": {
|
||||
description:
|
||||
"The operator has disabled the API instance-wide. Every route in this module refuses while that setting is off, for a cookie session as well as for a Bearer token; it is not a per-user permission and retrying will not help.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
};
|
||||
|
||||
const mcpConnection = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
clientName: z
|
||||
.string()
|
||||
.describe(
|
||||
"Name the OAuth client registered itself under. Client-supplied at registration time — display it as such, do not treat it as verified.",
|
||||
),
|
||||
scope: z
|
||||
.string()
|
||||
.describe("Space-separated scope string granted to this connection."),
|
||||
createdAt: z.iso.datetime({ offset: true }),
|
||||
lastUsedAt: z.iso
|
||||
.datetime({ offset: true })
|
||||
.nullable()
|
||||
.describe("Null when the connection has never been exercised."),
|
||||
})
|
||||
.meta({
|
||||
id: "McpConnection",
|
||||
description:
|
||||
"A live remote-connector authorization created through the MCP OAuth bridge. Carries no token material: the access tokens it issued are not addressable here, they are ended by revoking the connection.",
|
||||
});
|
||||
|
||||
const mcpConnectorToken = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
permissions: z
|
||||
.array(z.string())
|
||||
.describe(
|
||||
'The granted scopes — `["health:read"]` or `["health:read", "health:write"]`. A `health:write` token is audience-bound to `/mcp`: the resource-server guard refuses it on every REST write, so it only admits the confirmed in-process write tools.',
|
||||
),
|
||||
lastUsedAt: z.iso.datetime({ offset: true }).nullable(),
|
||||
expiresAt: z.iso.datetime({ offset: true }).nullable(),
|
||||
createdAt: z.iso.datetime({ offset: true }),
|
||||
revoked: z
|
||||
.boolean()
|
||||
.describe(
|
||||
"Revoked tokens stay in this list rather than disappearing from it, so a client must filter if it wants live credentials only.",
|
||||
),
|
||||
})
|
||||
.meta({
|
||||
id: "McpConnectorToken",
|
||||
description:
|
||||
"A manually-minted MCP connector token. The token VALUE is not part of this shape — it exists in one response only, the 201 that mints it.",
|
||||
});
|
||||
|
||||
const createMcpTokenRequest = createMcpTokenSchema.meta({
|
||||
id: "CreateMcpTokenRequest",
|
||||
description:
|
||||
"Mint a connector Bearer. `scope` is a closed two-value choice, not a permission list: `read` (the default) grants `health:read`, `read_write` adds `health:write`. The permission array is built field by field from that choice, so no request shape can widen the grant. `expiresInDays` defaults to 90.",
|
||||
});
|
||||
|
||||
const createMcpTokenResponse = z
|
||||
.object({
|
||||
token: z
|
||||
.string()
|
||||
.describe(
|
||||
"The raw `hlk_` Bearer, RETURNED EXACTLY ONCE. It is stored only as an HMAC-SHA256 hash, so there is no way to retrieve it later; a client that does not capture it here has to mint a replacement. Treat it as a secret in logs, crash reports and analytics.",
|
||||
),
|
||||
name: z.string(),
|
||||
expiresAt: z.iso.datetime({ offset: true }),
|
||||
})
|
||||
.meta({
|
||||
id: "CreateMcpTokenResponse",
|
||||
description:
|
||||
"The one response in the API that carries a usable Bearer token value for an MCP connector.",
|
||||
});
|
||||
|
||||
export const mcpPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
"/api/mcp/connections": {
|
||||
get: {
|
||||
tags: ["MCP"],
|
||||
summary: "List the caller's live MCP connector connections",
|
||||
description:
|
||||
"Returns the caller's non-revoked OAuth-bridge connections, newest first. `data` is the array itself, not nested under a named key. Auth via cookie or Bearer.",
|
||||
responses: {
|
||||
...apiDisabledResponse,
|
||||
"200": {
|
||||
description: "Live connections.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
z.array(mcpConnection),
|
||||
"McpConnectionListEnvelope",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
},
|
||||
"/api/mcp/connections/{id}": {
|
||||
delete: {
|
||||
tags: ["MCP"],
|
||||
summary: "Revoke an MCP connector connection",
|
||||
description:
|
||||
"Stamps the connection revoked so every future refresh fails, and revokes every access token it ever issued. Ownership is enforced inside the revoke, so a connection id alone cannot reach somebody else's connection — an id the caller does not own is indistinguishable from one that does not exist. Auth via cookie or Bearer.",
|
||||
parameters: [
|
||||
{
|
||||
name: "id",
|
||||
in: "path",
|
||||
required: true,
|
||||
schema: { type: "string" },
|
||||
description: "Connection id from the list endpoint.",
|
||||
},
|
||||
],
|
||||
responses: {
|
||||
...apiDisabledResponse,
|
||||
"200": {
|
||||
description: "The connection was revoked.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
z.object({ revoked: z.literal(true) }),
|
||||
"McpConnectionRevokeEnvelope",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
"404": {
|
||||
description:
|
||||
"No live connection with this id for this caller — also the answer for an already-revoked one, so a repeat revoke is 404 rather than an idempotent 200.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
},
|
||||
"/api/mcp/tokens": {
|
||||
get: {
|
||||
tags: ["MCP"],
|
||||
summary: "List the caller's MCP connector tokens",
|
||||
description:
|
||||
"Returns the caller's manually-minted `health:read` tokens, newest first, revoked ones included. Access tokens issued by the OAuth bridge are excluded — they are transient 60-minute rows that would flood the list, and they are surfaced and revoked as connections instead. `data` is the array itself, not nested under a named key. Auth via cookie or Bearer.",
|
||||
responses: {
|
||||
...apiDisabledResponse,
|
||||
"200": {
|
||||
description: "Connector tokens.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
z.array(mcpConnectorToken),
|
||||
"McpConnectorTokenListEnvelope",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
post: {
|
||||
tags: ["MCP"],
|
||||
summary: "Mint an MCP connector token",
|
||||
description:
|
||||
"Mints a `health:read` (optionally read+write) Bearer for the manual / stdio path and audits the mint. THE RESPONSE CARRIES THE RAW TOKEN — this is the only place it ever exists, and it cannot be retrieved again. Body capped at 16 KiB. Auth via cookie or Bearer.",
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: { "application/json": { schema: createMcpTokenRequest } },
|
||||
},
|
||||
responses: {
|
||||
...apiDisabledResponse,
|
||||
"201": {
|
||||
description:
|
||||
"Token minted. The `token` field is the only copy of the secret.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
createMcpTokenResponse,
|
||||
"CreateMcpTokenEnvelope",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
"400": {
|
||||
description: "Body is not parseable JSON.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
"413": {
|
||||
description: "Body exceeds 16 KiB.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
"415": {
|
||||
description: "Content-Type is not `application/json`.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
...stdResponses,
|
||||
"422": {
|
||||
description:
|
||||
"Validation failed. The envelope carries every offending issue, not just the first.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
"/api/mcp/tokens/{id}": {
|
||||
delete: {
|
||||
tags: ["MCP"],
|
||||
summary: "Revoke an MCP connector token",
|
||||
description:
|
||||
"Marks the token revoked and audits it. The lookup requires the token to be the caller's own AND to carry `health:read`, so this endpoint can never revoke a differently-scoped credential by id alone — a native-client or ingest token is a 404 here. Auth via cookie or Bearer.",
|
||||
parameters: [
|
||||
{
|
||||
name: "id",
|
||||
in: "path",
|
||||
required: true,
|
||||
schema: { type: "string" },
|
||||
description: "Token id from the list endpoint.",
|
||||
},
|
||||
],
|
||||
responses: {
|
||||
...apiDisabledResponse,
|
||||
"200": {
|
||||
description: "The token was revoked.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
z.object({ revoked: z.literal(true) }),
|
||||
"McpConnectorTokenRevokeEnvelope",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
"404": {
|
||||
description:
|
||||
"No `health:read` token with this id for this caller. An already-revoked token is still found, so a repeat revoke answers 200.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,275 @@
|
||||
/**
|
||||
* OpenAPI route table — notification channels: per-event preferences and
|
||||
* per-channel delivery health.
|
||||
*
|
||||
* Part of the OpenAPI route table; aggregated in `./index.ts`. The request
|
||||
* bodies come from `src/lib/validations/notifications.ts` so the wire contract
|
||||
* stays single-source; the response DTOs mirror the handlers under
|
||||
* `src/app/api/notifications/*`.
|
||||
*
|
||||
* The channel and event vocabularies are read from
|
||||
* `src/lib/notifications/types.ts` rather than restated, so a new channel type
|
||||
* or event category cannot be added to the dispatcher and quietly go missing
|
||||
* from the published contract.
|
||||
*/
|
||||
import { z } from "zod/v4";
|
||||
import type { ZodOpenApiObject } from "zod-openapi";
|
||||
|
||||
import { CHANNEL_TYPES, EVENT_TYPES } from "@/lib/notifications/types";
|
||||
import {
|
||||
notificationPreferenceSchema,
|
||||
reEnableChannelSchema,
|
||||
} from "@/lib/validations/notifications";
|
||||
import { dataEnvelope, errorEnvelope, stdResponses } from "./shared";
|
||||
|
||||
const channelTypeEnum = z
|
||||
.enum(CHANNEL_TYPES)
|
||||
.describe("Delivery transport for a notification channel.");
|
||||
|
||||
const eventTypeEnum = z
|
||||
.enum(EVENT_TYPES)
|
||||
.describe("Notification category a per-channel preference can toggle.");
|
||||
|
||||
const notificationChannel = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
type: channelTypeEnum,
|
||||
label: z
|
||||
.string()
|
||||
.describe(
|
||||
"Human-readable channel name. Falls back to the raw `type` when no label is registered.",
|
||||
),
|
||||
enabled: z.boolean().describe("The user's own per-channel toggle."),
|
||||
globallyEnabled: z
|
||||
.boolean()
|
||||
.describe(
|
||||
"The operator's instance-wide toggle for this transport. Only TELEGRAM, NTFY and WEB_PUSH have one; every other transport reports `true`. A channel the user has enabled still sends nothing while this is false.",
|
||||
),
|
||||
})
|
||||
.meta({
|
||||
id: "NotificationChannelSummary",
|
||||
description:
|
||||
"One of the caller's notification channels, with both the per-user and the instance-wide toggle so a client can explain why an enabled channel is silent.",
|
||||
});
|
||||
|
||||
const notificationPreference = z
|
||||
.object({
|
||||
channelId: z.string(),
|
||||
eventType: eventTypeEnum,
|
||||
enabled: z.boolean(),
|
||||
})
|
||||
.meta({
|
||||
id: "NotificationPreference",
|
||||
description:
|
||||
"An explicit per-(channel, event) override. Only STORED rows appear — an event with no row here follows the server-side default for that category, which is ON for most and OFF for the opt-in ones (personal records, mood and cycle reminders). Absence is therefore not 'disabled'.",
|
||||
});
|
||||
|
||||
const notificationPreferencesResponse = z
|
||||
.object({
|
||||
channels: z.array(notificationChannel),
|
||||
preferences: z.array(notificationPreference),
|
||||
eventTypes: z
|
||||
.array(z.string())
|
||||
.describe(
|
||||
"Every event category the server knows, in declaration order — the list a client renders rows for.",
|
||||
),
|
||||
})
|
||||
.meta({
|
||||
id: "NotificationPreferencesResponse",
|
||||
description:
|
||||
"The caller's notification channels, their stored per-event overrides, and the full event vocabulary.",
|
||||
});
|
||||
|
||||
const notificationPreferenceRequest = notificationPreferenceSchema.meta({
|
||||
id: "NotificationPreferenceRequest",
|
||||
description:
|
||||
"Set one per-(channel, event) override. `channelId` must belong to the caller — a channel id owned by somebody else answers 404, not 403. Upsert: the row is created when absent.",
|
||||
});
|
||||
|
||||
const channelDeliveryStatus = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
type: channelTypeEnum,
|
||||
label: z.string(),
|
||||
enabled: z.boolean(),
|
||||
state: z
|
||||
.enum(["active", "auto_disabled", "manually_disabled", "sending_paused"])
|
||||
.describe(
|
||||
"Server-derived. `auto_disabled` — the dispatcher turned it off after repeated hard rejects (`disabledReason` says why). `manually_disabled` — the user turned it off. `sending_paused` — still enabled but inside a retry cooldown until `nextRetryAt`. `active` — enabled and sending.",
|
||||
),
|
||||
disabledReason: z
|
||||
.string()
|
||||
.nullable()
|
||||
.describe(
|
||||
"Why the dispatcher auto-disabled the channel; null when it did not. This is the field that separates `auto_disabled` from `manually_disabled`.",
|
||||
),
|
||||
consecutiveFailures: z.number().int(),
|
||||
lastSuccessAt: z.iso.datetime({ offset: true }).nullable(),
|
||||
lastFailureAt: z.iso.datetime({ offset: true }).nullable(),
|
||||
lastFailureReason: z.string().nullable(),
|
||||
nextRetryAt: z.iso
|
||||
.datetime({ offset: true })
|
||||
.nullable()
|
||||
.describe("End of the current cooldown; null when not paused."),
|
||||
})
|
||||
.meta({
|
||||
id: "NotificationChannelDeliveryStatus",
|
||||
description:
|
||||
"Delivery health for one channel: the derived state plus the raw counters and timestamps behind it.",
|
||||
});
|
||||
|
||||
const eventDeliveryStatus = z
|
||||
.object({
|
||||
lastDeliveredAt: z.iso
|
||||
.datetime({ offset: true })
|
||||
.nullable()
|
||||
.describe("Null when this category has never been delivered."),
|
||||
})
|
||||
.meta({ id: "NotificationEventDeliveryStatus" });
|
||||
|
||||
const notificationStatusResponse = z
|
||||
.object({
|
||||
channels: z.array(channelDeliveryStatus),
|
||||
events: z
|
||||
.record(z.string(), eventDeliveryStatus)
|
||||
.describe(
|
||||
"Keyed by event category. EVERY known category is present, with `lastDeliveredAt: null` when no data exists, so a client can render an empty row without conditional plumbing. Only categories with their own dispatch ledger can ever report a non-null instant — today that is `MOOD_REMINDER` alone; every other category reports null regardless of what was actually delivered.",
|
||||
),
|
||||
})
|
||||
.meta({
|
||||
id: "NotificationStatusResponse",
|
||||
description:
|
||||
"Per-channel delivery health plus a per-category last-delivered map.",
|
||||
});
|
||||
|
||||
const reEnableChannelRequest = reEnableChannelSchema.meta({
|
||||
id: "ReEnableNotificationChannelRequest",
|
||||
description:
|
||||
"Clear the auto-disable on one of the caller's own channels. A channel id the caller does not own answers 404.",
|
||||
});
|
||||
|
||||
export const notificationChannelPaths: NonNullable<ZodOpenApiObject["paths"]> =
|
||||
{
|
||||
"/api/notifications/preferences": {
|
||||
get: {
|
||||
tags: ["Notifications"],
|
||||
summary: "Read the caller's notification channels and preferences",
|
||||
description:
|
||||
"Returns every channel the caller has, its stored per-event overrides, and the full event vocabulary. Not a pure read: a user whose Telegram config still lives only on the legacy `User` columns has it migrated into a channel row as a side effect of this call, and that migration failing is swallowed as a warning rather than surfaced. Auth via cookie or Bearer.",
|
||||
responses: {
|
||||
"200": {
|
||||
description: "Channels, stored overrides and event vocabulary.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
notificationPreferencesResponse,
|
||||
"GetNotificationPreferences",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
put: {
|
||||
tags: ["Notifications"],
|
||||
summary: "Set one per-channel notification preference",
|
||||
description:
|
||||
"Upserts a single (channel, event) override and echoes the stored row. One preference per call — there is no batch arm. Body capped at 64 KiB. Auth via cookie or Bearer.",
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: {
|
||||
"application/json": { schema: notificationPreferenceRequest },
|
||||
},
|
||||
},
|
||||
responses: {
|
||||
"200": {
|
||||
description: "The stored preference.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
notificationPreference,
|
||||
"PutNotificationPreferenceResponse",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
"404": {
|
||||
description: "No such channel for this caller.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
"413": {
|
||||
description: "Body exceeds 64 KiB.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
...stdResponses,
|
||||
"422": {
|
||||
description:
|
||||
"Body is not parseable JSON, or failed validation. Note that unlike the routes wrapped in `safeJson`, a malformed body here is 422 rather than 400, and no Content-Type check runs.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
"/api/notifications/status": {
|
||||
get: {
|
||||
tags: ["Notifications"],
|
||||
summary: "Read per-channel delivery health",
|
||||
description:
|
||||
"What the notification settings surface paints into its Active / Auto-disabled / Sending-paused badges, plus a per-category last-delivered map. Auth via cookie or Bearer.",
|
||||
responses: {
|
||||
"200": {
|
||||
description: "Delivery health per channel and per category.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
notificationStatusResponse,
|
||||
"GetNotificationStatus",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
post: {
|
||||
tags: ["Notifications"],
|
||||
summary: "Re-enable an auto-disabled channel",
|
||||
description:
|
||||
"Clears `disabledReason`, `consecutiveFailures` and `nextRetryAt`, sets `enabled` true, and audits the change. Accepted on any of the caller's channels, not only auto-disabled ones — re-enabling an already-active channel is a no-op that still answers 200. Follow up with a test send if the client wants confirmation the transport works again. Body capped at 64 KiB. Auth via cookie or Bearer.",
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: {
|
||||
"application/json": { schema: reEnableChannelRequest },
|
||||
},
|
||||
},
|
||||
responses: {
|
||||
"200": {
|
||||
description: "The channel was re-enabled.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
z.object({ ok: z.literal(true) }),
|
||||
"ReEnableNotificationChannelResponse",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
"404": {
|
||||
description: "No such channel for this caller.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
"413": {
|
||||
description: "Body exceeds 64 KiB.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
...stdResponses,
|
||||
"422": {
|
||||
description:
|
||||
"Body is not parseable JSON, or failed validation. As above, a malformed body here is 422 rather than 400.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -37,6 +37,7 @@ import {
|
||||
updatedAtTokenField,
|
||||
conflictResponse409,
|
||||
invalidBaseTokenResponse,
|
||||
deviceRevokeResponse,
|
||||
} from "./shared";
|
||||
|
||||
// v1.18.0 — module enable/disable. The PATCH request is the REAL runtime
|
||||
@@ -693,19 +694,6 @@ const devicePatchRequest = z
|
||||
"Per-device medication-reminder delivery override. `server` forces server-side dispatch to this device, `client` leaves it to the app's own local reminders, and `null` CLEARS the override so the device inherits the account default.",
|
||||
});
|
||||
|
||||
const deviceRevokeResponse = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
revoked: z.literal(true),
|
||||
refreshTokensRevoked: z.number().int(),
|
||||
accessTokensRevoked: z.number().int(),
|
||||
})
|
||||
.meta({
|
||||
id: "DeviceRevokeResponse",
|
||||
description:
|
||||
"What the revocation cascade actually removed. The counts are the point: a client can tell the person how many credentials were killed rather than saying only that something happened.",
|
||||
});
|
||||
|
||||
const labsLocalOcrPatchRequest = labsLocalOcrPatchSchema.meta({
|
||||
id: "LabsLocalOcrPatchRequest",
|
||||
description:
|
||||
@@ -1624,7 +1612,7 @@ export const profilePaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
deviceRevokeResponse,
|
||||
"DeviceRevokeEnvelope",
|
||||
"AccountDeviceRevokeEnvelope",
|
||||
),
|
||||
},
|
||||
},
|
||||
|
||||
@@ -0,0 +1,453 @@
|
||||
/**
|
||||
* OpenAPI route table — the managed record's own configuration.
|
||||
*
|
||||
* A Guardian acting on a managed record reads and writes that record's
|
||||
* settings here, never through `/api/auth/me`: the actor's identity payload
|
||||
* stays the actor's while the browser is pointed at somebody else's record, and
|
||||
* conflating the two is how a Guardian's own locale ends up written onto a
|
||||
* child's profile. Every response names the record it describes for the same
|
||||
* reason.
|
||||
*
|
||||
* These paths carry `recordRefusal()` rather than the local `sharingRefusal`
|
||||
* the grant-lifecycle module uses, and the difference is load-bearing: this is
|
||||
* the one tree in the application fenced by `requireGuardianAuth`, so
|
||||
* `src/__tests__/openapi-sharing-denial.test.ts` holds every operation here to
|
||||
* the byte-identical shared refusal sentence. Copying the neighbouring
|
||||
* module's wording into this one fails that guard.
|
||||
*
|
||||
* Part of the OpenAPI route table; aggregated in `./index.ts`. The PATCH
|
||||
* bodies come from `src/lib/record-settings/configuration.ts` — the same strict
|
||||
* objects the handler parses — so a published field the route would 422 cannot
|
||||
* drift into the contract.
|
||||
*/
|
||||
import type { ZodOpenApiObject } from "zod-openapi";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { METRIC_BOUNDS } from "@/lib/analytics/effective-range";
|
||||
import { MANAGED_RECORD_SETTINGS_PATCH_SCHEMAS } from "@/lib/record-settings";
|
||||
import {
|
||||
dataEnvelope,
|
||||
errorEnvelope,
|
||||
recordRefusal,
|
||||
stdResponses,
|
||||
} from "./shared";
|
||||
|
||||
const thresholdMetricEnum = z
|
||||
.enum(Object.keys(METRIC_BOUNDS) as [string, ...string[]])
|
||||
.describe("A metric that carries a user-overridable traffic-light range.");
|
||||
|
||||
const settingsFamilyEnum = z
|
||||
.enum([
|
||||
"profile",
|
||||
"modules",
|
||||
"notifications",
|
||||
"thresholds",
|
||||
"coach",
|
||||
"insights",
|
||||
])
|
||||
.describe(
|
||||
"The closed set of configuration families a Guardian may read and write on a managed record. Identity, credentials, delivery channels, Coach memories and provider connections are absent by construction — no family accepts them, so every future field fails closed until one deliberately does.",
|
||||
);
|
||||
|
||||
const recordSettingsResponse = z
|
||||
.object({
|
||||
record: z.object({
|
||||
id: z.string(),
|
||||
displayName: z
|
||||
.string()
|
||||
.describe("Empty string when the record has no display name set."),
|
||||
locale: z.string().nullable(),
|
||||
timezone: z.string(),
|
||||
kind: z
|
||||
.literal("managed")
|
||||
.describe(
|
||||
"Always `managed`. The endpoint exists only for managed records; there is no owner-record arm.",
|
||||
),
|
||||
}),
|
||||
})
|
||||
.meta({
|
||||
id: "RecordSettingsResponse",
|
||||
description:
|
||||
"The active managed record's configuration identity. Deliberately a distinct DTO rather than another actor field on `/api/auth/me`.",
|
||||
});
|
||||
|
||||
const recordSettingsIntegrationsResponse = z
|
||||
.object({
|
||||
recordId: z.string(),
|
||||
integrations: z
|
||||
.array(
|
||||
z.object({
|
||||
integration: z.enum([
|
||||
"withings",
|
||||
"whoop",
|
||||
"fitbit",
|
||||
"nightscout",
|
||||
"polar",
|
||||
"oura",
|
||||
"google-health",
|
||||
"strava",
|
||||
]),
|
||||
state: z.enum([
|
||||
"connected",
|
||||
"error_transient",
|
||||
"error_reauth",
|
||||
"disconnected",
|
||||
"parked",
|
||||
]),
|
||||
lastSuccessAt: z.iso.datetime({ offset: true }).nullable(),
|
||||
lastAttemptAt: z.iso.datetime({ offset: true }).nullable(),
|
||||
}),
|
||||
)
|
||||
.describe(
|
||||
"All eight providers, always, in the fixed order withings, whoop, fitbit, nightscout, polar, oura, google-health, strava. Note the order differs from the owner's own `/api/integrations/status` envelope.",
|
||||
),
|
||||
})
|
||||
.meta({
|
||||
id: "RecordSettingsIntegrationsResponse",
|
||||
description:
|
||||
"Whether the managed record's integrations are connected, and nothing else. Deliberately no control and no credential projection — OAuth and provider state cannot safely carry a record selector, so a Guardian can see that a pipe exists but cannot connect, disconnect, probe or resume it from here. A provider with no real credential reads `disconnected` even when its ledger row says otherwise, because a synthesised healthy ledger is not proof of a connection.",
|
||||
});
|
||||
|
||||
// ── The six family DTOs ──────────────────────────────────────────────
|
||||
|
||||
const profileSettings = z
|
||||
.object({
|
||||
displayName: z.string().nullable(),
|
||||
heightCm: z.number().nullable(),
|
||||
dateOfBirth: z.iso
|
||||
.date()
|
||||
.nullable()
|
||||
.describe("Calendar date (`YYYY-MM-DD`), not an instant."),
|
||||
gender: z.enum(["MALE", "FEMALE", "OTHER"]).nullable(),
|
||||
locale: z.enum(["de", "en", "es", "fr", "it", "pl"]).nullable(),
|
||||
timezone: z.string(),
|
||||
unitPreference: z.enum(["metric", "imperial"]),
|
||||
timeFormat: z.enum(["AUTO", "H12", "H24"]),
|
||||
dateFormat: z.enum(["AUTO", "DMY", "MDY", "YMD"]),
|
||||
})
|
||||
.meta({ id: "RecordProfileSettings" });
|
||||
|
||||
const moduleSettings = z
|
||||
.object({
|
||||
modulePreferences: z
|
||||
.record(z.string(), z.boolean())
|
||||
.describe(
|
||||
"Every directly-owned module key, always present, with the registry default filled in for keys the record has never persisted — so a Guardian administers the whole supported surface rather than only what happens to be stored.",
|
||||
),
|
||||
})
|
||||
.meta({ id: "RecordModuleSettings" });
|
||||
|
||||
const notificationSettings = z
|
||||
.object({
|
||||
moodReminderEnabled: z.boolean(),
|
||||
notificationPreferences: z.object({
|
||||
medication: z.object({
|
||||
lowStockRunwayDays: z.number().int().nullable(),
|
||||
reorderLeadDays: z.number().int(),
|
||||
}),
|
||||
mood: z.object({ reminderHour: z.number().int() }),
|
||||
}),
|
||||
})
|
||||
.meta({
|
||||
id: "RecordNotificationSettings",
|
||||
description:
|
||||
"Reminder timing and low-stock thresholds only. Delivery ownership is the actor's personal choice and is not here: a Guardian cannot route a managed record's notifications to their own phone or channel.",
|
||||
});
|
||||
|
||||
const trafficRange = z.object({
|
||||
greenMin: z.number(),
|
||||
greenMax: z.number(),
|
||||
orangeMin: z.number(),
|
||||
orangeMax: z.number(),
|
||||
});
|
||||
|
||||
const thresholdSettings = z
|
||||
.object({
|
||||
overrides: z
|
||||
.record(
|
||||
thresholdMetricEnum,
|
||||
z.object({ min: z.number(), max: z.number() }),
|
||||
)
|
||||
.describe(
|
||||
"Only the metrics the record has actually overridden. A metric absent here uses the computed default.",
|
||||
),
|
||||
effective: z
|
||||
.record(
|
||||
thresholdMetricEnum,
|
||||
z.object({
|
||||
range: trafficRange
|
||||
.nullable()
|
||||
.describe("Resolved range: the override if set, else the default."),
|
||||
isOverride: z.boolean(),
|
||||
default: trafficRange
|
||||
.nullable()
|
||||
.describe(
|
||||
"The unmodified computed default, so a client can show the diff. Null when no default can be computed — a weight range needs a height, an age-banded range needs a date of birth.",
|
||||
),
|
||||
bounds: z.object({
|
||||
min: z.number(),
|
||||
max: z.number(),
|
||||
unit: z.string(),
|
||||
}),
|
||||
}),
|
||||
)
|
||||
.describe(
|
||||
"Every threshold metric, always, whether overridden or not — this is the resolved view a client renders without recomputing anything.",
|
||||
),
|
||||
})
|
||||
.meta({ id: "RecordThresholdSettings" });
|
||||
|
||||
const coachSettings = z
|
||||
.object({
|
||||
disableCoach: z.boolean(),
|
||||
preferences: z.object({
|
||||
tone: z.string(),
|
||||
verbosity: z.string(),
|
||||
excludeMetrics: z.array(z.string()),
|
||||
defaultWindow: z.string(),
|
||||
dataClusters: z
|
||||
.array(z.string())
|
||||
.optional()
|
||||
.describe("Absent when the record has never set it."),
|
||||
}),
|
||||
})
|
||||
.meta({
|
||||
id: "RecordCoachSettings",
|
||||
description:
|
||||
"The Coach kill switch and the prompt-tuning subset a Guardian may set. A write to `preferences` also mirrors `excludeMetrics` onto the record's insights exclusion list, so the two cannot drift apart.",
|
||||
});
|
||||
|
||||
const insightsSettings = z
|
||||
.object({
|
||||
layout: z.object({
|
||||
version: z.number().int(),
|
||||
sections: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
visible: z.boolean(),
|
||||
order: z.number().int(),
|
||||
}),
|
||||
),
|
||||
tiles: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
visible: z.boolean(),
|
||||
order: z.number().int(),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
})
|
||||
.meta({
|
||||
id: "RecordInsightsSettings",
|
||||
description:
|
||||
"The resolved insights layout. Unknown and legacy tile ids are normalised or dropped on read, and a newly-shipped tile is merged in default-visible, so the response is always the full current tile set rather than whatever was last persisted.",
|
||||
});
|
||||
|
||||
const recordSettingsFamilyResponse = z
|
||||
.object({
|
||||
recordId: z.string(),
|
||||
family: settingsFamilyEnum,
|
||||
settings: z
|
||||
.union([
|
||||
profileSettings,
|
||||
moduleSettings,
|
||||
notificationSettings,
|
||||
thresholdSettings,
|
||||
coachSettings,
|
||||
insightsSettings,
|
||||
])
|
||||
.describe(
|
||||
"The DTO for the family in the path. Which variant arrives is determined entirely by `{family}`, so branch on `family` rather than probing the shape — OpenAPI cannot express the dependency between a path parameter and a response variant.",
|
||||
),
|
||||
})
|
||||
.meta({
|
||||
id: "RecordSettingsFamilyResponse",
|
||||
description:
|
||||
"One family's settings for one managed record. Both the GET and the PATCH answer this same shape; the PATCH echo is the post-write state.",
|
||||
});
|
||||
|
||||
const recordSettingsPatchRequest = z
|
||||
.union([
|
||||
MANAGED_RECORD_SETTINGS_PATCH_SCHEMAS.profile.meta({
|
||||
id: "RecordProfileSettingsPatch",
|
||||
description:
|
||||
"Partial profile edit. Every key is optional and an omitted key is untouched; a `null` on a nullable field clears it. Strict — an unknown key is a 422, which is what keeps the allowlist an allowlist.",
|
||||
}),
|
||||
MANAGED_RECORD_SETTINGS_PATCH_SCHEMAS.modules.meta({
|
||||
id: "RecordModuleSettingsPatch",
|
||||
description:
|
||||
"Partial module toggle. Merged onto the record's current preferences; omitted keys keep their value.",
|
||||
}),
|
||||
MANAGED_RECORD_SETTINGS_PATCH_SCHEMAS.notifications.meta({
|
||||
id: "RecordNotificationSettingsPatch",
|
||||
description:
|
||||
"Reminder timing and low-stock thresholds. No delivery-channel field exists here by design.",
|
||||
}),
|
||||
MANAGED_RECORD_SETTINGS_PATCH_SCHEMAS.thresholds.meta({
|
||||
id: "RecordThresholdSettingsPatch",
|
||||
description:
|
||||
"Per-metric range overrides, merged onto the stored set. Each range must sit inside the metric's physiological bounds with `min` strictly below `max`. There is no clear arm: sending a metric replaces its override, and omitting it keeps the stored one.",
|
||||
}),
|
||||
MANAGED_RECORD_SETTINGS_PATCH_SCHEMAS.coach.meta({
|
||||
id: "RecordCoachSettingsPatch",
|
||||
description:
|
||||
"The Coach kill switch and the prompt-tuning subset. `preferences` is merged onto the stored preferences, not replaced wholesale.",
|
||||
}),
|
||||
MANAGED_RECORD_SETTINGS_PATCH_SCHEMAS.insights.meta({
|
||||
id: "RecordInsightsSettingsPatch",
|
||||
description:
|
||||
"The full insights layout. Unlike the other five families this one is a replacement rather than a merge.",
|
||||
}),
|
||||
])
|
||||
.meta({
|
||||
id: "RecordSettingsPatchRequest",
|
||||
description:
|
||||
"The body for the family named in the path. Only that family's variant is accepted — sending the profile body to `/thresholds` is a 422, because every variant is strict. OpenAPI cannot tie the variant to the path parameter, so the union is the honest publication of six separate contracts sharing one URL shape.",
|
||||
});
|
||||
|
||||
const familyParameter = {
|
||||
name: "family",
|
||||
in: "path" as const,
|
||||
required: true,
|
||||
schema: {
|
||||
type: "string" as const,
|
||||
enum: [
|
||||
"profile",
|
||||
"modules",
|
||||
"notifications",
|
||||
"thresholds",
|
||||
"coach",
|
||||
"insights",
|
||||
],
|
||||
},
|
||||
description:
|
||||
"Which configuration family to read or write. An unrecognised value is a 404 — and note that the family check runs BEFORE authentication, so an unknown family answers 404 to an unauthenticated caller where a known one would answer 401.",
|
||||
};
|
||||
|
||||
export const recordSettingsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
"/api/record-settings": {
|
||||
get: {
|
||||
tags: ["Account sharing"],
|
||||
summary: "Read the active managed record's identity",
|
||||
description:
|
||||
"The record the session is currently acting on, named explicitly. This is not `/api/auth/me` with a different scope: that endpoint keeps reporting the actor throughout, and this one reports the record, so a client rendering a managed surface has an unambiguous source for each. Cookie session or Bearer, but only while acting on a managed record the caller guards.",
|
||||
responses: {
|
||||
...recordRefusal(),
|
||||
"200": {
|
||||
description: "The active managed record.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
recordSettingsResponse,
|
||||
"RecordSettingsEnvelope",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
},
|
||||
"/api/record-settings/integrations": {
|
||||
get: {
|
||||
tags: ["Account sharing"],
|
||||
summary: "Read the managed record's integration connection states",
|
||||
description:
|
||||
"Disclosure only: whether each of the record's integrations is connected and when it last succeeded. There is deliberately no control arm and no credential projection anywhere under this path — a Guardian cannot connect, disconnect, probe or resume a managed record's provider, because an OAuth flow cannot safely carry a record selector. Cookie session or Bearer, while acting on a managed record the caller guards.",
|
||||
responses: {
|
||||
...recordRefusal(),
|
||||
"200": {
|
||||
description: "Connection state per provider.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
recordSettingsIntegrationsResponse,
|
||||
"RecordSettingsIntegrationsEnvelope",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
},
|
||||
"/api/record-settings/{family}": {
|
||||
get: {
|
||||
tags: ["Account sharing"],
|
||||
summary: "Read one configuration family of the managed record",
|
||||
description:
|
||||
"Returns the named family's resolved settings for the record the session is acting on. Cookie session or Bearer, while acting on a managed record the caller guards.",
|
||||
parameters: [familyParameter],
|
||||
responses: {
|
||||
...recordRefusal(),
|
||||
"200": {
|
||||
description: "The family's settings.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
recordSettingsFamilyResponse,
|
||||
"GetRecordSettingsFamilyEnvelope",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
"404": {
|
||||
description:
|
||||
"Either the path named a family outside the closed set, or the record row itself is gone. The two are not distinguished, and the first is answered before the caller is authenticated at all.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
patch: {
|
||||
tags: ["Account sharing"],
|
||||
summary: "Update one configuration family of the managed record",
|
||||
description:
|
||||
"Applies the family's patch and echoes the post-write state, so a client never needs a follow-up read. Five of the six families MERGE — an omitted key keeps its stored value; `insights` replaces the layout instead. The write is audited against the record with the acting Guardian recorded as the actor, and the changed key names ride the audit row. Body capped at 64 KiB. Cookie session or Bearer, while acting on a managed record the caller guards.",
|
||||
parameters: [familyParameter],
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: {
|
||||
"application/json": { schema: recordSettingsPatchRequest },
|
||||
},
|
||||
},
|
||||
responses: {
|
||||
...recordRefusal(),
|
||||
"200": {
|
||||
description: "The family's settings after the write.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
recordSettingsFamilyResponse,
|
||||
"PatchRecordSettingsFamilyEnvelope",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
"400": {
|
||||
description: "Body is not parseable JSON.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
"404": {
|
||||
description:
|
||||
"The path named a family outside the closed set. Answered before authentication.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
"413": {
|
||||
description: "Body exceeds 64 KiB.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
"415": {
|
||||
description: "Content-Type is not `application/json`.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
...stdResponses,
|
||||
"422": {
|
||||
description:
|
||||
"Validation failed against the family's strict schema, with every offending issue in the envelope rather than only the first. An unknown key lands here rather than being ignored — that is what makes the field allowlist enforceable.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -11,7 +11,10 @@ import type { ZodOpenApiObject } from "zod-openapi";
|
||||
import {
|
||||
emailSettingsSchema,
|
||||
notificationChannelEnabledSchema,
|
||||
ntfySettingsSchema,
|
||||
webhookSettingsSchema,
|
||||
} from "@/lib/validations/notifications";
|
||||
import { telegramSettingsSchema } from "@/lib/validations/telegram";
|
||||
import {
|
||||
dataEnvelope,
|
||||
errorEnvelope,
|
||||
@@ -208,7 +211,304 @@ const dataWipeResponse = z
|
||||
})
|
||||
.meta({ id: "DataWipeResponse" });
|
||||
|
||||
// ── Per-channel notification config ──────────────────────────────────
|
||||
// Three credential-bearing channels the Settings page and the iOS client both
|
||||
// write. Every GET here reports the SECRET AS A BOOLEAN and never the value:
|
||||
// `hasAuthToken` (ntfy), `hasBotToken` (Telegram), `hasHeaderValue` (webhook).
|
||||
// The PUT side is what that costs: because a client cannot read the secret back,
|
||||
// an empty value on the way in means "keep what is stored", never "clear it".
|
||||
|
||||
const jsonBodyRefusals = {
|
||||
"400": {
|
||||
description: "Body is not parseable JSON.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
"413": {
|
||||
description: "Body exceeds 64 KiB.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
"415": {
|
||||
description: "Content-Type is not `application/json`.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
};
|
||||
|
||||
const channelEnabledOnlyRequest = notificationChannelEnabledSchema.meta({
|
||||
id: "NotificationChannelEnabledRequest",
|
||||
description:
|
||||
"The toggle-only arm of a channel PUT: exactly `{ enabled }` and nothing else. Any additional key falls through to the channel's full config body instead. Enabling a channel whose stored config is incomplete fails with 422.",
|
||||
});
|
||||
|
||||
const ntfySettingsRequest = ntfySettingsSchema.meta({
|
||||
id: "NtfySettingsRequest",
|
||||
description:
|
||||
"ntfy channel config. `serverUrl` must pass the SSRF floor — a URL resolving into a private range is refused at input time. An EMPTY OR OMITTED `authToken` preserves the stored one rather than clearing it: the GET never returns the secret, so a client round-tripping the form would otherwise wipe it on every unrelated save. Sending a non-empty value replaces it. There is no way to clear a stored auth token through this endpoint.",
|
||||
});
|
||||
|
||||
const telegramSettingsRequest = telegramSettingsSchema.meta({
|
||||
id: "TelegramSettingsRequest",
|
||||
description:
|
||||
"Telegram channel config. Both credential fields are optional and behave by key PRESENCE, not by value: omit `botToken` to keep the stored one, send an empty string to clear it. Same for `chatId`. Enabling the channel registers the Telegram webhook against `APP_URL` as part of the write, so a deployment whose `APP_URL` is not a public HTTPS host on port 80/88/443/8443 cannot enable Telegram at all.",
|
||||
});
|
||||
|
||||
const webhookSettingsRequest = webhookSettingsSchema.meta({
|
||||
id: "WebhookSettingsRequest",
|
||||
description:
|
||||
"Generic-webhook channel config — one channel covering Gotify, Discord, Slack, a Matrix bridge, Home Assistant, or any relay accepting an inbound JSON POST. `url` must pass the SSRF floor at input time and is re-checked at dispatch time. An EMPTY OR OMITTED `headerValue` preserves the stored one, for the same reason as ntfy's `authToken`: the GET never returns it. There is no way to clear a stored header value through this endpoint.",
|
||||
});
|
||||
|
||||
/**
|
||||
* The two shapes every channel PUT accepts, as one `anyOf`.
|
||||
*
|
||||
* The handler tries the strict `{ enabled }` object first and falls through to
|
||||
* the full config schema, so the wire genuinely admits either. Publishing only
|
||||
* the full schema would tell a client it has to resend the whole config to flip
|
||||
* a toggle — exactly the round-trip the preserve-on-empty rule exists to
|
||||
* survive, and exactly the round-trip that used to wipe the stored secret.
|
||||
*/
|
||||
const ntfyPutRequest = z
|
||||
.union([channelEnabledOnlyRequest, ntfySettingsRequest])
|
||||
.meta({
|
||||
id: "NtfySettingsPutRequest",
|
||||
description:
|
||||
"Either the toggle-only body or the full ntfy config. The toggle arm is tried first and matches only an object with `enabled` and no other key.",
|
||||
});
|
||||
|
||||
const telegramPutRequest = z
|
||||
.union([channelEnabledOnlyRequest, telegramSettingsRequest])
|
||||
.meta({
|
||||
id: "TelegramSettingsPutRequest",
|
||||
description:
|
||||
"Either the toggle-only body or the full Telegram config. The toggle arm is tried first and matches only an object with `enabled` and no other key.",
|
||||
});
|
||||
|
||||
const webhookPutRequest = z
|
||||
.union([channelEnabledOnlyRequest, webhookSettingsRequest])
|
||||
.meta({
|
||||
id: "WebhookSettingsPutRequest",
|
||||
description:
|
||||
"Either the toggle-only body or the full webhook config. The toggle arm is tried first and matches only an object with `enabled` and no other key.",
|
||||
});
|
||||
|
||||
const ntfySettingsResponse = z
|
||||
.object({
|
||||
enabled: z.boolean(),
|
||||
serverUrl: z
|
||||
.string()
|
||||
.describe("Defaults to `https://ntfy.sh` when no channel row exists."),
|
||||
topic: z.string().describe("Empty string when unset."),
|
||||
hasAuthToken: z
|
||||
.boolean()
|
||||
.describe(
|
||||
"Whether an auth token is stored. The token itself is never returned.",
|
||||
),
|
||||
})
|
||||
.meta({
|
||||
id: "NtfySettingsResponse",
|
||||
description:
|
||||
"Stored ntfy channel config, with the auth token reduced to a presence flag.",
|
||||
});
|
||||
|
||||
const telegramSettingsResponse = z
|
||||
.object({
|
||||
enabled: z.boolean(),
|
||||
hasBotToken: z
|
||||
.boolean()
|
||||
.describe(
|
||||
"Whether a bot token is stored. The token itself is never returned.",
|
||||
),
|
||||
chatId: z
|
||||
.string()
|
||||
.nullable()
|
||||
.describe(
|
||||
"The stored chat id, returned in full. It is an addressing value, not a credential — the bot token is what authorises a send.",
|
||||
),
|
||||
})
|
||||
.meta({
|
||||
id: "TelegramSettingsResponse",
|
||||
description:
|
||||
"Stored Telegram channel config, with the bot token reduced to a presence flag.",
|
||||
});
|
||||
|
||||
const webhookSettingsResponse = z
|
||||
.object({
|
||||
enabled: z.boolean(),
|
||||
url: z.string().describe("Empty string when no channel row exists."),
|
||||
headerName: z
|
||||
.string()
|
||||
.describe("Empty string when unset. The header NAME is not a secret."),
|
||||
hasHeaderValue: z
|
||||
.boolean()
|
||||
.describe(
|
||||
"Whether a header value (the shared secret) is stored. The value itself is never returned.",
|
||||
),
|
||||
})
|
||||
.meta({
|
||||
id: "WebhookSettingsResponse",
|
||||
description:
|
||||
"Stored generic-webhook channel config, with the secret header value reduced to a presence flag.",
|
||||
});
|
||||
|
||||
const channelSaved = z.object({ saved: z.literal(true) });
|
||||
const channelUpdated = z.object({ updated: z.literal(true) });
|
||||
|
||||
export const settingsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
"/api/settings/ntfy": {
|
||||
get: {
|
||||
tags: ["Notifications"],
|
||||
summary: "Read the caller's ntfy channel config",
|
||||
description:
|
||||
'Returns the stored server URL, topic and enabled flag. The auth token is reported as `hasAuthToken` only. When the user has no ntfy channel row the defaults `{ enabled: false, serverUrl: "https://ntfy.sh", topic: "", hasAuthToken: false }` are returned rather than a 404. Auth via cookie or Bearer.',
|
||||
responses: {
|
||||
"200": {
|
||||
description: "Stored (or default) ntfy config.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(ntfySettingsResponse, "GetNtfySettings"),
|
||||
},
|
||||
},
|
||||
},
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
put: {
|
||||
tags: ["Notifications"],
|
||||
summary: "Update the caller's ntfy channel config",
|
||||
description:
|
||||
"Upserts the channel. Accepts either the toggle-only body or the full config. The response is `{ saved: true }` and carries no config echo, so re-read the GET if the client needs the resolved state. Auth via cookie or Bearer.",
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: { "application/json": { schema: ntfyPutRequest } },
|
||||
},
|
||||
responses: {
|
||||
"200": {
|
||||
description: "Config stored.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(channelSaved, "PutNtfySettingsResponse"),
|
||||
},
|
||||
},
|
||||
},
|
||||
...jsonBodyRefusals,
|
||||
...stdResponses,
|
||||
"422": {
|
||||
description:
|
||||
"Body matched neither accepted shape, or `enabled` is true while the stored config has no server URL and topic.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
"/api/settings/telegram": {
|
||||
get: {
|
||||
tags: ["Notifications"],
|
||||
summary: "Read the caller's Telegram channel config",
|
||||
description:
|
||||
"Returns the enabled flag, the chat id and `hasBotToken`. The bot token is never returned. Auth via cookie or Bearer.",
|
||||
responses: {
|
||||
"200": {
|
||||
description: "Stored Telegram config.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
telegramSettingsResponse,
|
||||
"GetTelegramSettings",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
put: {
|
||||
tags: ["Notifications"],
|
||||
summary: "Update the caller's Telegram channel config",
|
||||
description:
|
||||
"Accepts either the toggle-only body or the full config, then registers (on enable) or deletes (on disable) the Telegram webhook for the bot before persisting. Webhook deletion is best-effort and its failure does not fail the write; webhook REGISTRATION is not — a rejected registration aborts the whole call and nothing is stored. The response is `{ updated: true }` with no config echo. Auth via cookie or Bearer.",
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: { "application/json": { schema: telegramPutRequest } },
|
||||
},
|
||||
responses: {
|
||||
"200": {
|
||||
description: "Config stored.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
channelUpdated,
|
||||
"PutTelegramSettingsResponse",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
"404": {
|
||||
description: "The session's user row no longer exists.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
...jsonBodyRefusals,
|
||||
"500": {
|
||||
description:
|
||||
"The deployment cannot register a Telegram webhook because `APP_URL` (or `NEXT_PUBLIC_APP_URL`) is missing or unparseable. An operator configuration problem, not a client one — retrying will not help.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
...stdResponses,
|
||||
"422": {
|
||||
description:
|
||||
"Body matched neither accepted shape; or `enabled` is true without both a bot token and a chat id; or the deployment's `APP_URL` is not a public HTTPS host on port 80/88/443/8443; or Telegram refused the webhook registration.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
"/api/settings/webhook": {
|
||||
get: {
|
||||
tags: ["Notifications"],
|
||||
summary: "Read the caller's generic-webhook channel config",
|
||||
description:
|
||||
'Returns the stored URL, header name and enabled flag. The secret header value is reported as `hasHeaderValue` only. When the user has no webhook channel row the defaults `{ enabled: false, url: "", headerName: "", hasHeaderValue: false }` are returned rather than a 404. Auth via cookie or Bearer.',
|
||||
responses: {
|
||||
"200": {
|
||||
description: "Stored (or default) webhook config.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
webhookSettingsResponse,
|
||||
"GetWebhookSettings",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
put: {
|
||||
tags: ["Notifications"],
|
||||
summary: "Update the caller's generic-webhook channel config",
|
||||
description:
|
||||
"Upserts the channel. Accepts either the toggle-only body or the full config. The response is `{ saved: true }` and carries no config echo. Auth via cookie or Bearer.",
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: { "application/json": { schema: webhookPutRequest } },
|
||||
},
|
||||
responses: {
|
||||
"200": {
|
||||
description: "Config stored.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(channelSaved, "PutWebhookSettingsResponse"),
|
||||
},
|
||||
},
|
||||
},
|
||||
...jsonBodyRefusals,
|
||||
...stdResponses,
|
||||
"422": {
|
||||
description:
|
||||
"Body matched neither accepted shape, or `enabled` is true while no webhook URL is stored.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
"/api/settings/reminder-thresholds": {
|
||||
get: {
|
||||
tags: ["Notifications"],
|
||||
|
||||
@@ -363,3 +363,36 @@ export const moduleDisabledResponse = {
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* What a device revocation actually removed.
|
||||
*
|
||||
* Two paths answer with this exact shape, because two routes are two doors onto
|
||||
* one `revokeDeviceCascade` call: `DELETE /api/devices/{id}` and
|
||||
* `DELETE /api/auth/me/devices/{id}`. They were documented independently and
|
||||
* each minted a component called `DeviceRevokeResponse`, which the emitter
|
||||
* refuses outright — one id cannot name two schemas. It lives here rather than
|
||||
* in either module so neither owns it and the next door onto the same call
|
||||
* finds it.
|
||||
*
|
||||
* The counts are the point. A client can tell the person how many credentials
|
||||
* were killed rather than only that something happened.
|
||||
*/
|
||||
export const deviceRevokeResponse = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
revoked: z.literal(true),
|
||||
refreshTokensRevoked: z
|
||||
.number()
|
||||
.int()
|
||||
.describe("Refresh tokens the cascade revoked."),
|
||||
accessTokensRevoked: z
|
||||
.number()
|
||||
.int()
|
||||
.describe("Access tokens the cascade revoked."),
|
||||
})
|
||||
.meta({
|
||||
id: "DeviceRevokeResponse",
|
||||
description:
|
||||
"What the revocation cascade actually removed. The counts let a client say how many credentials were killed rather than only that something happened.",
|
||||
});
|
||||
@@ -129,7 +129,13 @@ const managedCoachPreferencesSchema = coachPrefsSchema
|
||||
})
|
||||
.strict();
|
||||
|
||||
const MANAGED_RECORD_SETTINGS_PATCH_SCHEMAS = {
|
||||
/**
|
||||
* One strict patch schema per family. Exported so the OpenAPI registry can
|
||||
* publish the same objects the handler parses rather than a restatement of
|
||||
* them — every family is `strict()`, so a published paraphrase that drifted
|
||||
* would promise a field the route answers 422 for.
|
||||
*/
|
||||
export const MANAGED_RECORD_SETTINGS_PATCH_SCHEMAS = {
|
||||
profile: profilePatchSchema,
|
||||
modules: z.object({ modulePreferences: modulePrefsPatchSchema }).strict(),
|
||||
notifications: z
|
||||
|
||||
@@ -18,6 +18,7 @@ export {
|
||||
managedModulePreferencesFrom,
|
||||
MANAGED_RECORD_SETTINGS_FIELD_ALLOWLIST,
|
||||
MANAGED_RECORD_SETTINGS_MODULE_DEFAULTS,
|
||||
MANAGED_RECORD_SETTINGS_PATCH_SCHEMAS,
|
||||
parseManagedRecordSettingsPatch,
|
||||
safeParseManagedRecordSettingsPatch,
|
||||
type ManagedRecordSettingsFamily,
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { z } from "zod/v4";
|
||||
|
||||
/**
|
||||
* Per-user Google Health BYO-key credentials. Each self-hoster registers their
|
||||
* own Google Cloud OAuth client (the Restricted-scope brand verification + CASA
|
||||
* assessment is per-OAuth-client, so a single shared app is unworkable for a
|
||||
* multi-operator product) and pastes the client id/secret into Settings. Stored
|
||||
* encrypted on `User`.
|
||||
*/
|
||||
export const googleHealthCredentialsSchema = z.object({
|
||||
clientId: z.string().min(1).max(200),
|
||||
clientSecret: z.string().min(1).max(200),
|
||||
});
|
||||
|
||||
export type GoogleHealthCredentialsInput = z.infer<
|
||||
typeof googleHealthCredentialsSchema
|
||||
>;
|
||||
@@ -0,0 +1,18 @@
|
||||
import { z } from "zod/v4";
|
||||
|
||||
/**
|
||||
* Body of `POST /api/mcp/tokens` — mint a connector Bearer for the manual /
|
||||
* stdio path.
|
||||
*
|
||||
* `scope` is a closed two-value choice, not a permission list: `read` maps to
|
||||
* `["health:read"]` and `read_write` adds `health:write`. The route builds the
|
||||
* `permissions` array from that choice field by field, so no request shape can
|
||||
* coerce this endpoint into minting a wildcard or any other grant.
|
||||
*/
|
||||
export const createMcpTokenSchema = z.object({
|
||||
name: z.string().min(1, "Name required").max(100),
|
||||
expiresInDays: z.number().int().min(1).max(365).optional(),
|
||||
scope: z.enum(["read", "read_write"]).optional().default("read"),
|
||||
});
|
||||
|
||||
export type CreateMcpTokenInput = z.infer<typeof createMcpTokenSchema>;
|
||||
@@ -12,6 +12,15 @@ export const notificationChannelEnabledSchema = z.strictObject({
|
||||
enabled: z.boolean(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Body of `POST /api/notifications/status` — clear the auto-disable on one of
|
||||
* the caller's own channels. The channel is looked up scoped to the session
|
||||
* user, so an id alone cannot re-enable somebody else's channel.
|
||||
*/
|
||||
export const reEnableChannelSchema = z.object({
|
||||
channelId: z.string().min(1).max(64),
|
||||
});
|
||||
|
||||
/**
|
||||
* Parse a dotted-quad IPv4 string into normalized octets.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { z } from "zod/v4";
|
||||
|
||||
/**
|
||||
* The optional flag-only body every manual provider-sync trigger accepts.
|
||||
*
|
||||
* Deliberately NOT `strict()`. An unknown key has always been ignored here and
|
||||
* tightening that would refuse callers this change is not aiming at — the point
|
||||
* is that a key the server DOES read must not be misread, not that the body
|
||||
* becomes a closed shape.
|
||||
*/
|
||||
export const syncTriggerSchema = z.object({
|
||||
fullSync: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export type SyncTriggerInput = z.infer<typeof syncTriggerSchema>;
|
||||
Reference in new issue
Block a user