mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 23:33:29 +00:00
Merge fix/settings-that-do-nothing
# Conflicts: # CHANGELOG.md
This commit is contained in:
commit
5cac883c17
17 files changed
+1188
-26
No files matched your search
@@ -482,3 +482,134 @@ describe("PUT /api/admin/settings", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* The five assistant flags were accepted by `adminSettingsSchema` and then
|
||||
* dropped on the floor: sending one alone answered 422 ("No valid fields"),
|
||||
* sending it alongside a real field answered 200 and stored nothing. The
|
||||
* schema comment promised the opposite, so the route was brought up to the
|
||||
* contract rather than the contract down to the route.
|
||||
*/
|
||||
describe("PUT /api/admin/settings — assistant flags", () => {
|
||||
const STORED = {
|
||||
registrationEnabled: true,
|
||||
mfaRequired: false,
|
||||
defaultLocale: "de",
|
||||
telegramGlobal: true,
|
||||
ntfyGlobal: true,
|
||||
webPushGlobal: true,
|
||||
webPushVapidPublicKey: null,
|
||||
webPushVapidPrivateKeyEncrypted: null,
|
||||
webPushVapidSubject: null,
|
||||
apiGlobal: true,
|
||||
umamiEnabled: false,
|
||||
umamiScriptUrl: null,
|
||||
umamiWebsiteId: null,
|
||||
glitchtipEnabled: false,
|
||||
glitchtipDsn: null,
|
||||
glitchtipEnvironment: null,
|
||||
reminderLateMinutes: 120,
|
||||
reminderMissedMinutes: 240,
|
||||
documentMaxFileBytes: 26_214_400,
|
||||
documentQuotaBytes: BigInt(1_073_741_824),
|
||||
defaultUserTimezone: null,
|
||||
assistantEnabled: true,
|
||||
assistantCoachEnabled: false,
|
||||
assistantBriefingEnabled: true,
|
||||
assistantInsightStatusEnabled: true,
|
||||
assistantCorrelationsEnabled: true,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(prisma.appSettings.upsert).mockResolvedValue(STORED as never);
|
||||
});
|
||||
|
||||
it("persists a lone assistant flag instead of answering 'No valid fields'", async () => {
|
||||
const res = await PUT(jsonReq({ assistantCoachEnabled: false }));
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(prisma.appSettings.upsert).toHaveBeenCalledTimes(1);
|
||||
const args = vi.mocked(prisma.appSettings.upsert).mock.calls[0]?.[0] as {
|
||||
update: Record<string, unknown>;
|
||||
};
|
||||
expect(args.update).toEqual({ assistantCoachEnabled: false });
|
||||
});
|
||||
|
||||
it("persists an assistant flag sent alongside an unrelated field", async () => {
|
||||
const res = await PUT(
|
||||
jsonReq({ registrationEnabled: false, assistantCoachEnabled: false }),
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const args = vi.mocked(prisma.appSettings.upsert).mock.calls[0]?.[0] as {
|
||||
update: Record<string, unknown>;
|
||||
};
|
||||
expect(args.update).toEqual({
|
||||
registrationEnabled: false,
|
||||
assistantCoachEnabled: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("echoes the stored flags so a scripted write reads back", async () => {
|
||||
const res = await PUT(jsonReq({ assistantCoachEnabled: false }));
|
||||
const body = (await res.json()) as { data: Record<string, unknown> };
|
||||
|
||||
expect(body.data).toMatchObject({
|
||||
assistantEnabled: true,
|
||||
assistantCoachEnabled: false,
|
||||
assistantBriefingEnabled: true,
|
||||
assistantInsightStatusEnabled: true,
|
||||
assistantCorrelationsEnabled: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("audits the flag it changed", async () => {
|
||||
await PUT(jsonReq({ assistantCorrelationsEnabled: false }));
|
||||
|
||||
expect(auditLog).toHaveBeenCalledWith(
|
||||
"admin.settings.update",
|
||||
expect.objectContaining({
|
||||
details: expect.objectContaining({
|
||||
assistantCorrelationsEnabled: false,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("still refuses an unknown flag-shaped key", async () => {
|
||||
const res = await PUT(jsonReq({ assistantNotAThing: false }));
|
||||
expect(res.status).toBe(422);
|
||||
expect(prisma.appSettings.upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/admin/settings — assistant flags", () => {
|
||||
it("defaults every flag to enabled when the row is absent", async () => {
|
||||
vi.mocked(prisma.appSettings.findUnique).mockResolvedValue(null);
|
||||
const res = await GET();
|
||||
const body = (await res.json()) as { data: Record<string, unknown> };
|
||||
|
||||
expect(body.data).toMatchObject({
|
||||
assistantEnabled: true,
|
||||
assistantCoachEnabled: true,
|
||||
assistantBriefingEnabled: true,
|
||||
assistantInsightStatusEnabled: true,
|
||||
assistantCorrelationsEnabled: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("surfaces the stored flags", async () => {
|
||||
vi.mocked(prisma.appSettings.findUnique).mockResolvedValue({
|
||||
assistantEnabled: false,
|
||||
assistantCoachEnabled: false,
|
||||
} as never);
|
||||
const res = await GET();
|
||||
const body = (await res.json()) as { data: Record<string, unknown> };
|
||||
|
||||
expect(body.data).toMatchObject({
|
||||
assistantEnabled: false,
|
||||
assistantCoachEnabled: false,
|
||||
assistantBriefingEnabled: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -61,6 +61,16 @@ export const GET = apiHandler(async () => {
|
||||
// resolver"; surfacing the raw value lets the admin UI render
|
||||
// an empty picker placeholder until they opt in.
|
||||
defaultUserTimezone: settings?.defaultUserTimezone ?? null,
|
||||
// Raw column values, not the resolved matrix — the master flag is
|
||||
// applied to the sub-flags by `/settings/assistant-flags`, which owns
|
||||
// that shape. Echoed here so a write over this route reads back.
|
||||
assistantEnabled: settings?.assistantEnabled ?? true,
|
||||
assistantCoachEnabled: settings?.assistantCoachEnabled ?? true,
|
||||
assistantBriefingEnabled: settings?.assistantBriefingEnabled ?? true,
|
||||
assistantInsightStatusEnabled:
|
||||
settings?.assistantInsightStatusEnabled ?? true,
|
||||
assistantCorrelationsEnabled:
|
||||
settings?.assistantCorrelationsEnabled ?? true,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -83,7 +93,13 @@ export const PUT = apiHandler(async (request: NextRequest) => {
|
||||
const updates: Record<string, unknown> = {};
|
||||
const auditDetails: Record<string, unknown> = {};
|
||||
|
||||
// Boolean fields — direct mapping
|
||||
// Boolean fields — direct mapping.
|
||||
//
|
||||
// The five assistant flags belong here and not only on the dedicated
|
||||
// `/settings/assistant-flags` endpoint: `adminSettingsSchema` accepts them
|
||||
// so an operator scripting their settings over a single route can carry
|
||||
// them, and a schema that accepts a field and then drops it is worse than
|
||||
// one that refuses it.
|
||||
const booleanFields = [
|
||||
"registrationEnabled",
|
||||
"mfaRequired",
|
||||
@@ -93,6 +109,11 @@ export const PUT = apiHandler(async (request: NextRequest) => {
|
||||
"apiGlobal",
|
||||
"umamiEnabled",
|
||||
"glitchtipEnabled",
|
||||
"assistantEnabled",
|
||||
"assistantCoachEnabled",
|
||||
"assistantBriefingEnabled",
|
||||
"assistantInsightStatusEnabled",
|
||||
"assistantCorrelationsEnabled",
|
||||
] as const;
|
||||
for (const field of booleanFields) {
|
||||
if (data[field] !== undefined) {
|
||||
@@ -258,5 +279,10 @@ export const PUT = apiHandler(async (request: NextRequest) => {
|
||||
documentMaxFileBytes: settings.documentMaxFileBytes,
|
||||
documentQuotaBytes: Number(settings.documentQuotaBytes),
|
||||
defaultUserTimezone: settings.defaultUserTimezone,
|
||||
assistantEnabled: settings.assistantEnabled,
|
||||
assistantCoachEnabled: settings.assistantCoachEnabled,
|
||||
assistantBriefingEnabled: settings.assistantBriefingEnabled,
|
||||
assistantInsightStatusEnabled: settings.assistantInsightStatusEnabled,
|
||||
assistantCorrelationsEnabled: settings.assistantCorrelationsEnabled,
|
||||
});
|
||||
});
|
||||
@@ -26,12 +26,19 @@ vi.mock("@/lib/api-handler", () => ({
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
// The route reads the operator's instance-wide Web Push switch before it
|
||||
// touches the body; the default stub leaves it on so these cases keep
|
||||
// asserting the validation refusals they were written for.
|
||||
appSettings: { findUnique: vi.fn() },
|
||||
pushSubscription: { upsert: vi.fn(), deleteMany: vi.fn() },
|
||||
notificationChannel: { findFirst: vi.fn(), create: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/logging/context", () => ({ annotate: vi.fn() }));
|
||||
vi.mock("@/lib/logging/context", () => ({
|
||||
annotate: vi.fn(),
|
||||
getEvent: vi.fn(() => null),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/crypto", () => ({ encrypt: (v: string) => `enc(${v})` }));
|
||||
|
||||
@@ -67,6 +74,12 @@ type Handler = (r: Request) => Promise<Response>;
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(requireAuth).mockResolvedValue({ user: USER } as never);
|
||||
vi.mocked(prisma.appSettings.findUnique).mockResolvedValue({
|
||||
telegramGlobal: true,
|
||||
ntfyGlobal: true,
|
||||
webPushGlobal: true,
|
||||
apiGlobal: true,
|
||||
} as never);
|
||||
});
|
||||
|
||||
describe("POST /api/notifications/web-push — the subscribe refusal", () => {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { isChannelGloballyEnabled } from "@/lib/app-settings";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { apiSuccess, apiError, returnAllZodIssues } from "@/lib/api-response";
|
||||
import { encrypt } from "@/lib/crypto";
|
||||
@@ -43,6 +44,18 @@ export const POST = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "notifications.web-push.subscribe" } });
|
||||
|
||||
// Subscribing IS the enable step for this channel — it creates the
|
||||
// WEB_PUSH `NotificationChannel` row. An operator who switched Web Push
|
||||
// off instance-wide (`AppSettings.webPushGlobal`) gets a refusal that says
|
||||
// so rather than a subscription that stores fine and delivers nothing.
|
||||
if (!(await isChannelGloballyEnabled("WEB_PUSH"))) {
|
||||
annotate({ meta: { refused: "globally_disabled" } });
|
||||
return apiError(
|
||||
"Web Push is disabled on this instance by the operator",
|
||||
403,
|
||||
);
|
||||
}
|
||||
|
||||
let body: unknown;
|
||||
try {
|
||||
const raw = await request.text();
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
/**
|
||||
* Enabling a channel the operator switched off instance-wide is refused.
|
||||
*
|
||||
* The three switches (`AppSettings.telegramGlobal` / `.ntfyGlobal` /
|
||||
* `.webPushGlobal`) now stop delivery in the dispatcher. Without a matching
|
||||
* refusal on the way in, a user would still see the toggle flip, the row
|
||||
* would still say `enabled = true`, and nothing would ever arrive. These
|
||||
* tests pin the refusal and the absence of any write behind it.
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
appSettings: { findUnique: vi.fn() },
|
||||
notificationChannel: {
|
||||
findUnique: vi.fn(),
|
||||
findFirst: vi.fn(),
|
||||
create: vi.fn(),
|
||||
updateMany: vi.fn(),
|
||||
upsert: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
},
|
||||
pushSubscription: { upsert: vi.fn() },
|
||||
user: { findUnique: vi.fn(), update: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/crypto", () => ({
|
||||
encrypt: vi.fn((value: string) => `encrypted:${value}`),
|
||||
decrypt: vi.fn((value: string) => value.replace(/^encrypted:/, "")),
|
||||
}));
|
||||
|
||||
const setTelegramWebhookMock = vi.fn().mockResolvedValue(true);
|
||||
vi.mock("@/lib/telegram", () => ({
|
||||
setTelegramWebhook: (...args: unknown[]) => setTelegramWebhookMock(...args),
|
||||
deleteTelegramWebhook: vi.fn().mockResolvedValue(true),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
|
||||
vi.mock("@/lib/auth/audit", () => ({
|
||||
auditLog: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
|
||||
vi.mock("@/lib/db-compat", () => ({
|
||||
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
vi.mock("@/lib/rate-limit", () => ({
|
||||
checkRateLimit: vi.fn().mockResolvedValue({
|
||||
allowed: true,
|
||||
remaining: 59,
|
||||
resetAt: Date.now() + 60_000,
|
||||
}),
|
||||
rateLimitHeaders: () => ({}),
|
||||
}));
|
||||
vi.mock("next/headers", () => ({
|
||||
headers: vi.fn(async () => ({ get: () => null })),
|
||||
cookies: vi.fn(async () => ({
|
||||
get: () => undefined,
|
||||
set: () => {},
|
||||
delete: () => {},
|
||||
})),
|
||||
}));
|
||||
|
||||
import { PUT as putNtfy } from "../ntfy/route";
|
||||
import { PUT as putTelegram } from "../telegram/route";
|
||||
import { POST as postWebPush } from "../../notifications/web-push/route";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
|
||||
const SESSION_OK = {
|
||||
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
|
||||
user: { id: "user-1", username: "testuser", role: "USER" as const },
|
||||
};
|
||||
|
||||
const WEB_PUSH_SUBSCRIPTION = {
|
||||
endpoint: "https://push.example.com/subscription/abc",
|
||||
keys: { p256dh: "a".repeat(87), auth: "b".repeat(22) },
|
||||
};
|
||||
|
||||
function stubSettings(over: Record<string, boolean>) {
|
||||
vi.mocked(prisma.appSettings.findUnique).mockResolvedValue({
|
||||
telegramGlobal: true,
|
||||
ntfyGlobal: true,
|
||||
webPushGlobal: true,
|
||||
apiGlobal: true,
|
||||
...over,
|
||||
} as never);
|
||||
}
|
||||
|
||||
function request(path: string, method: string, body: unknown) {
|
||||
return new Request(`http://localhost${path}`, {
|
||||
method,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
vi.mocked(prisma.notificationChannel.updateMany).mockResolvedValue({
|
||||
count: 1,
|
||||
} as never);
|
||||
vi.mocked(prisma.notificationChannel.upsert).mockResolvedValue({} as never);
|
||||
vi.mocked(prisma.notificationChannel.findUnique).mockResolvedValue({
|
||||
config: 'encrypted:{"serverUrl":"https://ntfy.sh","topic":"saved-topic"}',
|
||||
} as never);
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({
|
||||
telegramBotToken: "encrypted:saved-token",
|
||||
telegramChatId: "saved-chat",
|
||||
telegramEnabled: false,
|
||||
} as never);
|
||||
vi.mocked(prisma.user.update).mockResolvedValue({} as never);
|
||||
vi.mocked(prisma.pushSubscription.upsert).mockResolvedValue({} as never);
|
||||
vi.mocked(prisma.notificationChannel.findFirst).mockResolvedValue(null);
|
||||
});
|
||||
|
||||
describe("ntfy enable against the instance-wide switch", () => {
|
||||
it("refuses with 403 and writes nothing when the operator switched ntfy off", async () => {
|
||||
stubSettings({ ntfyGlobal: false });
|
||||
|
||||
const response = await putNtfy(
|
||||
request("/api/settings/ntfy", "PUT", { enabled: true }) as never,
|
||||
);
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
await expect(response.json()).resolves.toMatchObject({
|
||||
data: null,
|
||||
error: expect.stringContaining("disabled on this instance"),
|
||||
});
|
||||
expect(prisma.notificationChannel.updateMany).not.toHaveBeenCalled();
|
||||
expect(prisma.notificationChannel.upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("still allows disabling the channel while the switch is off", async () => {
|
||||
stubSettings({ ntfyGlobal: false });
|
||||
|
||||
const response = await putNtfy(
|
||||
request("/api/settings/ntfy", "PUT", { enabled: false }) as never,
|
||||
);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(prisma.notificationChannel.updateMany).toHaveBeenCalledWith({
|
||||
where: { userId: "user-1", type: "NTFY" },
|
||||
data: { enabled: false },
|
||||
});
|
||||
});
|
||||
|
||||
it("allows enabling while the switch is on", async () => {
|
||||
stubSettings({ ntfyGlobal: true });
|
||||
|
||||
const response = await putNtfy(
|
||||
request("/api/settings/ntfy", "PUT", { enabled: true }) as never,
|
||||
);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(prisma.notificationChannel.updateMany).toHaveBeenCalledWith({
|
||||
where: { userId: "user-1", type: "NTFY" },
|
||||
data: { enabled: true },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Telegram enable against the instance-wide switch", () => {
|
||||
it("refuses with 403, registers no webhook, and writes nothing", async () => {
|
||||
stubSettings({ telegramGlobal: false });
|
||||
|
||||
const response = await putTelegram(
|
||||
request("/api/settings/telegram", "PUT", { enabled: true }) as never,
|
||||
);
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
expect(setTelegramWebhookMock).not.toHaveBeenCalled();
|
||||
expect(prisma.user.update).not.toHaveBeenCalled();
|
||||
expect(prisma.notificationChannel.updateMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("refuses a full-config save that enables the channel", async () => {
|
||||
stubSettings({ telegramGlobal: false });
|
||||
|
||||
const response = await putTelegram(
|
||||
request("/api/settings/telegram", "PUT", {
|
||||
botToken: "123456:AAaaBBbbCCccDDddEEeeFFffGGgg-HHhhIIii",
|
||||
chatId: "9876543",
|
||||
enabled: true,
|
||||
}) as never,
|
||||
);
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
expect(setTelegramWebhookMock).not.toHaveBeenCalled();
|
||||
expect(prisma.user.update).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Web Push subscribe against the instance-wide switch", () => {
|
||||
it("refuses with 403 and stores no subscription", async () => {
|
||||
stubSettings({ webPushGlobal: false });
|
||||
|
||||
const response = await postWebPush(
|
||||
request(
|
||||
"/api/notifications/web-push",
|
||||
"POST",
|
||||
WEB_PUSH_SUBSCRIPTION,
|
||||
) as never,
|
||||
);
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
expect(prisma.pushSubscription.upsert).not.toHaveBeenCalled();
|
||||
expect(prisma.notificationChannel.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("stores the subscription while the switch is on", async () => {
|
||||
stubSettings({ webPushGlobal: true });
|
||||
|
||||
const response = await postWebPush(
|
||||
request(
|
||||
"/api/notifications/web-push",
|
||||
"POST",
|
||||
WEB_PUSH_SUBSCRIPTION,
|
||||
) as never,
|
||||
);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(prisma.pushSubscription.upsert).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -7,8 +7,17 @@ import {
|
||||
import { encrypt, decrypt } from "@/lib/crypto";
|
||||
import { NextRequest } from "next/server";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { isChannelGloballyEnabled } from "@/lib/app-settings";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
/**
|
||||
* Refusal for an enable attempt on a channel the operator switched off
|
||||
* instance-wide (`AppSettings.ntfyGlobal`). A toggle that appeared to work
|
||||
* and then delivered nothing is worse than a refusal that says why.
|
||||
*/
|
||||
const NTFY_GLOBALLY_DISABLED =
|
||||
"ntfy is disabled on this instance by the operator";
|
||||
|
||||
/**
|
||||
* GET: Return current ntfy config (without auth token).
|
||||
* PUT: Update ntfy config.
|
||||
@@ -60,6 +69,14 @@ export const PUT = apiHandler(async (request: NextRequest) => {
|
||||
if (enabledOnly.success) {
|
||||
const { enabled } = enabledOnly.data;
|
||||
|
||||
if (enabled && !(await isChannelGloballyEnabled("NTFY"))) {
|
||||
annotate({
|
||||
action: { name: "settings.ntfy.update" },
|
||||
meta: { refused: "globally_disabled" },
|
||||
});
|
||||
return apiError(NTFY_GLOBALLY_DISABLED, 403);
|
||||
}
|
||||
|
||||
if (enabled) {
|
||||
const existing = await prisma.notificationChannel.findUnique({
|
||||
where: { userId_type: { userId: user.id, type: "NTFY" } },
|
||||
@@ -106,6 +123,14 @@ export const PUT = apiHandler(async (request: NextRequest) => {
|
||||
|
||||
const { serverUrl, topic, authToken, enabled } = parsed.data;
|
||||
|
||||
if (enabled && !(await isChannelGloballyEnabled("NTFY"))) {
|
||||
annotate({
|
||||
action: { name: "settings.ntfy.update" },
|
||||
meta: { refused: "globally_disabled" },
|
||||
});
|
||||
return apiError(NTFY_GLOBALLY_DISABLED, 403);
|
||||
}
|
||||
|
||||
if (enabled && (!serverUrl || !topic)) {
|
||||
return apiError(
|
||||
"Server URL and topic are required when ntfy is enabled",
|
||||
|
||||
@@ -7,8 +7,17 @@ import { notificationChannelEnabledSchema } from "@/lib/validations/notification
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod/v4";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { isChannelGloballyEnabled } from "@/lib/app-settings";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
/**
|
||||
* Refusal for an enable attempt on a channel the operator switched off
|
||||
* instance-wide (`AppSettings.telegramGlobal`). A toggle that appeared to
|
||||
* work and then delivered nothing is worse than a refusal that says why.
|
||||
*/
|
||||
const TELEGRAM_GLOBALLY_DISABLED =
|
||||
"Telegram is disabled on this instance by the operator";
|
||||
|
||||
/**
|
||||
* Get Telegram notification settings for the current user.
|
||||
* Never returns the bot token in plaintext.
|
||||
@@ -117,6 +126,14 @@ export const PUT = apiHandler(async (request: NextRequest) => {
|
||||
const enabledOnly = notificationChannelEnabledSchema.safeParse(body);
|
||||
if (enabledOnly.success) {
|
||||
const { enabled } = enabledOnly.data;
|
||||
if (enabled && !(await isChannelGloballyEnabled("TELEGRAM"))) {
|
||||
annotate({
|
||||
action: { name: "settings.telegram.update" },
|
||||
meta: { refused: "globally_disabled" },
|
||||
});
|
||||
return apiError(TELEGRAM_GLOBALLY_DISABLED, 403);
|
||||
}
|
||||
|
||||
if (enabled && (!current.telegramBotToken || !current.telegramChatId)) {
|
||||
return apiError(
|
||||
"Bot token and chat ID are required when Telegram is enabled",
|
||||
@@ -166,6 +183,14 @@ export const PUT = apiHandler(async (request: NextRequest) => {
|
||||
const hasChatIdAfter =
|
||||
chatId !== undefined ? !!trimmedChatId : !!current.telegramChatId;
|
||||
|
||||
if (enabled && !(await isChannelGloballyEnabled("TELEGRAM"))) {
|
||||
annotate({
|
||||
action: { name: "settings.telegram.update" },
|
||||
meta: { refused: "globally_disabled" },
|
||||
});
|
||||
return apiError(TELEGRAM_GLOBALLY_DISABLED, 403);
|
||||
}
|
||||
|
||||
if (enabled && (!hasTokenAfter || !hasChatIdAfter)) {
|
||||
return apiError(
|
||||
"Bot token and chat ID are required when Telegram is enabled",
|
||||
|
||||
Reference in new issue
Block a user