refactor(dashboard): move the webhook forms' URL check and field messages into helpers (KEA-9386)

The inline validation added to the Custom, Slack and Discord forms pushed
their components over the complexity ratchet (new-code mode): function
length, cyclomatic and cognitive complexity.

No behaviour change. The debounced server check the three forms each
carried a copy of becomes the `useWebhookUrlCheck` hook, and what a field
shows under itself is derived by pure helpers in webhookFieldValidation.ts
(`webhookUrlFieldFeedback`, `webhookSecretFieldError`).
This commit is contained in:
diegosouzapw
2026-11-20 20:48:41 -03:00
parent 5454b20a1c
commit 997e83f685
5 changed files with 149 additions and 199 deletions

View File

@@ -1,15 +1,10 @@
"use client";
import { useEffect, useState } from "react";
import { useTranslations } from "next-intl";
import Input from "@/shared/components/Input";
import { WEBHOOK_SECRET_MAX_LENGTH } from "@/shared/constants/formLimits";
import { HmacRecipeBlock } from "../../shared/HmacRecipeBlock";
import {
webhookSecretTooLong,
webhookUrlFieldError,
webhookUrlProblem,
} from "../../../webhookFieldValidation";
import { webhookSecretFieldError, webhookUrlFieldFeedback } from "../../../webhookFieldValidation";
import { useWebhookUrlCheck } from "./useWebhookUrlCheck";
export interface CustomConfig {
endpointUrl: string;
@@ -25,8 +20,6 @@ interface CustomConfigFormProps {
showRequired?: boolean;
}
type UrlState = "idle" | "checking" | "ok" | "blocked" | "invalid";
export function CustomConfigForm({
value,
onChange,
@@ -35,67 +28,17 @@ export function CustomConfigForm({
showRequired,
}: CustomConfigFormProps) {
const tv = useTranslations("formValidation");
const [urlState, setUrlState] = useState<UrlState>("idle");
useEffect(() => {
const url = value.endpointUrl.trim();
const controller = new AbortController();
const askServer = webhookUrlProblem(value.endpointUrl) === null;
const delay = askServer ? 600 : 0;
const timer = setTimeout(async () => {
if (!askServer) {
setUrlState("idle");
return;
}
setUrlState("checking");
try {
const res = await fetch("/api/webhooks/validate-url", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ url }),
signal: controller.signal,
});
const data = await res.json().catch(() => ({}));
setUrlState(data.valid ? "ok" : data.reason === "blocked_private" ? "blocked" : "invalid");
} catch {
if (!controller.signal.aborted) setUrlState("invalid");
}
}, delay);
return () => {
clearTimeout(timer);
controller.abort();
};
}, [value.endpointUrl]);
const urlHint =
urlState === "checking"
? t("validateUrl.checking")
: urlState === "ok"
? t("validateUrl.ok")
: urlState === "blocked"
? t("validateUrl.blockedPrivate")
: urlState === "invalid" && value.endpointUrl.trim()
? t("validateUrl.invalidUrl")
: "";
// Empty, over the limit or not an http(s) URL is said at once, without a round trip; the
// server's verdict (blocked private address) follows for a value that passes.
const urlError =
webhookUrlFieldError(value.endpointUrl, {
label: t("custom.endpointUrl"),
showRequired,
t,
tv,
}) ?? (urlHint && urlState !== "ok" && urlState !== "checking" ? urlHint : undefined);
// Over the route's limit the key is flagged, never cut: a truncated signing key would sign
// payloads the receiver cannot verify.
const secretError = webhookSecretTooLong(value.secretKey)
? tv("maxLength", {
field: t("custom.secretKey"),
max: WEBHOOK_SECRET_MAX_LENGTH,
count: value.secretKey.trim().length,
})
: undefined;
const urlState = useWebhookUrlCheck(value.endpointUrl);
const url = webhookUrlFieldFeedback(value.endpointUrl, urlState, {
label: t("custom.endpointUrl"),
showRequired,
t,
tv,
});
const secretError = webhookSecretFieldError(value.secretKey, {
label: t("custom.secretKey"),
tv,
});
return (
<div className="space-y-4">
@@ -105,11 +48,13 @@ export function CustomConfigForm({
onChange={(e) => onChange({ ...value, endpointUrl: e.target.value })}
placeholder={t("custom.endpointUrlPlaceholder")}
required
error={urlError}
error={url.error}
hint={
<>
{urlHint && (urlState === "ok" || urlState === "checking") && (
<span className={`block ${urlState === "ok" ? "text-success" : ""}`}>{urlHint}</span>
{url.status && (
<span className={`block ${urlState === "ok" ? "text-success" : ""}`}>
{url.status}
</span>
)}
</>
}

View File

@@ -1,10 +1,10 @@
"use client";
import { Disclosure, DisclosureContent, DisclosureTrigger } from "@omniroute/ui-kit/disclosure";
import { useEffect, useState } from "react";
import { useTranslations } from "next-intl";
import Input from "@/shared/components/Input";
import { webhookUrlFieldError, webhookUrlProblem } from "../../../webhookFieldValidation";
import { webhookUrlFieldFeedback } from "../../../webhookFieldValidation";
import { useWebhookUrlCheck } from "./useWebhookUrlCheck";
export interface DiscordConfig {
webhookUrl: string;
@@ -18,60 +18,15 @@ interface DiscordConfigFormProps {
showRequired?: boolean;
}
type UrlState = "idle" | "checking" | "ok" | "blocked" | "invalid";
export function DiscordConfigForm({ value, onChange, t, showRequired }: DiscordConfigFormProps) {
const tv = useTranslations("formValidation");
const [urlState, setUrlState] = useState<UrlState>("idle");
useEffect(() => {
const url = value.webhookUrl.trim();
const controller = new AbortController();
const askServer = webhookUrlProblem(value.webhookUrl) === null;
const delay = askServer ? 600 : 0;
const timer = setTimeout(async () => {
if (!askServer) {
setUrlState("idle");
return;
}
setUrlState("checking");
try {
const res = await fetch("/api/webhooks/validate-url", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ url }),
signal: controller.signal,
});
const data = await res.json().catch(() => ({}));
setUrlState(data.valid ? "ok" : data.reason === "blocked_private" ? "blocked" : "invalid");
} catch {
if (!controller.signal.aborted) setUrlState("invalid");
}
}, delay);
return () => {
clearTimeout(timer);
controller.abort();
};
}, [value.webhookUrl]);
const urlHint =
urlState === "checking"
? t("validateUrl.checking")
: urlState === "ok"
? t("validateUrl.ok")
: urlState === "blocked"
? t("validateUrl.blockedPrivate")
: urlState === "invalid" && value.webhookUrl.trim()
? t("validateUrl.invalidUrl")
: "";
const urlError =
webhookUrlFieldError(value.webhookUrl, {
label: t("discord.webhookUrl"),
showRequired,
t,
tv,
}) ?? (urlHint && urlState !== "ok" && urlState !== "checking" ? urlHint : undefined);
const urlState = useWebhookUrlCheck(value.webhookUrl);
const url = webhookUrlFieldFeedback(value.webhookUrl, urlState, {
label: t("discord.webhookUrl"),
showRequired,
t,
tv,
});
return (
<div className="space-y-4">
@@ -81,11 +36,13 @@ export function DiscordConfigForm({ value, onChange, t, showRequired }: DiscordC
onChange={(e) => onChange({ webhookUrl: e.target.value })}
placeholder={t("discord.webhookUrlPlaceholder")}
required
error={urlError}
error={url.error}
hint={
<>
{urlHint && (urlState === "ok" || urlState === "checking") && (
<span className={`block ${urlState === "ok" ? "text-success" : ""}`}>{urlHint}</span>
{url.status && (
<span className={`block ${urlState === "ok" ? "text-success" : ""}`}>
{url.status}
</span>
)}
<span className="block">{t("discord.webhookUrlHint")}</span>
</>

View File

@@ -1,10 +1,10 @@
"use client";
import { Disclosure, DisclosureContent, DisclosureTrigger } from "@omniroute/ui-kit/disclosure";
import { useEffect, useState } from "react";
import { useTranslations } from "next-intl";
import Input from "@/shared/components/Input";
import { webhookUrlFieldError, webhookUrlProblem } from "../../../webhookFieldValidation";
import { webhookUrlFieldFeedback } from "../../../webhookFieldValidation";
import { useWebhookUrlCheck } from "./useWebhookUrlCheck";
export interface SlackConfig {
webhookUrl: string;
@@ -18,60 +18,15 @@ interface SlackConfigFormProps {
showRequired?: boolean;
}
type UrlState = "idle" | "checking" | "ok" | "blocked" | "invalid";
export function SlackConfigForm({ value, onChange, t, showRequired }: SlackConfigFormProps) {
const tv = useTranslations("formValidation");
const [urlState, setUrlState] = useState<UrlState>("idle");
useEffect(() => {
const url = value.webhookUrl.trim();
const controller = new AbortController();
const askServer = webhookUrlProblem(value.webhookUrl) === null;
const delay = askServer ? 600 : 0;
const timer = setTimeout(async () => {
if (!askServer) {
setUrlState("idle");
return;
}
setUrlState("checking");
try {
const res = await fetch("/api/webhooks/validate-url", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ url }),
signal: controller.signal,
});
const data = await res.json().catch(() => ({}));
setUrlState(data.valid ? "ok" : data.reason === "blocked_private" ? "blocked" : "invalid");
} catch {
if (!controller.signal.aborted) setUrlState("invalid");
}
}, delay);
return () => {
clearTimeout(timer);
controller.abort();
};
}, [value.webhookUrl]);
const urlHint =
urlState === "checking"
? t("validateUrl.checking")
: urlState === "ok"
? t("validateUrl.ok")
: urlState === "blocked"
? t("validateUrl.blockedPrivate")
: urlState === "invalid" && value.webhookUrl.trim()
? t("validateUrl.invalidUrl")
: "";
const urlError =
webhookUrlFieldError(value.webhookUrl, {
label: t("slack.webhookUrl"),
showRequired,
t,
tv,
}) ?? (urlHint && urlState !== "ok" && urlState !== "checking" ? urlHint : undefined);
const urlState = useWebhookUrlCheck(value.webhookUrl);
const url = webhookUrlFieldFeedback(value.webhookUrl, urlState, {
label: t("slack.webhookUrl"),
showRequired,
t,
tv,
});
return (
<div className="space-y-4">
@@ -81,11 +36,13 @@ export function SlackConfigForm({ value, onChange, t, showRequired }: SlackConfi
onChange={(e) => onChange({ webhookUrl: e.target.value })}
placeholder={t("slack.webhookUrlPlaceholder")}
required
error={urlError}
error={url.error}
hint={
<>
{urlHint && (urlState === "ok" || urlState === "checking") && (
<span className={`block ${urlState === "ok" ? "text-success" : ""}`}>{urlHint}</span>
{url.status && (
<span className={`block ${urlState === "ok" ? "text-success" : ""}`}>
{url.status}
</span>
)}
<span className="block">{t("slack.webhookUrlHint")}</span>
</>

View File

@@ -0,0 +1,45 @@
"use client";
import { useEffect, useState } from "react";
import { webhookUrlProblem, type WebhookUrlCheckState } from "../../../webhookFieldValidation";
/**
* Asks the server whether a destination is allowed (it refuses private addresses), 600 ms after
* the last keystroke. A value that is empty, over the limit or not an http(s) URL is never
* sent: the field says so itself.
*/
export function useWebhookUrlCheck(value: string): WebhookUrlCheckState {
const [urlState, setUrlState] = useState<WebhookUrlCheckState>("idle");
useEffect(() => {
const url = value.trim();
const controller = new AbortController();
const askServer = webhookUrlProblem(value) === null;
const delay = askServer ? 600 : 0;
const timer = setTimeout(async () => {
if (!askServer) {
setUrlState("idle");
return;
}
setUrlState("checking");
try {
const res = await fetch("/api/webhooks/validate-url", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ url }),
signal: controller.signal,
});
const data = await res.json().catch(() => ({}));
setUrlState(data.valid ? "ok" : data.reason === "blocked_private" ? "blocked" : "invalid");
} catch {
if (!controller.signal.aborted) setUrlState("invalid");
}
}, delay);
return () => {
clearTimeout(timer);
controller.abort();
};
}, [value]);
return urlState;
}

View File

@@ -2,6 +2,9 @@ import { WEBHOOK_SECRET_MAX_LENGTH, WEBHOOK_URL_MAX_LENGTH } from "@/shared/cons
export type WebhookUrlProblem = "required" | "tooLong" | "invalid";
/** Where the server's check of a destination stands (see `useWebhookUrlCheck`). */
export type WebhookUrlCheckState = "idle" | "checking" | "ok" | "blocked" | "invalid";
/**
* What is wrong with a webhook destination before the server is asked: empty, over the route's
* length limit, or not an http(s) URL (the first thing the outbound guard refuses). `null` means
@@ -23,23 +26,22 @@ export function webhookUrlProblem(value: string): WebhookUrlProblem | null {
type Translate = (key: string, values?: Record<string, string | number>) => string;
interface WebhookUrlFieldOptions {
/** The field's visible label, named in the message. */
label: string;
showRequired?: boolean;
/** The `webhooks` translator the wizard is given. */
t: Translate;
/** The shared `formValidation` translator. */
tv: Translate;
}
/**
* The inline message for a destination field, or `undefined` when the value can go to the
* server check. "Required" is only said once the user has tried to continue (`showRequired`);
* a malformed or over-long value is said as it is typed.
*/
export function webhookUrlFieldError(
value: string,
options: {
/** The field's visible label, named in the message. */
label: string;
showRequired?: boolean;
/** The `webhooks` translator the wizard is given. */
t: Translate;
/** The shared `formValidation` translator. */
tv: Translate;
}
): string | undefined {
function webhookUrlFieldError(value: string, options: WebhookUrlFieldOptions): string | undefined {
const problem = webhookUrlProblem(value);
if (problem === "tooLong") {
return options.tv("maxLength", {
@@ -55,11 +57,55 @@ export function webhookUrlFieldError(
return undefined;
}
/** The server check's verdict in words; empty while there is nothing to say. */
function webhookUrlCheckText(state: WebhookUrlCheckState, value: string, t: Translate): string {
if (state === "checking") return t("validateUrl.checking");
if (state === "ok") return t("validateUrl.ok");
if (state === "blocked") return t("validateUrl.blockedPrivate");
if (state === "invalid" && value.trim()) return t("validateUrl.invalidUrl");
return "";
}
/**
* What a destination field shows under itself. `error` is the field's own verdict (empty, over
* the limit, not an http(s) URL — said at once, without a round trip) or, for a value that
* passes it, the server's refusal. `status` is the server check while it runs or once it
* accepted the value; empty otherwise.
*/
export function webhookUrlFieldFeedback(
value: string,
state: WebhookUrlCheckState,
options: WebhookUrlFieldOptions
): { error: string | undefined; status: string } {
const text = webhookUrlCheckText(state, value, options.t);
const pendingOrAccepted = state === "ok" || state === "checking";
return {
error: webhookUrlFieldError(value, options) ?? (text && !pendingOrAccepted ? text : undefined),
status: pendingOrAccepted ? text : "",
};
}
/** The signing secret is sent trimmed; over the route's limit it is refused, never cut. */
export function webhookSecretTooLong(value: string): boolean {
return value.trim().length > WEBHOOK_SECRET_MAX_LENGTH;
}
/**
* The inline message for a signing secret over the route's limit. The key is flagged, never
* cut: a truncated signing key would sign payloads the receiver cannot verify.
*/
export function webhookSecretFieldError(
value: string,
options: { label: string; tv: Translate }
): string | undefined {
if (!webhookSecretTooLong(value)) return undefined;
return options.tv("maxLength", {
field: options.label,
max: WEBHOOK_SECRET_MAX_LENGTH,
count: value.trim().length,
});
}
/**
* Text of the `error` field of a webhooks API reply. A validation failure arrives as an object
* (`{ message, details: [{ field, message }] }`), which must not reach the UI as