Skip to content

Open-source status page, incident response and uptime monitoring

Extract header pair validation into shared schema (#2773)

Maximilian Kasked4a03396acd9
diff --git a/apps/dashboard/src/components/forms/monitor/form-general.tsx b/apps/dashboard/src/components/forms/monitor/form-general.tsx
index 6ccdadbbc..a86175cea 100644
--- a/apps/dashboard/src/components/forms/monitor/form-general.tsx
+++ b/apps/dashboard/src/components/forms/monitor/form-general.tsx
@@ -65,9 +65,10 @@ import {
TooltipTrigger,
} from "@openstatus/ui/components/ui/tooltip";
import { cn } from "@openstatus/ui/lib/utils";
+import { headerPairSchema } from "@openstatus/utils";
import { isTRPCClientError } from "@trpc/client";
import { useEffect, useState, useTransition } from "react";
-import { useForm } from "react-hook-form";
+import { useFieldArray, useForm } from "react-hook-form";
import { toast } from "sonner";
import { z } from "zod";
@@ -97,12 +98,7 @@ const schema = z.object({
type: z.enum(TYPES),
method: z.enum(monitorMethods),
url: z.string().min(1, "URL is required"),
- headers: z.array(
- z.object({
- key: z.string(),
- value: z.string(),
- }),
- ),
+ headers: z.array(headerPairSchema),
active: z.boolean().prefault(true),
assertions: z.array(
z.discriminatedUnion("type", [
@@ -150,6 +146,17 @@ export function FormGeneral({
saveCheck: false,
},
});
+ // Stable row ids so removing a row remounts the shifted controllers.
+ const {
+ fields: headerFields,
+ append: appendHeader,
+ remove: removeHeader,
+ } = useFieldArray({ control: form.control, name: "headers" });
+ const {
+ fields: assertionFields,
+ append: appendAssertion,
+ remove: removeAssertion,
+ } = useFieldArray({ control: form.control, name: "assertions" });
const [isPending, startTransition] = useTransition();
const watchType = form.watch("type");
const watchMethod = form.watch("method");
@@ -410,74 +417,56 @@ export function FormGeneral({
)}
/>
</div>
- <FormField
- control={form.control}
- name="headers"
- render={({ field }) => (
- <FormItem className="col-span-full">
- <FormLabel>Request Headers</FormLabel>
- {field.value.map((header, index) => (
- <div key={index} className="grid gap-2 sm:grid-cols-5">
- <Input
- placeholder="Key"
- className="col-span-2"
- value={header.key}
- onChange={(e) => {
- const newHeaders = [...field.value];
- newHeaders[index] = {
- ...newHeaders[index],
- key: e.target.value,
- };
- field.onChange(newHeaders);
- }}
- />
- <Input
- placeholder="Value"
- className="col-span-2"
- value={header.value}
- onChange={(e) => {
- const newHeaders = [...field.value];
- newHeaders[index] = {
- ...newHeaders[index],
- value: e.target.value,
- };
- field.onChange(newHeaders);
- }}
- />
- <Button
- size="icon"
- variant="ghost"
- onClick={() => {
- const newHeaders = field.value.filter(
- (_, i) => i !== index,
- );
- field.onChange(newHeaders);
- }}
- >
- <Close />
- </Button>
- </div>
- ))}
- <div>
- <Button
- size="sm"
- variant="outline"
- type="button"
- onClick={() => {
- field.onChange([
- ...field.value,
- { key: "", value: "" },
- ]);
- }}
- >
- <Add />
- Add Header
- </Button>
- </div>
- <FormMessage />
- </FormItem>
- )}
- />
+ <FormItem className="col-span-full">
+ <FormLabel>Request Headers</FormLabel>
+ {headerFields.map((row, index) => (
+ <div key={row.id} className="grid gap-2 sm:grid-cols-5">
+ <FormField
+ control={form.control}
+ name={`headers.${index}.key`}
+ render={({ field }) => (
+ <FormItem className="col-span-2">
+ <FormControl>
+ <Input placeholder="Key" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name={`headers.${index}.value`}
+ render={({ field }) => (
+ <FormItem className="col-span-2">
+ <FormControl>
+ <Input placeholder="Value" {...field} />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ <Button
+ size="icon"
+ variant="ghost"
+ type="button"
+ aria-label="Remove header"
+ onClick={() => removeHeader(index)}
+ >
+ <Close />
+ </Button>
+ </div>
+ ))}
+ <div>
+ <Button
+ size="sm"
+ variant="outline"
+ type="button"
+ onClick={() => appendHeader({ key: "", value: "" })}
+ >
+ <Add />
+ Add Header
+ </Button>
+ </div>
+ </FormItem>
{["POST", "PUT", "PATCH", "DELETE"].includes(watchMethod) && (
<FormField
control={form.control}
@@ -497,215 +486,188 @@ export function FormGeneral({
</FormCardContent>
<FormCardSeparator />
<FormCardContent>
- <FormField
- control={form.control}
- name="assertions"
- render={({ field }) => (
- <FormItem className="col-span-full">
- <FormLabel>Assertions</FormLabel>
- <FormDescription>
- Validate the response to ensure your service is working
- as expected. <br />
- Add body, header, or status assertions.
- </FormDescription>
- {field.value.map((assertion, index) => (
- <div key={index} className="grid gap-2 sm:grid-cols-6">
- <FormField
- control={form.control}
- name={`assertions.${index}.type`}
- render={({ field }) => (
- <FormItem>
- <Select
- value={field.value}
- onValueChange={field.onChange}
- disabled={true}
- >
- <SelectTrigger
- aria-invalid={
- !!form.formState.errors.assertions?.[
- index
- ]?.type
- }
- className="w-full"
- >
- <SelectValue placeholder="Select type" />
- </SelectTrigger>
- <SelectContent>
- {HTTP_ASSERTION_TYPES.map((type) => (
- <SelectItem key={type} value={type}>
- {type}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name={`assertions.${index}.compare`}
- render={({ field }) => (
- <FormItem>
- <Select
- value={field.value}
- onValueChange={field.onChange}
- >
- <SelectTrigger className="w-full min-w-16">
- <span className="truncate">
- <SelectValue placeholder="Select compare" />
- </span>
- </SelectTrigger>
- <SelectContent>
- {assertion.type === "status"
- ? Object.entries(
- numberCompareDictionary,
- ).map(([key, value]) => (
- <SelectItem key={key} value={key}>
- {value}
- </SelectItem>
- ))
- : Object.entries(
- stringCompareDictionary,
- ).map(([key, value]) => (
- <SelectItem key={key} value={key}>
- {value}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- <FormMessage />
- </FormItem>
- )}
- />
- {assertion.type === "header" && (
- <FormField
- control={form.control}
- name={`assertions.${index}.key`}
- render={({ field }) => (
- <FormItem>
- <Input
- placeholder="Header key"
- className="w-full"
- {...field}
- value={field.value as string}
- />
- <FormMessage />
- </FormItem>
- )}
- />
+ <FormItem className="col-span-full">
+ <FormLabel>Assertions</FormLabel>
+ <FormDescription>
+ Validate the response to ensure your service is working as
+ expected. <br />
+ Add body, header, or status assertions.
+ </FormDescription>
+ {assertionFields.map((assertion, index) => (
+ <div
+ key={assertion.id}
+ className="grid gap-2 sm:grid-cols-6"
+ >
+ <FormField
+ control={form.control}
+ name={`assertions.${index}.type`}
+ render={({ field }) => (
+ <FormItem>
+ <Select
+ value={field.value}
+ onValueChange={field.onChange}
+ disabled={true}
+ >
+ <SelectTrigger
+ aria-invalid={
+ !!form.formState.errors.assertions?.[index]
+ ?.type
+ }
+ className="w-full"
+ >
+ <SelectValue placeholder="Select type" />
+ </SelectTrigger>
+ <SelectContent>
+ {HTTP_ASSERTION_TYPES.map((type) => (
+ <SelectItem key={type} value={type}>
+ {type}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name={`assertions.${index}.compare`}
+ render={({ field }) => (
+ <FormItem>
+ <Select
+ value={field.value}
+ onValueChange={field.onChange}
+ >
+ <SelectTrigger className="w-full min-w-16">
+ <span className="truncate">
+ <SelectValue placeholder="Select compare" />
+ </span>
+ </SelectTrigger>
+ <SelectContent>
+ {assertion.type === "status"
+ ? Object.entries(numberCompareDictionary).map(
+ ([key, value]) => (
+ <SelectItem key={key} value={key}>
+ {value}
+ </SelectItem>
+ ),
+ )
+ : Object.entries(stringCompareDictionary).map(
+ ([key, value]) => (
+ <SelectItem key={key} value={key}>
+ {value}
+ </SelectItem>
+ ),
+ )}
+ </SelectContent>
+ </Select>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ {assertion.type === "header" && (
+ <FormField
+ control={form.control}
+ name={`assertions.${index}.key`}
+ render={({ field }) => (
+ <FormItem>
+ <Input
+ placeholder="Header key"
+ className="w-full"
+ {...field}
+ value={field.value as string}
+ />
+ <FormMessage />
+ </FormItem>
)}
- <FormField
- control={form.control}
- name={`assertions.${index}.target`}
- render={({ field }) => (
- <FormItem>
- <Input
- placeholder="Target value"
- className="w-full"
- type={
- assertion.type === "status"
- ? "number"
- : "text"
- }
- {...field}
- value={field.value?.toString() || ""}
- onChange={(e) => {
- const value =
- assertion.type === "status"
- ? Number.parseInt(e.target.value) || 0
- : e.target.value;
- field.onChange(value);
- }}
- />
- <FormMessage />
- </FormItem>
- )}
- />
- <Button
- size="icon"
- variant="ghost"
- type="button"
- onClick={() => {
- const newAssertions = field.value.filter(
- (_, i) => i !== index,
- );
- field.onChange(newAssertions);
- }}
- >
- <Close />
- </Button>
- </div>
- ))}
- <div className="flex flex-wrap gap-2">
- <Button
- size="sm"
- variant="outline"
- type="button"
- onClick={() => {
- const currentAssertions =
- form.getValues("assertions");
- field.onChange([
- ...currentAssertions,
- {
- type: "status",
- version: "v1",
- compare: "eq",
- target: 200,
- },
- ]);
- }}
- >
- <Add />
- Add Status Assertion
- </Button>
- <Button
- size="sm"
- variant="outline"
- type="button"
- onClick={() => {
- const currentAssertions =
- form.getValues("assertions");
- field.onChange([
- ...currentAssertions,
- {
- type: "header",
- version: "v1",
- compare: "eq",
- key: "",
- target: "",
- },
- ]);
- }}
- >
- <Add />
- Add Header Assertion
- </Button>
- <Button
- size="sm"
- variant="outline"
- type="button"
- onClick={() => {
- const currentAssertions =
- form.getValues("assertions");
- field.onChange([
- ...currentAssertions,
- {
- type: "textBody",
- version: "v1",
- compare: "eq",
- target: "",
- },
- ]);
- }}
- >
- <Add />
- Add Body Assertion
- </Button>
- </div>
- <FormMessage />
- </FormItem>
- )}
- />
+ />
+ )}
+ <FormField
+ control={form.control}
+ name={`assertions.${index}.target`}
+ render={({ field }) => (
+ <FormItem>
+ <Input
+ placeholder="Target value"
+ className="w-full"
+ type={
+ assertion.type === "status" ? "number" : "text"
+ }
+ {...field}
+ value={field.value?.toString() || ""}
+ onChange={(e) => {
+ const value =
+ assertion.type === "status"
+ ? Number.parseInt(e.target.value) || 0
+ : e.target.value;
+ field.onChange(value);
+ }}
+ />
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <Button
+ size="icon"
+ variant="ghost"
+ type="button"
+ onClick={() => removeAssertion(index)}
+ >
+ <Close />
+ </Button>
+ </div>
+ ))}
+ <div className="flex flex-wrap gap-2">
+ <Button
+ size="sm"
+ variant="outline"
+ type="button"
+ onClick={() =>
+ appendAssertion({
+ type: "status",
+ version: "v1",
+ compare: "eq",
+ target: 200,
+ })
+ }
+ >
+ <Add />
+ Add Status Assertion
+ </Button>
+ <Button
+ size="sm"
+ variant="outline"
+ type="button"
+ onClick={() =>
+ appendAssertion({
+ type: "header",
+ version: "v1",
+ compare: "eq",
+ key: "",
+ target: "",
+ })
+ }
+ >
+ <Add />
+ Add Header Assertion
+ </Button>
+ <Button
+ size="sm"
+ variant="outline"
+ type="button"
+ onClick={() =>
+ appendAssertion({
+ type: "textBody",
+ version: "v1",
+ compare: "eq",
+ target: "",
+ })
+ }
+ >
+ <Add />
+ Add Body Assertion
+ </Button>
+ </div>
+ </FormItem>
</FormCardContent>
</>
)}
@@ -863,76 +825,60 @@ export function FormGeneral({
</FormItem>
)}
/>
- <FormField
- control={form.control}
- name="headers"
- render={({ field }) => (
- <FormItem className="col-span-full">
- <FormLabel>Metadata</FormLabel>
- {field.value.map((header, index) => (
- <div key={index} className="grid gap-2 sm:grid-cols-5">
- <Input
- placeholder="Key"
- className="col-span-2"
- value={header.key}
- onChange={(e) => {
- const newHeaders = [...field.value];
- newHeaders[index] = {
- ...newHeaders[index],
- key: e.target.value,
- };
- field.onChange(newHeaders);
- }}
- />
- <Input
- placeholder="Value"
- className="col-span-2"
- value={header.value}
- onChange={(e) => {
- const newHeaders = [...field.value];
- newHeaders[index] = {
- ...newHeaders[index],
- value: e.target.value,
- };
- field.onChange(newHeaders);
- }}
- />
- <Button
- size="icon"
- variant="ghost"
- onClick={() => {
- field.onChange(
- field.value.filter((_, i) => i !== index),
- );
- }}
- >
- <Close />
- </Button>
- </div>
- ))}
- <div>
- <Button
- size="sm"
- variant="outline"
- type="button"
- onClick={() => {
- field.onChange([
- ...field.value,
- { key: "", value: "" },
- ]);
- }}
- >
- <Add />
- Add Metadata
- </Button>
- </div>
- <FormDescription>
- Sent with the health check request, commonly for
- authentication.
- </FormDescription>
- </FormItem>
- )}
- />
+ <FormItem className="col-span-full">
+ <FormLabel>Metadata</FormLabel>
+ {headerFields.map((row, index) => (
+ <div key={row.id} className="grid gap-2 sm:grid-cols-5">
+ <FormField
+ control={form.control}
+ name={`headers.${index}.key`}
+ render={({ field }) => (
+ <FormItem className="col-span-2">
+ <FormControl>
+ <Input placeholder="Key" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name={`headers.${index}.value`}
+ render={({ field }) => (
+ <FormItem className="col-span-2">
+ <FormControl>
+ <Input placeholder="Value" {...field} />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ <Button
+ size="icon"
+ variant="ghost"
+ type="button"
+ aria-label="Remove header"
+ onClick={() => removeHeader(index)}
+ >
+ <Close />
+ </Button>
+ </div>
+ ))}
+ <div>
+ <Button
+ size="sm"
+ variant="outline"
+ type="button"
+ onClick={() => appendHeader({ key: "", value: "" })}
+ >
+ <Add />
+ Add Metadata
+ </Button>
+ </div>
+ <FormDescription>
+ Sent with the health check request, commonly for
+ authentication.
+ </FormDescription>
+ </FormItem>
</FormCardContent>
)}
{watchType === "dns" && (
@@ -957,182 +903,165 @@ export function FormGeneral({
</FormCardContent>
<FormCardSeparator />
<FormCardContent>
- <FormField
- control={form.control}
- name="assertions"
- render={({ field }) => (
- <FormItem className="col-span-full">
- <FormLabel>Assertions</FormLabel>
- <FormDescription>
- Validate the response to ensure your service is working
- as expected. <br />
- Add DNS record assertions.
- </FormDescription>
- {field.value.map((assertion, index) => (
- <div key={index} className="grid gap-2 sm:grid-cols-6">
- <FormField
- control={form.control}
- name={`assertions.${index}.type`}
- defaultValue={"dnsRecord"}
- render={({ field }) => (
- <FormItem className="hidden">
- <Select
- value={field.value}
- onValueChange={field.onChange}
- disabled
- >
- <SelectTrigger className="w-full">
- <SelectValue placeholder="Select type" />
- </SelectTrigger>
- </Select>
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name={`assertions.${index}.key`}
- render={({ field }) => (
- <FormItem>
- <Select
- value={field.value as string}
- onValueChange={field.onChange}
- >
- <SelectTrigger
- aria-invalid={
- !!form.formState.errors.assertions?.[
- index
- ]?.type
- }
- className="w-full"
- >
- <SelectValue placeholder="Select type" />
- </SelectTrigger>
- <SelectContent>
- {DNS_ASSERTION_TYPES.map((type) => (
- <SelectItem key={type} value={type}>
- {type}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name={`assertions.${index}.compare`}
- render={({ field }) => (
- <FormItem>
- <Select
- value={field.value}
- onValueChange={field.onChange}
- >
- <SelectTrigger className="w-full min-w-16">
- <span className="truncate">
- <SelectValue placeholder="Select compare" />
- </span>
- </SelectTrigger>
- <SelectContent>
- {Object.entries(
- recordCompareDictionary,
- ).map(([key, value]) => (
- <SelectItem key={key} value={key}>
- {value}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- <FormMessage />
- </FormItem>
- )}
- />
- {assertion.type === "header" && (
- <FormField
- control={form.control}
- name={`assertions.${index}.key`}
- render={({ field }) => (
- <FormItem>
- <Input
- placeholder="Header key"
- className="w-full"
- {...field}
- value={field.value as string}
- />
- <FormMessage />
- </FormItem>
- )}
- />
+ <FormItem className="col-span-full">
+ <FormLabel>Assertions</FormLabel>
+ <FormDescription>
+ Validate the response to ensure your service is working as
+ expected. <br />
+ Add DNS record assertions.
+ </FormDescription>
+ {assertionFields.map((assertion, index) => (
+ <div
+ key={assertion.id}
+ className="grid gap-2 sm:grid-cols-6"
+ >
+ <FormField
+ control={form.control}
+ name={`assertions.${index}.type`}
+ defaultValue={"dnsRecord"}
+ render={({ field }) => (
+ <FormItem className="hidden">
+ <Select
+ value={field.value}
+ onValueChange={field.onChange}
+ disabled
+ >
+ <SelectTrigger className="w-full">
+ <SelectValue placeholder="Select type" />
+ </SelectTrigger>
+ </Select>
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name={`assertions.${index}.key`}
+ render={({ field }) => (
+ <FormItem>
+ <Select
+ value={field.value as string}
+ onValueChange={field.onChange}
+ >
+ <SelectTrigger
+ aria-invalid={
+ !!form.formState.errors.assertions?.[index]
+ ?.type
+ }
+ className="w-full"
+ >
+ <SelectValue placeholder="Select type" />
+ </SelectTrigger>
+ <SelectContent>
+ {DNS_ASSERTION_TYPES.map((type) => (
+ <SelectItem key={type} value={type}>
+ {type}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name={`assertions.${index}.compare`}
+ render={({ field }) => (
+ <FormItem>
+ <Select
+ value={field.value}
+ onValueChange={field.onChange}
+ >
+ <SelectTrigger className="w-full min-w-16">
+ <span className="truncate">
+ <SelectValue placeholder="Select compare" />
+ </span>
+ </SelectTrigger>
+ <SelectContent>
+ {Object.entries(recordCompareDictionary).map(
+ ([key, value]) => (
+ <SelectItem key={key} value={key}>
+ {value}
+ </SelectItem>
+ ),
+ )}
+ </SelectContent>
+ </Select>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ {assertion.type === "header" && (
+ <FormField
+ control={form.control}
+ name={`assertions.${index}.key`}
+ render={({ field }) => (
+ <FormItem>
+ <Input
+ placeholder="Header key"
+ className="w-full"
+ {...field}
+ value={field.value as string}
+ />
+ <FormMessage />
+ </FormItem>
)}
- <FormField
- control={form.control}
- name={`assertions.${index}.target`}
- render={({ field }) => (
- <FormItem>
- <Input
- placeholder="Target value"
- className="w-full"
- type={
- assertion.type === "status"
- ? "number"
- : "text"
- }
- {...field}
- value={field.value?.toString() || ""}
- onChange={(e) => {
- const value =
- assertion.type === "status"
- ? Number.parseInt(e.target.value) || 0
- : e.target.value;
- field.onChange(value);
- }}
- />
- <FormMessage />
- </FormItem>
- )}
- />
- <Button
- size="icon"
- variant="ghost"
- type="button"
- onClick={() => {
- const newAssertions = field.value.filter(
- (_, i) => i !== index,
- );
- field.onChange(newAssertions);
- }}
- >
- <Close />
- </Button>
- </div>
- ))}
- <div className="flex flex-wrap gap-2">
- <Button
- size="sm"
- variant="outline"
- type="button"
- onClick={() => {
- const currentAssertions =
- form.getValues("assertions");
- field.onChange([
- ...currentAssertions,
- {
- type: "dnsRecord",
- version: "v1",
- compare: "eq",
- key: "A",
- target: "",
- },
- ]);
- }}
- >
- <Add />
- Add DNS Record Assertion
- </Button>
- </div>
- <FormMessage />
- </FormItem>
- )}
- />
+ />
+ )}
+ <FormField
+ control={form.control}
+ name={`assertions.${index}.target`}
+ render={({ field }) => (
+ <FormItem>
+ <Input
+ placeholder="Target value"
+ className="w-full"
+ type={
+ assertion.type === "status" ? "number" : "text"
+ }
+ {...field}
+ value={field.value?.toString() || ""}
+ onChange={(e) => {
+ const value =
+ assertion.type === "status"
+ ? Number.parseInt(e.target.value) || 0
+ : e.target.value;
+ field.onChange(value);
+ }}
+ />
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <Button
+ size="icon"
+ variant="ghost"
+ type="button"
+ onClick={() => removeAssertion(index)}
+ >
+ <Close />
+ </Button>
+ </div>
+ ))}
+ <div className="flex flex-wrap gap-2">
+ <Button
+ size="sm"
+ variant="outline"
+ type="button"
+ onClick={() =>
+ appendAssertion({
+ type: "dnsRecord",
+ version: "v1",
+ compare: "eq",
+ key: "A",
+ target: "",
+ })
+ }
+ >
+ <Add />
+ Add DNS Record Assertion
+ </Button>
+ </div>
+ </FormItem>
</FormCardContent>
</>
)}
diff --git a/apps/dashboard/src/components/forms/monitor/form-otel.tsx b/apps/dashboard/src/components/forms/monitor/form-otel.tsx
index f7082b9d8..43190c5d7 100644
--- a/apps/dashboard/src/components/forms/monitor/form-otel.tsx
+++ b/apps/dashboard/src/components/forms/monitor/form-otel.tsx
@@ -12,9 +12,10 @@ import {
FormMessage,
} from "@openstatus/ui/components/ui/form";
import { Input } from "@openstatus/ui/components/ui/input";
+import { headerPairSchema } from "@openstatus/utils";
import NextLink from "next/link";
import { useTransition } from "react";
-import { useForm } from "react-hook-form";
+import { useFieldArray, useForm } from "react-hook-form";
import { toast } from "sonner";
import { z } from "zod";
@@ -34,9 +35,7 @@ import {
const schema = z.object({
endpoint: z.url("Please enter a valid URL"),
- headers: z
- .array(z.object({ key: z.string(), value: z.string() }))
- .prefault([]),
+ headers: z.array(headerPairSchema).prefault([]),
});
type FormValues = z.input<typeof schema>;
@@ -55,6 +54,12 @@ export function FormOtel({
resolver: zodResolver(schema),
defaultValues: defaultValues ?? { endpoint: "", headers: [] },
});
+ // Stable row ids so removing a row remounts the shifted controllers.
+ const {
+ fields: headerFields,
+ append: appendHeader,
+ remove: removeHeader,
+ } = useFieldArray({ control: form.control, name: "headers" });
const [isPending, startTransition] = useTransition();
function submitAction(values: FormValues) {
@@ -104,78 +109,66 @@ export function FormOtel({
</FormItem>
)}
/>
- <FormField
- control={form.control}
- name="headers"
- disabled={locked}
- render={({ field }) => (
- <FormItem className="col-span-full">
- <FormLabel>Request Headers</FormLabel>
- {field.value?.map((header, index) => (
- <div key={index} className="grid gap-2 sm:grid-cols-5">
- <Input
- placeholder="Key"
- className="col-span-2"
- value={header.key}
- disabled={locked}
- onChange={(e) => {
- const newHeaders = [...(field.value ?? [])];
- newHeaders[index] = {
- ...newHeaders[index],
- key: e.target.value,
- };
- field.onChange(newHeaders);
- }}
- />
- <Input
- placeholder="Value"
- className="col-span-2"
- value={header.value}
- disabled={locked}
- onChange={(e) => {
- const newHeaders = [...(field.value ?? [])];
- newHeaders[index] = {
- ...newHeaders[index],
- value: e.target.value,
- };
- field.onChange(newHeaders);
- }}
- />
- <Button
- size="icon"
- variant="ghost"
- onClick={() => {
- const newHeaders = field.value?.filter(
- (_, i) => i !== index,
- );
- field.onChange(newHeaders);
- }}
- >
- <Close />
- </Button>
- </div>
- ))}
- <div>
- <Button
- size="sm"
- variant="outline"
- type="button"
- disabled={locked}
- onClick={() => {
- field.onChange([
- ...(field.value ?? []),
- { key: "", value: "" },
- ]);
- }}
- >
- <Add />
- Add Header
- </Button>
- </div>
- <FormMessage />
- </FormItem>
- )}
- />
+ <FormItem className="col-span-full">
+ <FormLabel>Request Headers</FormLabel>
+ {headerFields.map((row, index) => (
+ <div key={row.id} className="grid gap-2 sm:grid-cols-5">
+ <FormField
+ control={form.control}
+ name={`headers.${index}.key`}
+ render={({ field }) => (
+ <FormItem className="col-span-2">
+ <FormControl>
+ <Input
+ placeholder="Key"
+ {...field}
+ disabled={locked}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name={`headers.${index}.value`}
+ render={({ field }) => (
+ <FormItem className="col-span-2">
+ <FormControl>
+ <Input
+ placeholder="Value"
+ {...field}
+ disabled={locked}
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ <Button
+ size="icon"
+ variant="ghost"
+ type="button"
+ aria-label="Remove header"
+ disabled={locked}
+ onClick={() => removeHeader(index)}
+ >
+ <Close />
+ </Button>
+ </div>
+ ))}
+ <div>
+ <Button
+ size="sm"
+ variant="outline"
+ type="button"
+ disabled={locked}
+ onClick={() => appendHeader({ key: "", value: "" })}
+ >
+ <Add />
+ Add Header
+ </Button>
+ </div>
+ </FormItem>
</FormCardContent>
<FormCardFooter>
<FormCardFooterInfo>
diff --git a/packages/api/src/router/checker.ts b/packages/api/src/router/checker.ts
index ec84b1580..60deba8ef 100644
--- a/packages/api/src/router/checker.ts
+++ b/packages/api/src/router/checker.ts
@@ -16,6 +16,7 @@ import {
type grpcPayloadSchema,
type icmpPayloadSchema,
GRPC_TLS_MODES,
+ headerPairSchema,
safeUrlSchema,
type tpcPayloadSchema,
transformHeaders,
@@ -84,7 +85,7 @@ const httpTestInput = z.object({
"TRACE",
])
.prefault("GET"),
- headers: z.array(z.object({ key: z.string(), value: z.string() })).optional(),
+ headers: z.array(headerPairSchema).optional(),
body: z.string().optional(),
region: monitorRegionSchema.prefault("ams"),
assertions: z
@@ -130,7 +131,7 @@ const grpcTestInput = z.object({
url: z.string(),
service: z.string().optional(),
tls: z.enum(GRPC_TLS_MODES).prefault("tls"),
- headers: z.array(z.object({ key: z.string(), value: z.string() })).optional(),
+ headers: z.array(headerPairSchema).optional(),
region: monitorRegionSchema.prefault("ams"),
});
diff --git a/packages/api/src/router/monitor.ts b/packages/api/src/router/monitor.ts
index 639232409..ba01ec9a5 100644
--- a/packages/api/src/router/monitor.ts
+++ b/packages/api/src/router/monitor.ts
@@ -31,6 +31,7 @@ import {
updateMonitorSchedulingRegions,
updateMonitorTags,
} from "@openstatus/services/monitor";
+import { headerPairSchema } from "@openstatus/utils";
import { z } from "zod";
import { env } from "../env";
@@ -44,7 +45,7 @@ const isSelfHost = env.SELF_HOST;
// tRPC-side input schemas. These preserve the existing wire contract exactly.
-const headerPair = z.object({ key: z.string(), value: z.string() });
+const headerPair = headerPairSchema;
const assertionUnion = z.discriminatedUnion("type", [
statusAssertion,
headerAssertion,
diff --git a/packages/db/src/schema/monitors/validation.ts b/packages/db/src/schema/monitors/validation.ts
index 3d1942f12..16a01bf21 100644
--- a/packages/db/src/schema/monitors/validation.ts
+++ b/packages/db/src/schema/monitors/validation.ts
@@ -1,4 +1,5 @@
import * as assertions from "@openstatus/assertions";
+import { headerPairSchema } from "@openstatus/utils";
import { createInsertSchema, createSelectSchema } from "drizzle-zod";
import { z } from "zod";
@@ -62,9 +63,7 @@ export const selectMonitorSchema = createSelectSchema(monitor, {
method: monitorMethodsSchema.prefault("GET"),
});
-const headersSchema = z
- .array(z.object({ key: z.string(), value: z.string() }))
- .optional();
+const headersSchema = z.array(headerPairSchema).optional();
export const insertMonitorSchema = createInsertSchema(monitor, {
name: z
diff --git a/packages/services/src/monitor/schemas.ts b/packages/services/src/monitor/schemas.ts
index 245361914..ae1d0a84c 100644
--- a/packages/services/src/monitor/schemas.ts
+++ b/packages/services/src/monitor/schemas.ts
@@ -11,11 +11,12 @@ import {
monitorJobTypes,
monitorMethods,
} from "@openstatus/db/src/schema/monitors/constants";
+import { headerPairSchema } from "@openstatus/utils";
import { z } from "zod";
export { grpcTlsModes, monitorJobTypes, monitorMethods, monitorPeriodicity };
-const headerPair = z.object({ key: z.string(), value: z.string() });
+const headerPair = headerPairSchema;
const assertion = z.discriminatedUnion("type", [
statusAssertion,
headerAssertion,
diff --git a/packages/utils/src/headers.test.ts b/packages/utils/src/headers.test.ts
new file mode 100644
index 000000000..61c746acd
--- /dev/null
+++ b/packages/utils/src/headers.test.ts
@@ -0,0 +1,41 @@
+import { expect } from "@std/expect";
+import { describe, test } from "@std/testing/bdd";
+
+import { headerPairSchema } from "./headers";
+
+describe("headerPairSchema", () => {
+ test("trims surrounding whitespace from the value only", () => {
+ expect(
+ headerPairSchema.parse({ key: "Content-Type", value: " text/plain " }),
+ ).toEqual({ key: "Content-Type", value: "text/plain" });
+ });
+
+ test("rejects surrounding whitespace in the key instead of trimming it", () => {
+ for (const key of [" Content-Type", "Content-Type ", " "]) {
+ expect(headerPairSchema.safeParse({ key, value: "x" }).success).toBe(
+ false,
+ );
+ }
+ });
+
+ test("rejects an empty name so a placeholder row is never persisted", () => {
+ const result = headerPairSchema.safeParse({ key: "", value: "" });
+ expect(result.success).toBe(false);
+ expect(result.error?.issues[0]?.message).toBe("Header name is required");
+ });
+
+ test("allows an empty value", () => {
+ expect(headerPairSchema.parse({ key: "X-Empty", value: "" })).toEqual({
+ key: "X-Empty",
+ value: "",
+ });
+ });
+
+ test("rejects a name that is not a header token", () => {
+ for (const key of ["Content Type", "X-Trace:", "Ünicode", "a\tb"]) {
+ expect(headerPairSchema.safeParse({ key, value: "x" }).success).toBe(
+ false,
+ );
+ }
+ });
+});
diff --git a/packages/utils/src/headers.ts b/packages/utils/src/headers.ts
new file mode 100644
index 000000000..05931de1b
--- /dev/null
+++ b/packages/utils/src/headers.ts
@@ -0,0 +1,20 @@
+import { z } from "zod";
+
+// RFC 9110 field-name token: the only shape net/http will put on the wire.
+const HEADER_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]*$/;
+
+// The key is not trimmed on purpose: a pasted " Content-Type" should surface
+// as an error rather than be silently rewritten. An empty name is rejected
+// here too so a placeholder row can't be persisted through the API.
+export const headerPairSchema = z.object({
+ key: z
+ .string()
+ .min(1, "Header name is required")
+ .regex(
+ HEADER_NAME,
+ "Header name must not contain spaces or special characters",
+ ),
+ value: z.string().trim(),
+});
+
+export type HeaderPair = z.infer<typeof headerPairSchema>;
diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts
index 4caa8f75c..1aa6a38f4 100644
--- a/packages/utils/src/index.ts
+++ b/packages/utils/src/index.ts
@@ -23,6 +23,7 @@ export {
MONITOR_STATUSES,
} from "./constants";
export { buildCurlCommand, type CurlRequest } from "./curl";
+export { type HeaderPair, headerPairSchema } from "./headers";
export { iteratorToStream, yieldMany } from "./stream";
export { type PageUpdateStatus, statusLabel } from "./status";