feat(modules): add operator-level server-wide module availability

Second layer of the module enable/disable model: an operator can turn a
module off for the whole server, and an operator-disabled module is off
for every account regardless of personal preference — mirroring the
coach master flag above the per-user opt-out.

Storage is a DISABLED allowlist on AppSettings.moduleAvailabilityJson
(absent/empty/true = available, explicit false = disabled), resolved by
getOperatorModuleAvailability(). The gate now resolves every toggleable
module as operatorAvailable(key) AND userEnabled(key); cycle and coach
keep their existing delegation but are still AND-ed with operator
availability. Core domains are never disableable.

GET/PATCH /api/admin/settings/module-availability is cookie-only
(requireAdmin); a strict per-module-key schema rejects core domains and
unknown keys at the boundary.
This commit is contained in:
Marc-André Bombeck committed 2026-06-15 22:44:35 +02:00
1 parent 3cae7beda8
commit 5d55347dd0
7 files changed
+667 -30

No files matched your search

@@ -0,0 +1,133 @@
/**
* v1.18.0 — `GET` / `PATCH /api/admin/settings/module-availability` —
* operator-side surface for the server-wide module availability matrix.
*
* The SECOND layer of the two-layer module model. A module the operator
* turns off here is off for EVERY account regardless of that account's
* personal preference — mirroring the coach master flag
* (`assistant_coach_enabled`) sitting above the per-user
* `User.disableCoach`. The gate (`src/lib/modules/gate.ts`) AND-s this
* operator availability with the per-user opt-out, and `GET /api/auth/me`
* already projects the resolved (operator AND user) map, so web + iOS need
* no extra logic.
*
* Dedicated endpoint (separate from the generic `/api/admin/settings`)
* so the admin panel can wire an optimistic matrix against a focused
* request/response shape and the audit trail carries a single
* `admin.settings.module-availability.update` action.
*
* Request shape — a partial DISABLED-allowlist patch keyed by toggleable
* module key; every field optional; `true` ⇒ available, `false` ⇒ disabled
* server-wide:
*
* { "mood": false, "glucose": true }
*
* Core domains (weight, BP, pulse, medications) are NOT module keys; the
* `.strict()` schema rejects them, so the measurement engine + meds can
* never be disabled through this route.
*
* `requireAdmin()` gates the route — cookie-only by construction; a Bearer
* token (even `["*"]` scope) cannot reach it.
*/
import type { NextRequest } from "next/server";
import { z } from "zod/v4";
import { apiHandler, requireAdmin } from "@/lib/api-handler";
import {
apiSuccess,
apiError,
getClientIp,
returnAllZodIssues,
safeJson,
} from "@/lib/api-response";
import { auditLog } from "@/lib/auth/audit";
import { prisma } from "@/lib/db";
import { annotate } from "@/lib/logging/context";
import {
mergeAvailabilityPatch,
resolveOperatorAvailability,
} from "@/lib/modules/operator-availability";
import { MODULE_KEYS } from "@/lib/modules/registry";
export const dynamic = "force-dynamic";
/**
* Strict per-module boolean patch. Building the shape from `MODULE_KEYS`
* keeps the schema exhaustive and rejects any non-module key (including
* the four core domains) at the validation boundary.
*/
const moduleAvailabilitySchema = z
.object(
Object.fromEntries(
MODULE_KEYS.map((key) => [key, z.boolean().optional()]),
) as Record<(typeof MODULE_KEYS)[number], z.ZodOptional<z.ZodBoolean>>,
)
.strict();
export const GET = apiHandler(async () => {
await requireAdmin();
annotate({ action: { name: "admin.settings.module-availability.get" } });
const settings = await prisma.appSettings.findUnique({
where: { id: "singleton" },
select: { moduleAvailabilityJson: true },
});
return apiSuccess({
availability: resolveOperatorAvailability(settings?.moduleAvailabilityJson),
});
});
export const PATCH = apiHandler(async (request: NextRequest) => {
const { user } = await requireAdmin();
annotate({ action: { name: "admin.settings.module-availability.update" } });
const { data: body, error: jsonError } = await safeJson(request, {
maxBytes: 64 * 1024,
});
if (jsonError) return jsonError;
const parsed = moduleAvailabilitySchema.safeParse(body);
if (!parsed.success) {
return returnAllZodIssues(parsed.error, 422);
}
const patch: Record<string, boolean> = {};
for (const [key, value] of Object.entries(parsed.data)) {
if (typeof value === "boolean") {
patch[key] = value;
}
}
if (Object.keys(patch).length === 0) {
return apiError("No valid fields", 422);
}
// Merge onto the existing blob so a partial PATCH leaves untouched keys
// intact; the merge drops any non-module key defensively.
const existing = await prisma.appSettings.findUnique({
where: { id: "singleton" },
select: { moduleAvailabilityJson: true },
});
const merged = mergeAvailabilityPatch(
existing?.moduleAvailabilityJson,
patch,
);
const settings = await prisma.appSettings.upsert({
where: { id: "singleton" },
update: { moduleAvailabilityJson: merged },
create: { id: "singleton", moduleAvailabilityJson: merged },
select: { moduleAvailabilityJson: true },
});
await auditLog("admin.settings.module-availability.update", {
userId: user.id,
ipAddress: getClientIp(request),
details: patch,
});
return apiSuccess({
availability: resolveOperatorAvailability(settings.moduleAvailabilityJson),
});
});