mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-15 15:02:04 +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
@@ -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.",
|
||||
});
|
||||
Reference in new issue
Block a user