Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

9.5 KB
Raw Blame
import { InputJsonValue } from "@prisma/client/runtime/library";
import { z } from "zod";
import { InvalidRequestError } from "../errors/InvalidRequestError";

/** ISO datetimes with minutes, seconds, or fractional seconds; timezone required. */
export function isoDateTime({
  offset = false,
  error = "Invalid ISO datetime",
}: {
  offset?: boolean;
  error?: string | z.core.$ZodErrorMap;
} = {}) {
  // Share the date/time patterns once to keep tool schemas compact and union-free.
  const date = z.regexes.date.source.slice(1, -1);
  const time = z.regexes.time({}).source.slice(1, -1);
  const timezone = offset ? "(?:Z|[+-](?:[01]\\d|2[0-3]):[0-5]\\d)" : "Z";
  const pattern = new RegExp(`^${date}T${time}${timezone}$`);
  return z.string({ error }).regex(pattern, { error });
}

// to be used for Prisma JSON type
// @see: https://github.com/colinhacks/zod#json-type

// For root-level literals where null is not allowed
const rootLiteralSchema = z.union([z.string(), z.number(), z.boolean()]);

// For nested literals where null is allowed
const nestedLiteralSchema = z.union([
  z.string(),
  z.number(),
  z.boolean(),
  z.null(),
]);

type Root = z.infer<typeof rootLiteralSchema>;
type Literal = z.infer<typeof nestedLiteralSchema>;

export type JsonNested = Literal | { [key: string]: JsonNested } | JsonNested[];
type Json = Root | { [key: string]: JsonNested } | JsonNested[];

// Here, you define the schema recursively
export const jsonSchemaNullable: z.ZodType<JsonNested> = z.lazy(() =>
  z.union([
    z.array(jsonSchemaNullable),
    z.record(z.string(), jsonSchemaNullable),
    nestedLiteralSchema,
  ]),
);

// Root schema that does not allow nulls at the root level
export const jsonSchema: z.ZodType<Json> = z.lazy(() =>
  z.union([
    z.array(jsonSchemaNullable),
    z.record(z.string(), jsonSchemaNullable),
    rootLiteralSchema,
  ]),
);

export const paginationLimitZod = z.preprocess(
  (x) => (x === "" ? undefined : x),
  z.coerce.number().int().gte(1).lte(100).default(50),
);

/** @alias */
export const publicApiPaginationLimitZod = paginationLimitZod;

export const paginationZod = {
  page: z.preprocess(
    (x) => (x === "" ? undefined : x),
    z.coerce.number().nonnegative().default(1),
  ),
  limit: paginationLimitZod,
};

export const publicApiPaginationZod = {
  page: z.preprocess(
    (x) => (x === "" ? undefined : x),
    z.coerce.number().int().gt(0).default(1),
  ),
  limit: publicApiPaginationLimitZod,
};

const splitCommaSeparatedQueryParam = (value: string) =>
  value
    .split(",")
    .map((item) => item.trim())
    .filter((item) => item.length > 0);

export const optionalCommaSeparatedStringArray = z
  .string()
  .nullish()
  .transform((value) => {
    if (!value) return undefined;

    const values = splitCommaSeparatedQueryParam(value);
    return values.length > 0 ? values : undefined;
  });

export const optionalJsonParam = <T extends z.ZodType>(
  schema: T,
  paramName: string,
) =>
  z
    .string()
    .optional()
    .transform((str) => {
      if (!str) return undefined;
      try {
        return JSON.parse(str);
      } catch {
        throw new InvalidRequestError(`Invalid JSON in ${paramName} parameter`);
      }
    })
    .pipe(schema.optional());

type CommaSeparatedEnumArrayOptions = {
  unknownValues?: "reject" | "filter";
};

type CommaSeparatedEnumArrayOutput<
  TValues extends readonly [string, ...string[]],
  TDefault extends Array<TValues[number]> | null,
> = TDefault extends null
  ? Array<TValues[number]> | null
  : Array<TValues[number]>;

export function commaSeparatedEnumArray<
  const TValues extends readonly [string, ...string[]],
  const TDefault extends Array<TValues[number]> | null,
>(
  values: TValues,
  defaultValue: TDefault,
  options?: CommaSeparatedEnumArrayOptions,
): z.ZodType<CommaSeparatedEnumArrayOutput<TValues, TDefault>> {
  const arraySchema = z.array(z.enum(values));
  const schema =
    defaultValue === null
      ? arraySchema.nullable().default(null)
      : arraySchema.default(defaultValue);

  return z.preprocess((value) => {
    if (value === null || value === undefined || value === "") return undefined;
    if (typeof value !== "string") return value;

    const items = splitCommaSeparatedQueryParam(value);

    if (options?.unknownValues === "filter") {
      return items.filter((item): item is TValues[number] =>
        values.includes(item as TValues[number]),
      );
    }

    return items;
  }, schema) as z.ZodType<CommaSeparatedEnumArrayOutput<TValues, TDefault>>;
}

export const optionalPaginationZod = {
  page: z
    .preprocess((x) => (x === "" ? undefined : x), z.coerce.number())
    .optional(),
  limit: z
    .preprocess((x) => (x === "" ? undefined : x), z.coerce.number())
    .optional(),
};

export const queryStringZod = z
  .string()
  .transform((val) => decodeURIComponent(val));

/**
 * Top-level `_deprecation` metadata returned by legacy public API endpoints.
 * Optional fields are omitted when empty (never null).
 */
export const deprecationResponseZod = z.object({
  message: z.string(),
  replacement: z.string().optional(),
  docsUrl: z.string().optional(),
  sunsetAt: z.string().optional(),
});

export type ApiDeprecationInfo = z.infer<typeof deprecationResponseZod>;

export const paginationMetaResponseZod = z.object({
  /** Set on list responses of legacy public API endpoints. */
  deprecation: deprecationResponseZod
    .pick({ sunsetAt: true, replacement: true })
    .optional(),
  page: z.number().int().positive(),
  limit: z.number().int().positive(),
  totalItems: z.number().int().nonnegative(),
  totalPages: z.number().int().nonnegative(),
});

export const urlRegex = /https?:\/\/[^\s/$.?#].[^\s]*/i;
export const noUrlCheck = (value: string) => !urlRegex.test(value);

export const NonEmptyString = z.string().min(1);

export const htmlRegex = /<[^<>]*>/g;
const containsHtmlRegex = /<[^<>]*>/;

function removeHtmlTags(input: string): string {
  const parts: string[] = [];
  let cursor = 0;

  while (cursor < input.length) {
    const tagStart = input.indexOf("<", cursor);
    if (tagStart === -1) {
      parts.push(input.slice(cursor));
      break;
    }

    const tagEnd = input.indexOf(">", tagStart + 1);
    if (tagEnd === -1) {
      parts.push(input.slice(cursor));
      break;
    }

    parts.push(input.slice(cursor, tagStart));
    cursor = tagEnd + 1;
  }

  return parts.join("");
}

export const StringNoHTML = z
  .string()
  .refine((val) => !containsHtmlRegex.test(val), {
    message: "Text cannot contain HTML tags",
  });

export const StringNoHTMLNonEmpty = z
  .string()
  .min(1, "Text cannot be empty")
  .refine((val) => !containsHtmlRegex.test(val), {
    message: "Text cannot contain HTML tags",
  });

/**
 * Validates an object against a Zod schema and helps with IDE type warnings.
 *
 * @param schema - The Zod schema to validate against.
 * @param object - The object to be validated.
 * @returns The parsed object if validation is successful.
 */
export const validateZodSchema = <T extends z.ZodType>(
  schema: T,
  object: z.infer<T>,
): z.infer<T> => {
  return schema.parse(object);
};

// JSON Schema validation
export const JSONPrimitiveValueSchema = z.union([
  z.string(),
  z.number(),
  z.boolean(),
]);

export const JSONValueSchema: z.ZodType<InputJsonValue> = z.lazy(() =>
  z.union([
    JSONPrimitiveValueSchema,
    z.array(JSONValueSchema),
    z.record(z.string(), JSONValueSchema),
  ]),
);

export const JSONObjectSchema = z.record(z.string(), JSONValueSchema);
export const JSONArraySchema = z.array(JSONValueSchema);

export type JSONPrimitiveValue = z.infer<typeof JSONPrimitiveValueSchema>;
export type JSONValue = z.infer<typeof JSONValueSchema>;
export type JSONObject = z.infer<typeof JSONObjectSchema>;
export type JSONArray = z.infer<typeof JSONArraySchema>;

/**
 * Sanitizes a string for safe use in email subject lines.
 * Prevents email header injection attacks by removing:
 * - Newline characters (\r, \n) which can be used for CRLF injection
 * - Control characters (ASCII 0-31 and 127) which can cause parsing issues
 * - HTML tags (defensive, though nodemailer should handle this)
 *
 * This is critical for security compliance as it prevents attackers from:
 * - Injecting additional email headers (BCC, CC, From, etc.)
 * - Manipulating email routing
 * - Executing XSS in email clients
 *
 * @param input - The string to sanitize (e.g., user name, project name)
 * @returns Sanitized string safe for email subject lines
 *
 * @example
 * sanitizeEmailSubject("John\r\nBCC: [email protected]") // Returns "JohnBCC: [email protected]"
 * sanitizeEmailSubject("Test<script>alert(1)</script>") // Returns "Testscriptalert(1)/script"
 */
export function sanitizeEmailSubject(input: string): string {
  const withoutControlCharacters = input
    // Remove carriage return and line feed (CRLF injection prevention)
    .replace(/[\r\n]/g, "")
    // Remove all control characters (ASCII 0-31 and 127)
    // eslint-disable-next-line no-control-regex
    .replace(/[\x00-\x1F\x7F]/g, "");

  return removeHtmlTags(withoutControlCharacters).trim();
}

/**
 * Zod schema for optional ISO 8601 timestamp strings (RFC 3339, Section 5.6) in UTC.
 * Used for dataset versioning to allow querying data at a specific point in time.
 *
 * Behavior:
 * - If provided, must be a valid ISO 8601 string (e.g., "2026-01-21T14:35:42Z")
 * - Coerces to Date object
 * - If undefined, treated as optional (returns latest version)
 *
 * @example
 * // Valid inputs
 * versionZod.parse("2026-01-21T14:35:42Z") // Returns Date object
 * versionZod.parse(undefined) // Returns undefined
 */
export const versionZod = z.coerce.date().optional();