import { z } from "zod"; /** * i18n note: the error messages in this module are intentionally plain English. * They are locale-neutral fallbacks only ever surfaced when the *base* schema is * used directly — e.g. server-side API routes parsing a request body, where no * `t()` / locale is available. The interactive form never shows these strings: * it rebuilds every user-facing field with translated messages via * `buildConnectFormSchema(t)` / `buildEditFormSchema(t)` / `localizedNameField(t)` * (see components/instance/connect-instance-form.tsx), which override the name, * endpoint, and credential-pairing messages below. Do NOT translate these to a * single hard-coded locale — that would leak that locale into the API layer. */ /** * Instance name constraints mirror packages/shared INSTANCE_NAME_PATTERN * (`^[a-z0-9-]{1,32}$`) plus the reserved "default" exclusion. */ const instanceNameSchema = z .string() .trim() .regex( /^[a-z0-9-]{1,32}$/, "Name must be 1-32 lowercase letters, digits, or hyphens", ) .refine((v) => v !== "default", 'Name "default" is reserved'); const trimmedNonEmpty = (label: string, max = 512) => z.string().trim().min(1, `Please enter ${label}`).max(max); const optionalTrimmed = (max = 512) => z.string().trim().max(max).optional().or(z.literal("")); // Credential-mode rules shared by connect / update / edit schemas: // 1. AccessKey ID and Secret must be supplied together (or both omitted). // 2. At least one data-plane credential must be present — the AK/SK pair or // an API Key. (Update/edit relax rule 2 to allow "keep existing".) const akSkPaired = (v: { accessKeyId?: string; accessKeySecret?: string; }): boolean => Boolean(v.accessKeyId) === Boolean(v.accessKeySecret); const AK_SK_PAIR_ERROR = { message: "AccessKey ID and Secret must be provided together", path: ["accessKeySecret"], }; const someCredential = (v: { accessKeyId?: string; accessKeySecret?: string; apiKey?: string; }): boolean => Boolean(v.accessKeyId && v.accessKeySecret) || Boolean(v.apiKey); const CREDENTIAL_REQUIRED_ERROR = { message: "Provide at least an API Key, or AccessKey ID + Secret", path: ["apiKey"], }; /** * Apply the credential-mode rules to any object schema that carries the * `accessKeyId` / `accessKeySecret` / `apiKey` fields. Exposed so the * interactive form can layer its own URL-shape overrides onto the base object * (via `.extend`) and still inherit the exact same credential validation. * The predicates read the parsed value loosely (`Record`) because the input * type varies across the connect / form variants. */ export function withCredentialModeRules(schema: S) { return schema .refine((v) => akSkPaired(v as Record), AK_SK_PAIR_ERROR) .refine( (v) => someCredential(v as Record), CREDENTIAL_REQUIRED_ERROR, ); } /** Base object (no refinements) so callers can `.extend` before refining. */ export const connectInstanceBaseSchema = z.object({ name: instanceNameSchema, accessKeyId: optionalTrimmed(128), accessKeySecret: optionalTrimmed(512), apiKey: optionalTrimmed(512), otsEndpoint: trimmedNonEmpty("OTS Endpoint", 256), otsInstanceName: trimmedNonEmpty("OTS instance name", 128), ossEndpoint: optionalTrimmed(256), ossBucketName: optionalTrimmed(128), region: optionalTrimmed(64), activate: z.boolean().optional(), }); export const connectInstanceSchema = withCredentialModeRules( connectInstanceBaseSchema, ); export const updateInstanceSchema = z .object({ accessKeyId: optionalTrimmed(128), accessKeySecret: optionalTrimmed(512), // Optional on update: omit/leave blank to keep the existing credential. apiKey: optionalTrimmed(512), otsEndpoint: optionalTrimmed(256), otsInstanceName: optionalTrimmed(128), ossEndpoint: optionalTrimmed(256), ossBucketName: optionalTrimmed(128), region: optionalTrimmed(64), activate: z.boolean().optional(), }) // Require AccessKey ID and Secret to be supplied together. Passing only // one of the pair previously sneaked past validation and later tripped a // generic 500 on the server side where the pair is encoded as a single // credential. Matching both at the schema layer surfaces the mistake in // the form itself with a field-targeted message. (No "at least one // credential" rule here: a partial update may touch only OSS/region and // legitimately leave both credential fields blank to keep the current one.) .refine( (v) => { const hasId = Boolean(v.accessKeyId && v.accessKeyId.length > 0); const hasSecret = Boolean( v.accessKeySecret && v.accessKeySecret.length > 0, ); return hasId === hasSecret; }, { message: "AccessKey ID and Secret must be updated together: fill in both or leave both blank", path: ["accessKeySecret"], }, ); /** * Form-side schema for editing an existing instance. Mirrors * {@link updateInstanceSchema} on the server: every field is optional and * AccessKey ID/Secret must be filled in pairs (or both left blank to keep * the existing credential intact). Used by the connect-instance form when * `mode === "edit"` so the dialog can prepopulate placeholders without * clobbering the live credential when the user only wants to change, say, * the OSS bucket. */ export const editInstanceFormSchema = z .object({ name: instanceNameSchema, accessKeyId: optionalTrimmed(128), accessKeySecret: optionalTrimmed(512), // Leave blank to keep the existing API Key. apiKey: optionalTrimmed(512), otsEndpoint: trimmedNonEmpty("OTS Endpoint", 256), otsInstanceName: trimmedNonEmpty("OTS instance name", 128), ossEndpoint: optionalTrimmed(256), ossBucketName: optionalTrimmed(128), region: optionalTrimmed(64), activate: z.boolean().optional(), }) .refine( (v) => { const hasId = Boolean(v.accessKeyId && v.accessKeyId.length > 0); const hasSecret = Boolean( v.accessKeySecret && v.accessKeySecret.length > 0, ); return hasId === hasSecret; }, { message: "AccessKey ID and Secret must be updated together: fill in both or leave both blank", path: ["accessKeySecret"], }, ); export const importInstanceSchema = z.object({ // Match the client-side Textarea guard (min 10) so server and browser // reject identical inputs; the previous 1-char floor let obvious // typos (e.g. a stray "a") reach the decoder which returned a // cryptic INVALID_TOKEN at submit time. token: z.string().trim().min(10, "Token is too short to be parsed").max(4096), name: instanceNameSchema.optional(), activate: z.boolean().optional(), }); export type ConnectInstanceInput = z.infer; export type UpdateInstanceInput = z.infer; export type ImportInstanceInput = z.infer;