diff --git a/app/dashboard/integrations/notifications/page.tsx b/app/dashboard/integrations/notifications/page.tsx index fae9d61..6c61995 100644 --- a/app/dashboard/integrations/notifications/page.tsx +++ b/app/dashboard/integrations/notifications/page.tsx @@ -49,45 +49,60 @@ import type { NotificationChannelType, NotificationChannelTypeInfo, } from "@/lib/types/notification"; -import { NOTIFICATION_CHANNEL_TYPES } from "@/lib/types/notification"; +import { + NOTIFICATION_CHANNEL_TYPES, + getNotificationTypeInfo, +} from "@/lib/types/notification"; +import type { ChannelFormState } from "@/lib/notifications/channel-form"; +import { + buildCreateFormState, + buildCreatePayload, + buildEditFormState, + buildUpdatePayload, + createHeaderRow, + validateChannelForm, +} from "@/lib/notifications/channel-form"; +import { SecretInput } from "@/components/notification/SecretInput"; import { NotificationIcon, notificationConfig, } from "@/components/notification/NotificationIcon"; import { toast } from "sonner"; -function maskSecret(value: string): string { - if (value.length <= 8) return "***"; - return value.slice(0, 4) + "***" + value.slice(-4); +function safeHost(url: unknown): string | null { + if (typeof url !== "string" || !url) return null; + try { + const parsed = new URL(url); + return `${parsed.protocol}//${parsed.host}/***`; + } catch { + return null; + } } +/** + * Built from redacted metadata only. Secret values are not part of the channel + * payload, so the subtitle describes configuration state instead. + */ function getChannelSubtitle(channel: NotificationChannel): string { - const cfg = channel.config; + const cfg = channel.config ?? {}; + if (channel.type === "webhook") { - try { - const parsed = new URL(cfg.url as string); - return `${parsed.protocol}//${parsed.host}/***`; - } catch { - return "***"; - } + const host = safeHost(cfg.url); + const headerCount = cfg.headerNames?.length ?? 0; + const headerLabel = + headerCount > 0 + ? ` \u00b7 ${headerCount} custom header${headerCount === 1 ? "" : "s"}` + : ""; + return `${host ?? "No endpoint configured"}${headerLabel}`; } + if (channel.type === "telegram") { - return `Chat: ${cfg.chat_id || "***"}`; - } - if (channel.type === "pagerduty") { - return `Routing key: ${maskSecret((cfg.routing_key as string) || "")}`; - } - // slack, discord, teams — all use webhook_url - const url = cfg.webhook_url as string; - if (url) { - try { - const parsed = new URL(url); - return `${parsed.protocol}//${parsed.host}/***`; - } catch { - return "***"; - } + const chatId = typeof cfg.chat_id === "string" ? cfg.chat_id : null; + return chatId ? `Chat: ${chatId}` : "Chat not configured"; } - return ""; + + const configuredCount = channel.configuredSecrets?.length ?? 0; + return configuredCount > 0 ? "Credentials configured" : "Not configured"; } export default function NotificationsPage() { @@ -113,10 +128,13 @@ export default function NotificationsPage() { useState(null); const [testingId, setTestingId] = useState(null); - // Form state - const [name, setName] = useState(""); - const [configValues, setConfigValues] = useState>({}); - const [headers, setHeaders] = useState<{ key: string; value: string }[]>([]); + // Form state. Secret values live here only while the user is typing them. + const [form, setForm] = useState({ + name: "", + values: {}, + secrets: {}, + headers: [], + }); const [isSubmitting, setIsSubmitting] = useState(false); useEffect(() => { @@ -133,34 +151,19 @@ export default function NotificationsPage() { setEditChannel(null); setSelectedType(null); setDialogStep("type"); - setName(""); - setConfigValues({}); - setHeaders([]); + setForm({ name: "", values: {}, secrets: {}, headers: [] }); setDialogOpen(true); }; const openEditDialog = (channel: NotificationChannel) => { + const typeInfo = getNotificationTypeInfo(channel.type); setEditChannel(channel); - const typeInfo = NOTIFICATION_CHANNEL_TYPES.find( - t => t.type === channel.type - ); setSelectedType(typeInfo || null); setDialogStep("config"); - setName(channel.name); - - // Populate config values from channel - const values: Record = {}; - if (typeInfo) { - for (const field of typeInfo.fields) { - values[field.key] = (channel.config[field.key] as string) || ""; - } - } - setConfigValues(values); - - // Populate headers for webhook type - const h = channel.config.headers as Record | undefined; - setHeaders( - h ? Object.entries(h).map(([key, value]) => ({ key, value })) : [] + setForm( + typeInfo + ? buildEditFormState(channel, typeInfo) + : { name: channel.name, values: {}, secrets: {}, headers: [] } ); setDialogOpen(true); }; @@ -168,60 +171,30 @@ export default function NotificationsPage() { const selectType = (typeInfo: NotificationChannelTypeInfo) => { setSelectedType(typeInfo); setDialogStep("config"); - setConfigValues({}); - setHeaders([]); + setForm(buildCreateFormState(typeInfo)); }; const handleSubmit = async () => { if (!selectedType) return; - if (!name.trim()) { - toast.error("Name is required"); + const validationError = validateChannelForm(form, selectedType); + if (validationError) { + toast.error(validationError); return; } - // Validate required fields - for (const field of selectedType.fields) { - if (field.required && !configValues[field.key]?.trim()) { - toast.error(`${field.label} is required`); - return; - } - } - setIsSubmitting(true); try { - const config: Record = {}; - for (const field of selectedType.fields) { - if (configValues[field.key]?.trim()) { - config[field.key] = configValues[field.key]; - } - } - - // Add custom headers for webhook type - if (selectedType.type === "webhook") { - const headerMap: Record = {}; - headers.forEach(h => { - if (h.key.trim()) headerMap[h.key] = h.value; - }); - if (Object.keys(headerMap).length > 0) { - config.headers = headerMap; - } - } - - const data = { - name, - type: selectedType.type, - config, - }; - if (editChannel) { - await updateChannel(editChannel.id, data); + await updateChannel( + editChannel.id, + buildUpdatePayload(form, selectedType) + ); } else { - await createChannel(data); + await createChannel(buildCreatePayload(form, selectedType)); } setDialogOpen(false); - } catch (error) { - console.error("Failed to save channel:", error); + } catch { toast.error("Failed to save channel"); } finally { setIsSubmitting(false); @@ -482,87 +455,163 @@ export default function NotificationsPage() { setName(e.target.value)} + value={form.name} + onChange={e => setForm({ ...form, name: e.target.value })} placeholder={`e.g., ${selectedType?.name || "My"} Alerts`} /> - {selectedType?.fields.map(field => ( -
- - + field.secret ? ( + - setConfigValues({ - ...configValues, - [field.key]: e.target.value, + label={field.label} + placeholder={field.placeholder} + helpText={field.helpText} + required={field.required} + allowRemove={!field.required} + state={ + form.secrets[field.key] ?? { + value: "", + configured: false, + markedForRemoval: false, + } + } + onChange={next => + setForm({ + ...form, + secrets: { ...form.secrets, [field.key]: next }, }) } - placeholder={field.placeholder} - type={field.type} /> - {field.helpText && ( -

- {field.helpText} -

- )} -
- ))} + ) : ( +
+ + + setForm({ + ...form, + values: { + ...form.values, + [field.key]: e.target.value, + }, + }) + } + placeholder={field.placeholder} + type={field.type} + aria-describedby={ + field.helpText ? `field-${field.key}-help` : undefined + } + /> + {field.helpText && ( +

+ {field.helpText} +

+ )} +
+ ) + )} - {/* Custom headers for webhook type */} - {selectedType?.type === "webhook" && ( + {/* Custom headers. Names are metadata, values are secrets. */} + {selectedType?.supportsCustomHeaders && (
- +
- {headers.map((h, i) => ( -
- { - const next = [...headers]; - next[i].key = e.target.value; - setHeaders(next); - }} - placeholder="Header name" - className="flex-1" - /> - { - const next = [...headers]; - next[i].value = e.target.value; - setHeaders(next); - }} - placeholder="Value" - className="flex-1" - /> - -
- ))} +
+
+ + { + const next = [...form.headers]; + next[index] = { + ...row, + name: e.target.value, + }; + setForm({ ...form, headers: next }); + }} + placeholder="X-Api-Key" + /> +
+ +
+ + { + const updated = [...form.headers]; + updated[index] = { ...row, value: next.value }; + setForm({ ...form, headers: updated }); + }} + /> + + ))} +
)} diff --git a/components/notification/SecretInput.tsx b/components/notification/SecretInput.tsx new file mode 100644 index 0000000..6057f9d --- /dev/null +++ b/components/notification/SecretInput.tsx @@ -0,0 +1,184 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { CheckCircle2, Trash2, Undo2 } from "lucide-react"; +import type { SecretFieldState } from "@/lib/notifications/channel-form"; + +interface SecretInputProps { + id: string; + label: string; + placeholder?: string; + helpText?: string; + required?: boolean; + /** Show a control that clears the stored secret on save. */ + allowRemove?: boolean; + state: SecretFieldState; + onChange: (next: SecretFieldState) => void; +} + +/** + * Input for a value the API never returns. When a secret is already stored the + * field renders empty with a "Configured" indicator; typing a value rotates it + * and the remove control clears it. + */ +export function SecretInput({ + id, + label, + placeholder, + helpText, + required, + allowRemove, + state, + onChange, +}: SecretInputProps) { + const [isReplacing, setIsReplacing] = useState(false); + const inputRef = useRef(null); + + // Move focus into the field the user just revealed so keyboard users land + // where they can type the new value. + useEffect(() => { + if (isReplacing) { + inputRef.current?.focus(); + } + }, [isReplacing]); + + const statusId = `${id}-status`; + const helpId = helpText ? `${id}-help` : undefined; + const describedBy = [statusId, helpId].filter(Boolean).join(" "); + + const showInput = !state.configured || isReplacing; + + const startReplacing = () => { + setIsReplacing(true); + onChange({ ...state, markedForRemoval: false }); + }; + + const cancelReplacing = () => { + setIsReplacing(false); + onChange({ ...state, value: "" }); + }; + + const markForRemoval = () => { + setIsReplacing(false); + onChange({ ...state, value: "", markedForRemoval: true }); + }; + + const undoRemoval = () => { + onChange({ ...state, markedForRemoval: false }); + }; + + let status: string; + if (state.markedForRemoval) { + status = `${label} will be removed when you save`; + } else if (showInput && state.configured) { + status = `Enter a new ${label} to replace the stored one`; + } else if (state.configured) { + status = `${label} is configured. The stored value is never displayed.`; + } else { + status = `${label} is not configured`; + } + + return ( +
+
+ + +
+ {state.configured && !state.markedForRemoval && !isReplacing && ( + + )} + {state.configured && isReplacing && ( + + )} + {allowRemove && + state.configured && + !state.markedForRemoval && + !isReplacing && ( + + )} + {state.markedForRemoval && ( + + )} +
+
+ + {showInput && !state.markedForRemoval ? ( + onChange({ ...state, value: e.target.value })} + placeholder={placeholder} + aria-describedby={describedBy} + autoComplete="new-password" + ref={inputRef} + /> + ) : ( +
+ {state.markedForRemoval ? ( +
+ )} + +

+ {status} +

+ + {helpText && ( +

+ {helpText} +

+ )} +
+ ); +} diff --git a/components/notification/__tests__/SecretInput.test.tsx b/components/notification/__tests__/SecretInput.test.tsx new file mode 100644 index 0000000..6688fad --- /dev/null +++ b/components/notification/__tests__/SecretInput.test.tsx @@ -0,0 +1,131 @@ +import { describe, it, expect, vi } from "vitest"; +import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { useState } from "react"; +import { SecretInput } from "../SecretInput"; +import type { SecretFieldState } from "@/lib/notifications/channel-form"; + +function Harness({ + initial, + allowRemove, + onState, +}: { + initial: SecretFieldState; + allowRemove?: boolean; + onState?: (state: SecretFieldState) => void; +}) { + const [state, setState] = useState(initial); + return ( + { + setState(next); + onState?.(next); + }} + /> + ); +} + +const configured: SecretFieldState = { + value: "", + configured: true, + markedForRemoval: false, +}; + +const empty: SecretFieldState = { + value: "", + configured: false, + markedForRemoval: false, +}; + +describe("SecretInput", () => { + it("renders an editable input when nothing is stored", () => { + render(); + + expect(screen.getByLabelText(/Webhook URL/)).toHaveValue(""); + expect( + screen.getByText("Webhook URL is not configured") + ).toBeInTheDocument(); + }); + + it("hides the input and announces the configured state", () => { + render(); + + expect(screen.queryByLabelText(/Webhook URL/)).not.toBeInTheDocument(); + expect(screen.getByText("Configured")).toBeInTheDocument(); + expect( + screen.getByText( + "Webhook URL is configured. The stored value is never displayed." + ) + ).toBeInTheDocument(); + }); + + it("opens an empty input when replacing a stored secret", async () => { + const user = userEvent.setup(); + render(); + + await user.click(screen.getByRole("button", { name: "Replace" })); + + const input = screen.getByLabelText(/Webhook URL/); + expect(input).toHaveValue(""); + expect(input).toHaveAttribute("type", "password"); + }); + + it("reports the typed replacement to the parent", async () => { + const user = userEvent.setup(); + const onState = vi.fn(); + render(); + + await user.click(screen.getByRole("button", { name: "Replace" })); + await user.type(screen.getByLabelText(/Webhook URL/), "new"); + + expect(onState).toHaveBeenLastCalledWith({ + value: "new", + configured: true, + markedForRemoval: false, + }); + }); + + it("clears the typed value when the replacement is cancelled", async () => { + const user = userEvent.setup(); + const onState = vi.fn(); + render(); + + await user.click(screen.getByRole("button", { name: "Replace" })); + await user.type(screen.getByLabelText(/Webhook URL/), "oops"); + await user.click(screen.getByRole("button", { name: "Cancel" })); + + expect(onState).toHaveBeenLastCalledWith({ + value: "", + configured: true, + markedForRemoval: false, + }); + expect(screen.getByText("Configured")).toBeInTheDocument(); + }); + + it("marks the secret for removal and allows undo", async () => { + const user = userEvent.setup(); + render(); + + await user.click(screen.getByRole("button", { name: /Remove/ })); + expect( + screen.getByText("Webhook URL will be removed when you save") + ).toBeInTheDocument(); + + await user.click(screen.getByRole("button", { name: /Undo/ })); + expect(screen.getByText("Configured")).toBeInTheDocument(); + }); + + it("hides the remove control when removal is not allowed", () => { + render(); + + expect( + screen.queryByRole("button", { name: /Remove/ }) + ).not.toBeInTheDocument(); + }); +}); diff --git a/lib/notifications/__tests__/channel-form.test.ts b/lib/notifications/__tests__/channel-form.test.ts new file mode 100644 index 0000000..2fe8b22 --- /dev/null +++ b/lib/notifications/__tests__/channel-form.test.ts @@ -0,0 +1,290 @@ +import { describe, it, expect } from "vitest"; +import { + buildCreateFormState, + buildCreatePayload, + buildEditFormState, + buildUpdatePayload, + createHeaderRow, + describeSecretState, + validateChannelForm, +} from "../channel-form"; +import type { NotificationChannel } from "@/lib/services/notifications"; +import { getNotificationTypeInfo } from "@/lib/types/notification"; + +const slack = getNotificationTypeInfo("slack")!; +const telegram = getNotificationTypeInfo("telegram")!; +const webhook = getNotificationTypeInfo("webhook")!; + +function channel( + overrides: Partial = {} +): NotificationChannel { + return { + id: "ch-1", + userId: "user-1", + name: "Ops Slack", + type: "slack", + config: {}, + configuredSecrets: ["webhook_url"], + enabled: true, + createdAt: "2026-01-01T00:00:00Z", + updatedAt: "2026-01-01T00:00:00Z", + ...overrides, + }; +} + +describe("buildEditFormState", () => { + it("leaves secret inputs empty and flags them as configured", () => { + const state = buildEditFormState(channel(), slack); + + expect(state.name).toBe("Ops Slack"); + expect(state.secrets.webhook_url).toEqual({ + value: "", + configured: true, + markedForRemoval: false, + }); + }); + + it("prefills non-secret metadata only", () => { + const state = buildEditFormState( + channel({ + type: "telegram", + config: { chat_id: "-1001234567890", bot_token: "leaked-token" }, + configuredSecrets: ["bot_token"], + }), + telegram + ); + + expect(state.values.chat_id).toBe("-1001234567890"); + expect(state.values.bot_token).toBeUndefined(); + expect(state.secrets.bot_token.value).toBe(""); + expect(JSON.stringify(state)).not.toContain("leaked-token"); + }); + + it("rebuilds header rows from names without values", () => { + const state = buildEditFormState( + channel({ + type: "webhook", + config: { url: "https://example.com/hook", headerNames: ["X-Api-Key"] }, + configuredSecrets: ["headers.X-Api-Key"], + }), + webhook + ); + + expect(state.headers).toHaveLength(1); + expect(state.headers[0]).toMatchObject({ + name: "X-Api-Key", + originalName: "X-Api-Key", + value: "", + configured: true, + }); + }); +}); + +describe("validateChannelForm", () => { + it("requires a secret on create", () => { + const state = buildCreateFormState(slack); + state.name = "New channel"; + + expect(validateChannelForm(state, slack)).toBe("Webhook URL is required"); + }); + + it("accepts an untouched secret that is already configured", () => { + const state = buildEditFormState(channel(), slack); + + expect(validateChannelForm(state, slack)).toBeNull(); + }); + + it("rejects removing a required secret", () => { + const state = buildEditFormState(channel(), slack); + state.secrets.webhook_url.markedForRemoval = true; + + expect(validateChannelForm(state, slack)).toBe("Webhook URL is required"); + }); + + it("requires a value for a renamed header", () => { + const state = buildEditFormState( + channel({ + type: "webhook", + config: { url: "https://example.com/hook", headerNames: ["X-Api-Key"] }, + configuredSecrets: ["headers.X-Api-Key"], + }), + webhook + ); + state.headers[0].name = "X-Token"; + + expect(validateChannelForm(state, webhook)).toBe( + 'Value for header "X-Token" is required' + ); + }); + + it("rejects duplicate header names", () => { + const state = buildCreateFormState(webhook); + state.name = "Hook"; + state.values.url = "https://example.com/hook"; + state.headers = [ + { ...createHeaderRow(), name: "X-Api-Key", value: "a" }, + { ...createHeaderRow(), name: "x-api-key", value: "b" }, + ]; + + expect(validateChannelForm(state, webhook)).toBe( + 'Duplicate header "x-api-key"' + ); + }); +}); + +describe("buildCreatePayload", () => { + it("separates secrets from config", () => { + const state = buildCreateFormState(telegram); + state.name = "Telegram"; + state.values.chat_id = "-100"; + state.secrets.bot_token.value = "123:abc"; + + expect(buildCreatePayload(state, telegram)).toEqual({ + name: "Telegram", + type: "telegram", + config: { chat_id: "-100" }, + secrets: { bot_token: "123:abc" }, + }); + }); + + it("sends header values as entered", () => { + const state = buildCreateFormState(webhook); + state.name = "Hook"; + state.values.url = "https://example.com/hook"; + state.headers = [{ ...createHeaderRow(), name: "X-Api-Key", value: "abc" }]; + + expect(buildCreatePayload(state, webhook).headers).toEqual([ + { name: "X-Api-Key", value: "abc" }, + ]); + }); +}); + +describe("buildUpdatePayload", () => { + it("omits secrets entirely for a metadata-only edit", () => { + const state = buildEditFormState( + channel({ + type: "telegram", + config: { chat_id: "-100" }, + configuredSecrets: ["bot_token"], + }), + telegram + ); + state.name = "Renamed"; + + const payload = buildUpdatePayload(state, telegram); + + expect(payload).toEqual({ + name: "Renamed", + config: { chat_id: "-100" }, + }); + expect("secrets" in payload).toBe(false); + expect("removeSecrets" in payload).toBe(false); + }); + + it("sends a replacement only for the retyped secret", () => { + const state = buildEditFormState( + channel({ + type: "telegram", + config: { chat_id: "-100" }, + configuredSecrets: ["bot_token"], + }), + telegram + ); + state.secrets.bot_token.value = "999:new"; + + expect(buildUpdatePayload(state, telegram).secrets).toEqual({ + bot_token: "999:new", + }); + }); + + it("requests explicit removal for a cleared secret", () => { + const state = buildEditFormState(channel(), slack); + state.secrets.webhook_url.markedForRemoval = true; + + const payload = buildUpdatePayload(state, slack); + + expect(payload.removeSecrets).toEqual(["webhook_url"]); + expect(payload.secrets).toBeUndefined(); + }); + + it("prefers a typed value over a pending removal", () => { + const state = buildEditFormState(channel(), slack); + state.secrets.webhook_url.markedForRemoval = true; + state.secrets.webhook_url.value = "https://hooks.slack.com/new"; + + const payload = buildUpdatePayload(state, slack); + + expect(payload.secrets).toEqual({ + webhook_url: "https://hooks.slack.com/new", + }); + expect(payload.removeSecrets).toBeUndefined(); + }); + + it("keeps an untouched header by name and drops deleted ones", () => { + const state = buildEditFormState( + channel({ + type: "webhook", + config: { + url: "https://example.com/hook", + headerNames: ["X-Api-Key", "X-Trace"], + }, + configuredSecrets: ["headers.X-Api-Key", "headers.X-Trace"], + }), + webhook + ); + state.headers = state.headers.filter(h => h.name !== "X-Trace"); + + expect(buildUpdatePayload(state, webhook).headers).toEqual([ + { name: "X-Api-Key" }, + ]); + }); + + it("sends a header value when the user rotates it", () => { + const state = buildEditFormState( + channel({ + type: "webhook", + config: { url: "https://example.com/hook", headerNames: ["X-Api-Key"] }, + configuredSecrets: ["headers.X-Api-Key"], + }), + webhook + ); + state.headers[0].value = "rotated"; + + expect(buildUpdatePayload(state, webhook).headers).toEqual([ + { name: "X-Api-Key", value: "rotated" }, + ]); + }); +}); + +describe("describeSecretState", () => { + it("reports each state", () => { + expect( + describeSecretState({ + value: "", + configured: false, + markedForRemoval: false, + }) + ).toBe("empty"); + expect( + describeSecretState({ + value: "", + configured: true, + markedForRemoval: false, + }) + ).toBe("configured"); + expect( + describeSecretState({ + value: "x", + configured: true, + markedForRemoval: false, + }) + ).toBe("replacing"); + expect( + describeSecretState({ + value: "", + configured: true, + markedForRemoval: true, + }) + ).toBe("removing"); + }); +}); diff --git a/lib/notifications/channel-form.ts b/lib/notifications/channel-form.ts new file mode 100644 index 0000000..c17e243 --- /dev/null +++ b/lib/notifications/channel-form.ts @@ -0,0 +1,281 @@ +import type { + ChannelHeaderInput, + CreateChannelRequest, + NotificationChannel, + UpdateChannelRequest, +} from "@/lib/services/notifications"; +import type { + NotificationChannelTypeInfo, + NotificationFormField, +} from "@/lib/types/notification"; +import { + HEADER_SECRET_PREFIX, + headerSecretKey, +} from "@/lib/types/notification"; + +/** + * State of a single write-only field. `value` only ever holds what the user + * typed in this session — a stored secret is never loaded into it. + */ +export interface SecretFieldState { + value: string; + /** Core reports a secret is stored under this key. */ + configured: boolean; + /** User asked to clear the stored secret on save. */ + markedForRemoval: boolean; +} + +export interface HeaderRowState { + /** Stable key for React lists; not sent to the API. */ + id: string; + name: string; + /** Name the header had when the form opened, "" for rows added locally. */ + originalName: string; + value: string; + configured: boolean; +} + +export interface ChannelFormState { + name: string; + /** Non-secret field values, keyed by field key. */ + values: Record; + secrets: Record; + headers: HeaderRowState[]; +} + +let headerRowCounter = 0; + +function nextHeaderRowId(): string { + headerRowCounter += 1; + return `header-${headerRowCounter}`; +} + +export function createHeaderRow(): HeaderRowState { + return { + id: nextHeaderRowId(), + name: "", + originalName: "", + value: "", + configured: false, + }; +} + +function emptySecret(configured: boolean): SecretFieldState { + return { value: "", configured, markedForRemoval: false }; +} + +export function buildCreateFormState( + typeInfo: NotificationChannelTypeInfo +): ChannelFormState { + const values: Record = {}; + const secrets: Record = {}; + + for (const field of typeInfo.fields) { + if (field.secret) { + secrets[field.key] = emptySecret(false); + } else { + values[field.key] = ""; + } + } + + return { name: "", values, secrets, headers: [] }; +} + +/** + * Edit state. Non-secret metadata is prefilled from the redacted config; + * secret inputs start empty and only carry a `configured` indicator. + */ +export function buildEditFormState( + channel: NotificationChannel, + typeInfo: NotificationChannelTypeInfo +): ChannelFormState { + const configured = new Set(channel.configuredSecrets ?? []); + const values: Record = {}; + const secrets: Record = {}; + + for (const field of typeInfo.fields) { + if (field.secret) { + secrets[field.key] = emptySecret(configured.has(field.key)); + } else { + const raw = channel.config?.[field.key]; + values[field.key] = typeof raw === "string" ? raw : ""; + } + } + + const headerNames = new Set(channel.config?.headerNames ?? []); + for (const key of configured) { + if (key.startsWith(HEADER_SECRET_PREFIX)) { + headerNames.add(key.slice(HEADER_SECRET_PREFIX.length)); + } + } + + const headers: HeaderRowState[] = [...headerNames].map(name => ({ + id: nextHeaderRowId(), + name, + originalName: name, + value: "", + configured: configured.has(headerSecretKey(name)), + })); + + return { name: channel.name, values, secrets, headers }; +} + +function secretIsSatisfied(state: SecretFieldState): boolean { + if (state.value.trim()) return true; + return state.configured && !state.markedForRemoval; +} + +/** Returns the first validation error, or null when the form can be saved. */ +export function validateChannelForm( + state: ChannelFormState, + typeInfo: NotificationChannelTypeInfo +): string | null { + if (!state.name.trim()) { + return "Name is required"; + } + + for (const field of typeInfo.fields) { + if (!field.required) continue; + + if (field.secret) { + if (!secretIsSatisfied(state.secrets[field.key] ?? emptySecret(false))) { + return `${field.label} is required`; + } + } else if (!state.values[field.key]?.trim()) { + return `${field.label} is required`; + } + } + + if (typeInfo.supportsCustomHeaders) { + const seen = new Set(); + for (const row of state.headers) { + const name = row.name.trim(); + if (!name) { + return "Header name is required"; + } + if (seen.has(name.toLowerCase())) { + return `Duplicate header "${name}"`; + } + seen.add(name.toLowerCase()); + + // A renamed header cannot inherit the previous value. + const keepsStoredValue = row.configured && name === row.originalName; + if (!row.value.trim() && !keepsStoredValue) { + return `Value for header "${name}" is required`; + } + } + } + + return null; +} + +function collectConfig( + state: ChannelFormState, + fields: NotificationFormField[] +): Record { + const config: Record = {}; + for (const field of fields) { + if (field.secret) continue; + const value = state.values[field.key]?.trim(); + if (value) { + config[field.key] = value; + } + } + return config; +} + +function collectHeaders( + state: ChannelFormState, + typeInfo: NotificationChannelTypeInfo +): ChannelHeaderInput[] | undefined { + if (!typeInfo.supportsCustomHeaders) return undefined; + + return state.headers + .filter(row => row.name.trim()) + .map(row => { + const name = row.name.trim(); + const header: ChannelHeaderInput = { name }; + // Only send a value the user typed. An untouched, still-named header + // keeps whatever Core stores. + if (row.value.trim() || !(row.configured && name === row.originalName)) { + header.value = row.value; + } + return header; + }); +} + +export function buildCreatePayload( + state: ChannelFormState, + typeInfo: NotificationChannelTypeInfo +): CreateChannelRequest { + const secrets: Record = {}; + for (const [key, field] of Object.entries(state.secrets)) { + if (field.value.trim()) { + secrets[key] = field.value; + } + } + + const payload: CreateChannelRequest = { + name: state.name.trim(), + type: typeInfo.type, + config: collectConfig(state, typeInfo.fields), + secrets, + }; + + const headers = collectHeaders(state, typeInfo); + if (headers && headers.length > 0) { + payload.headers = headers; + } + + return payload; +} + +/** + * Update payload. Secret keys are present only when the user typed a + * replacement or explicitly asked for removal, so a metadata-only edit leaves + * every configured secret untouched. + */ +export function buildUpdatePayload( + state: ChannelFormState, + typeInfo: NotificationChannelTypeInfo +): UpdateChannelRequest { + const payload: UpdateChannelRequest = { + name: state.name.trim(), + config: collectConfig(state, typeInfo.fields), + }; + + const secrets: Record = {}; + const removeSecrets: string[] = []; + + for (const [key, field] of Object.entries(state.secrets)) { + if (field.value.trim()) { + secrets[key] = field.value; + } else if (field.markedForRemoval && field.configured) { + removeSecrets.push(key); + } + } + + if (Object.keys(secrets).length > 0) { + payload.secrets = secrets; + } + if (removeSecrets.length > 0) { + payload.removeSecrets = removeSecrets; + } + + const headers = collectHeaders(state, typeInfo); + if (headers) { + payload.headers = headers; + } + + return payload; +} + +/** Human-readable state of a secret input, used for the accessible status. */ +export function describeSecretState( + field: SecretFieldState +): "empty" | "configured" | "replacing" | "removing" { + if (field.value.trim()) return "replacing"; + if (field.markedForRemoval) return "removing"; + if (field.configured) return "configured"; + return "empty"; +} diff --git a/lib/services/__tests__/notifications.test.ts b/lib/services/__tests__/notifications.test.ts new file mode 100644 index 0000000..ed81c13 --- /dev/null +++ b/lib/services/__tests__/notifications.test.ts @@ -0,0 +1,144 @@ +import { describe, it, expect, beforeEach, vi } from "vitest"; +import { + notificationService, + redactChannel, + type NotificationChannel, +} from "../notifications"; +import api from "@/lib/api"; + +vi.mock("@/lib/api", () => ({ + default: { + get: vi.fn(), + post: vi.fn(), + put: vi.fn(), + delete: vi.fn(), + }, +})); + +const mockedApi = vi.mocked(api); + +function channel( + overrides: Partial = {} +): NotificationChannel { + return { + id: "ch-1", + userId: "user-1", + name: "Ops", + type: "slack", + config: {}, + configuredSecrets: ["webhook_url"], + enabled: true, + createdAt: "2026-01-01T00:00:00Z", + updatedAt: "2026-01-01T00:00:00Z", + ...overrides, + }; +} + +describe("redactChannel", () => { + it("drops secret keys a server may still echo back", () => { + const result = redactChannel( + channel({ + config: { webhook_url: "https://hooks.slack.com/secret" }, + }) + ); + + expect(result.config.webhook_url).toBeUndefined(); + expect(JSON.stringify(result)).not.toContain("secret"); + }); + + it("keeps non-secret metadata", () => { + const result = redactChannel( + channel({ type: "telegram", config: { chat_id: "-100" } }) + ); + + expect(result.config.chat_id).toBe("-100"); + }); + + it("reduces echoed header values to names", () => { + const result = redactChannel( + channel({ + type: "webhook", + config: { + url: "https://example.com/hook", + headers: { "X-Api-Key": "abc123" }, + }, + }) + ); + + expect(result.config.headers).toBeUndefined(); + expect(result.config.headerNames).toEqual(["X-Api-Key"]); + expect(JSON.stringify(result)).not.toContain("abc123"); + }); + + it("defaults configuredSecrets to an empty list", () => { + const result = redactChannel( + channel({ configuredSecrets: undefined as unknown as string[] }) + ); + + expect(result.configuredSecrets).toEqual([]); + }); +}); + +describe("notificationService", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("redacts every channel it lists", async () => { + mockedApi.get.mockResolvedValue({ + data: { + channels: [channel({ config: { webhook_url: "https://leak" } })], + }, + }); + + const channels = await notificationService.listChannels(); + + expect(channels[0].config.webhook_url).toBeUndefined(); + }); + + it("returns an empty list when the payload has none", async () => { + mockedApi.get.mockResolvedValue({ data: {} }); + + await expect(notificationService.listChannels()).resolves.toEqual([]); + }); + + it("posts the create request unchanged", async () => { + mockedApi.post.mockResolvedValue({ data: { channel: channel() } }); + + await notificationService.createChannel({ + name: "Ops", + type: "slack", + config: {}, + secrets: { webhook_url: "https://hooks.slack.com/new" }, + }); + + expect(mockedApi.post).toHaveBeenCalledWith("/notifications/channels", { + name: "Ops", + type: "slack", + config: {}, + secrets: { webhook_url: "https://hooks.slack.com/new" }, + }); + }); + + it("sends an update without secret keys when none changed", async () => { + mockedApi.put.mockResolvedValue({ data: { channel: channel() } }); + + await notificationService.updateChannel("ch-1", { + name: "Renamed", + config: {}, + }); + + expect(mockedApi.put).toHaveBeenCalledWith("/notifications/channels/ch-1", { + name: "Renamed", + config: {}, + }); + }); + + it("propagates update failures", async () => { + mockedApi.put.mockRejectedValue(new Error("boom")); + + await expect( + notificationService.updateChannel("ch-1", { name: "Renamed" }) + ).rejects.toThrow("boom"); + }); +}); diff --git a/lib/services/notifications.ts b/lib/services/notifications.ts index d13c0db..bb9c69a 100644 --- a/lib/services/notifications.ts +++ b/lib/services/notifications.ts @@ -1,48 +1,122 @@ import api from "@/lib/api"; import type { NotificationChannelType } from "@/lib/types/notification"; +import { isSecretKey } from "@/lib/types/notification"; + +/** + * Non-secret metadata returned by Core for a channel. Stored webhook URLs, + * tokens, routing keys and custom header values are never part of this + * payload — only the indicators below describe them. + */ +export interface RedactedChannelConfig { + [key: string]: unknown; + /** Names of the custom headers stored for this channel. Values are secret. */ + headerNames?: string[]; +} export interface NotificationChannel { id: string; userId: string; name: string; type: NotificationChannelType; - config: Record; + config: RedactedChannelConfig; + /** + * Keys of the secrets currently stored for this channel, e.g. + * `["webhook_url"]` or `["headers.Authorization"]`. Presence means + * "configured"; the value itself is never returned. + */ + configuredSecrets: string[]; enabled: boolean; createdAt: string; updatedAt: string; } +/** + * A custom header in a write request. Omitting `value` keeps whatever Core + * already stores for that header name; including it replaces the value. + * Headers absent from the array are removed. + */ +export interface ChannelHeaderInput { + name: string; + value?: string; +} + export interface CreateChannelRequest { name: string; type: NotificationChannelType; + /** Non-secret fields only. */ config: Record; + /** Write-only values. */ + secrets: Record; + headers?: ChannelHeaderInput[]; + enabled?: boolean; +} + +export interface UpdateChannelRequest { + name?: string; + config?: Record; + /** Only the secrets the user actually retyped. Omitted when none changed. */ + secrets?: Record; + /** Secret keys the user explicitly cleared. Omitted when none were. */ + removeSecrets?: string[]; + headers?: ChannelHeaderInput[]; enabled?: boolean; } +/** + * Defensive guard against a server that still echoes secrets back: anything + * registered as a secret for the channel type is dropped before the channel + * reaches the store, so a stored value can never land in component state. + */ +export function redactChannel( + channel: NotificationChannel +): NotificationChannel { + const rawConfig = (channel.config ?? {}) as RedactedChannelConfig; + const config: RedactedChannelConfig = {}; + + for (const [key, value] of Object.entries(rawConfig)) { + if (!isSecretKey(channel.type, key)) { + config[key] = value; + } + } + + if (!config.headerNames && rawConfig.headers) { + config.headerNames = Object.keys( + rawConfig.headers as Record + ); + } + + return { + ...channel, + config, + configuredSecrets: channel.configuredSecrets ?? [], + }; +} + class NotificationService { async listChannels(): Promise { const response = await api.get("/notifications/channels"); - return response.data.channels || []; + const channels: NotificationChannel[] = response.data.channels || []; + return channels.map(redactChannel); } async createChannel( data: CreateChannelRequest ): Promise { const response = await api.post("/notifications/channels", data); - return response.data.channel; + return redactChannel(response.data.channel); } async getChannel(id: string): Promise { const response = await api.get(`/notifications/channels/${id}`); - return response.data; + return redactChannel(response.data.channel ?? response.data); } async updateChannel( id: string, - data: CreateChannelRequest + data: UpdateChannelRequest ): Promise { const response = await api.put(`/notifications/channels/${id}`, data); - return response.data.channel; + return redactChannel(response.data.channel); } async deleteChannel(id: string): Promise { diff --git a/lib/types/notification.ts b/lib/types/notification.ts index d1143aa..c97590e 100644 --- a/lib/types/notification.ts +++ b/lib/types/notification.ts @@ -11,6 +11,8 @@ export interface NotificationChannelTypeInfo { name: string; description: string; fields: NotificationFormField[]; + /** Whether the type accepts user-defined HTTP headers. */ + supportsCustomHeaders?: boolean; helpLink?: { prefix: string; linkText: string; url: string }; } @@ -21,6 +23,19 @@ export interface NotificationFormField { placeholder: string; required: boolean; helpText?: string; + /** + * Write-only value. The stored value is never returned by Core, so the + * field starts empty on edit and is only sent when the user types a new + * value. + */ + secret: boolean; +} + +/** Prefix used to address a custom header value as a secret key. */ +export const HEADER_SECRET_PREFIX = "headers."; + +export function headerSecretKey(headerName: string): string { + return `${HEADER_SECRET_PREFIX}${headerName}`; } export const NOTIFICATION_CHANNEL_TYPES: NotificationChannelTypeInfo[] = [ @@ -35,6 +50,7 @@ export const NOTIFICATION_CHANNEL_TYPES: NotificationChannelTypeInfo[] = [ type: "password", placeholder: "https://hooks.slack.com/services/T.../B.../...", required: true, + secret: true, }, ], helpLink: { @@ -54,6 +70,7 @@ export const NOTIFICATION_CHANNEL_TYPES: NotificationChannelTypeInfo[] = [ type: "password", placeholder: "https://discord.com/api/webhooks/...", required: true, + secret: true, }, ], helpLink: { @@ -73,6 +90,7 @@ export const NOTIFICATION_CHANNEL_TYPES: NotificationChannelTypeInfo[] = [ type: "password", placeholder: "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11", required: true, + secret: true, }, { key: "chat_id", @@ -80,6 +98,7 @@ export const NOTIFICATION_CHANNEL_TYPES: NotificationChannelTypeInfo[] = [ type: "text", placeholder: "-1001234567890", required: true, + secret: false, helpText: "Use @userinfobot or @RawDataBot to find your chat ID", }, ], @@ -100,6 +119,7 @@ export const NOTIFICATION_CHANNEL_TYPES: NotificationChannelTypeInfo[] = [ type: "password", placeholder: "R0XXXXXXXXXXXXXXXXXXXXXXXXXX", required: true, + secret: true, helpText: "The 32-character integration key from your PagerDuty service", }, @@ -121,6 +141,7 @@ export const NOTIFICATION_CHANNEL_TYPES: NotificationChannelTypeInfo[] = [ type: "password", placeholder: "https://outlook.office.com/webhook/...", required: true, + secret: true, }, ], helpLink: { @@ -133,6 +154,7 @@ export const NOTIFICATION_CHANNEL_TYPES: NotificationChannelTypeInfo[] = [ type: "webhook", name: "Generic Webhook", description: "Send raw JSON alerts to any HTTP endpoint", + supportsCustomHeaders: true, fields: [ { key: "url", @@ -140,6 +162,7 @@ export const NOTIFICATION_CHANNEL_TYPES: NotificationChannelTypeInfo[] = [ type: "text", placeholder: "https://example.com/webhook", required: true, + secret: false, }, ], }, @@ -150,3 +173,20 @@ export function getNotificationTypeInfo( ): NotificationChannelTypeInfo | undefined { return NOTIFICATION_CHANNEL_TYPES.find(t => t.type === type); } + +/** Secret field keys declared for a channel type. */ +export function getSecretFieldKeys(type: NotificationChannelType): string[] { + return (getNotificationTypeInfo(type)?.fields ?? []) + .filter(field => field.secret) + .map(field => field.key); +} + +/** Every key whose value must never be read back from the API. */ +export function isSecretKey( + type: NotificationChannelType, + key: string +): boolean { + if (key === "headers") return true; + if (key.startsWith(HEADER_SECRET_PREFIX)) return true; + return getSecretFieldKeys(type).includes(key); +} diff --git a/stores/NotificationChannelStore.ts b/stores/NotificationChannelStore.ts index 167a7ff..6190a46 100644 --- a/stores/NotificationChannelStore.ts +++ b/stores/NotificationChannelStore.ts @@ -3,6 +3,7 @@ import { notificationService, type NotificationChannel, type CreateChannelRequest, + type UpdateChannelRequest, } from "@/lib/services/notifications"; import { toast } from "sonner"; @@ -13,7 +14,10 @@ type NotificationChannelStore = { fetchChannels: () => Promise; createChannel: (data: CreateChannelRequest) => Promise; - updateChannel: (id: string, data: CreateChannelRequest) => Promise; + updateChannel: ( + id: string, + data: UpdateChannelRequest + ) => Promise; deleteChannel: (id: string) => Promise; testChannel: (id: string) => Promise; }; @@ -42,9 +46,14 @@ export const useNotificationChannelStore = create()( }, updateChannel: async (id, data) => { - await notificationService.updateChannel(id, data); - get().fetchChannels(); + // Local state and the success toast only follow a resolved request, so a + // failed rotation never reads as a saved credential. + const channel = await notificationService.updateChannel(id, data); + set({ + channels: get().channels.map(c => (c.id === id ? channel : c)), + }); toast.success("Channel updated"); + return channel; }, deleteChannel: async id => { diff --git a/stores/__tests__/NotificationChannelStore.test.ts b/stores/__tests__/NotificationChannelStore.test.ts new file mode 100644 index 0000000..01d4667 --- /dev/null +++ b/stores/__tests__/NotificationChannelStore.test.ts @@ -0,0 +1,129 @@ +import { describe, it, expect, beforeEach, vi } from "vitest"; +import { useNotificationChannelStore } from "../NotificationChannelStore"; +import { notificationService } from "@/lib/services/notifications"; +import { toast } from "sonner"; +import type { NotificationChannel } from "@/lib/services/notifications"; + +vi.mock("@/lib/services/notifications", () => ({ + notificationService: { + listChannels: vi.fn(), + createChannel: vi.fn(), + updateChannel: vi.fn(), + deleteChannel: vi.fn(), + testChannel: vi.fn(), + }, +})); + +vi.mock("sonner", () => ({ + toast: { + success: vi.fn(), + error: vi.fn(), + }, +})); + +const mockedService = vi.mocked(notificationService); + +function channel( + overrides: Partial = {} +): NotificationChannel { + return { + id: "ch-1", + userId: "user-1", + name: "Ops", + type: "slack", + config: {}, + configuredSecrets: ["webhook_url"], + enabled: true, + createdAt: "2026-01-01T00:00:00Z", + updatedAt: "2026-01-01T00:00:00Z", + ...overrides, + }; +} + +describe("NotificationChannelStore", () => { + beforeEach(() => { + vi.clearAllMocks(); + useNotificationChannelStore.setState({ + channels: [], + isLoading: false, + error: null, + }); + }); + + it("stores the fetched channels", async () => { + mockedService.listChannels.mockResolvedValue([channel()]); + + await useNotificationChannelStore.getState().fetchChannels(); + + expect(useNotificationChannelStore.getState().channels).toHaveLength(1); + expect(useNotificationChannelStore.getState().error).toBeNull(); + }); + + it("records an error when the fetch fails", async () => { + mockedService.listChannels.mockRejectedValue(new Error("network")); + + await useNotificationChannelStore.getState().fetchChannels(); + + expect(useNotificationChannelStore.getState().error).toBe( + "Failed to fetch channels" + ); + expect(useNotificationChannelStore.getState().isLoading).toBe(false); + }); + + it("replaces the channel with the response on update", async () => { + useNotificationChannelStore.setState({ channels: [channel()] }); + mockedService.updateChannel.mockResolvedValue( + channel({ name: "Renamed", configuredSecrets: [] }) + ); + + await useNotificationChannelStore + .getState() + .updateChannel("ch-1", { name: "Renamed" }); + + const [updated] = useNotificationChannelStore.getState().channels; + expect(updated.name).toBe("Renamed"); + expect(updated.configuredSecrets).toEqual([]); + expect(toast.success).toHaveBeenCalledWith("Channel updated"); + }); + + it("does not report success when the update fails", async () => { + useNotificationChannelStore.setState({ channels: [channel()] }); + mockedService.updateChannel.mockRejectedValue(new Error("boom")); + + await expect( + useNotificationChannelStore + .getState() + .updateChannel("ch-1", { secrets: { webhook_url: "rotated" } }) + ).rejects.toThrow("boom"); + + expect(toast.success).not.toHaveBeenCalled(); + expect(useNotificationChannelStore.getState().channels[0].name).toBe("Ops"); + }); + + it("prepends a created channel", async () => { + useNotificationChannelStore.setState({ channels: [channel()] }); + mockedService.createChannel.mockResolvedValue( + channel({ id: "ch-2", name: "New" }) + ); + + await useNotificationChannelStore.getState().createChannel({ + name: "New", + type: "slack", + config: {}, + secrets: { webhook_url: "https://hooks.slack.com/new" }, + }); + + expect( + useNotificationChannelStore.getState().channels.map(c => c.id) + ).toEqual(["ch-2", "ch-1"]); + }); + + it("removes a deleted channel", async () => { + useNotificationChannelStore.setState({ channels: [channel()] }); + mockedService.deleteChannel.mockResolvedValue(undefined); + + await useNotificationChannelStore.getState().deleteChannel("ch-1"); + + expect(useNotificationChannelStore.getState().channels).toEqual([]); + }); +});