Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(control-ui): validate raw spec.host display before any wizard write (R5-H1)

Diego Zacariasb24ec91a813c
diff --git a/control-ui/components/HostWizard/index.tsx b/control-ui/components/HostWizard/index.tsx
index 4dd1ba91b..7be53fdab 100644
--- a/control-ui/components/HostWizard/index.tsx
+++ b/control-ui/components/HostWizard/index.tsx
@@ -1,6 +1,11 @@
'use client'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import {
+ CONTROL_CHAR_RE,
+ DISPLAY_FIELD_MAX_LENGTH,
+ validateDisplayField,
+} from '@clerum/display-field'
import { ChannelCredentialsPanel } from '@/components/ChannelCredentialsPanel'
import type { CredentialDraft } from '@/components/ChannelCredentialsPanel/types'
import { CreateFlowPanel } from '@/components/CreateFlowPanel'
@@ -236,6 +241,31 @@ function secretSlugConstraintMessage(rawName: string): string | null {
return null
}
+// The free-text display value the server stores as spec.host — the operator's
+// trimmed name, or the derived slug when the trimmed name is empty. This is the
+// exact value submitAll writes (`hostName.trim() || toKebabCase(hostName)`), so
+// the gate validates precisely what the server will validate.
+function displayHostValue(rawHostName: string): string {
+ return rawHostName.trim() || toKebabCase(rawHostName)
+}
+
+// Human-readable reason the free-text spec.host display value is rejected, or
+// null when it is acceptable. The RULE of validity is owned by the shared
+// @clerum/display-field package (the SAME rule the server applies, D4); this
+// function only maps the machine issue to a user-facing message. The "empty"
+// case is intentionally NOT surfaced here — a hostName that derives a non-empty
+// slug is never display-empty, and the empty case is already covered by the
+// slug "Agent name must contain letters or numbers." message.
+function displayHostPreflightMessage(rawHostName: string): string | null {
+ const value = displayHostValue(rawHostName)
+ if (!validateDisplayField(value, 'spec.host')) return null
+ if (CONTROL_CHAR_RE.test(value))
+ return "Agent name can't contain control or formatting characters."
+ if (value.trim().length > DISPLAY_FIELD_MAX_LENGTH)
+ return `Agent name is too long (max ${DISPLAY_FIELD_MAX_LENGTH} characters).`
+ return null
+}
+
function isStepValid(
stepIndex: number,
state: {
@@ -276,6 +306,11 @@ function isStepValid(
// overwrite that agent's entire spec and still report "created". Gating here
// stops the collision BEFORE any sibling (secret/context/channel) is created.
if (state.existingHostNames.includes(toKebabCase(state.hostName))) return false
+ // Gate the free-text display value (spec.host) too: toKebabCase strips
+ // control/bidi chars, so a name like "agent‮name" derives a clean slug
+ // yet its display value carries a character the server rejects (422) AFTER
+ // the secret/context are created — orphaning them. Mirror that rule here.
+ if (validateDisplayField(displayHostValue(state.hostName), 'spec.host')) return false
return true
}
if (stepIndex === 1) {
@@ -710,6 +745,8 @@ export function HostWizard({
if (step === 0 && slugConstraintMessage(hostName)) return slugConstraintMessage(hostName)!
if (step === 0 && existingHostNames.includes(toKebabCase(hostName)))
return 'Identifier already in use — choose another name.'
+ if (step === 0 && displayHostPreflightMessage(hostName))
+ return displayHostPreflightMessage(hostName)!
if (step === 1 && contextMode === 'existing' && !selectedExistingContext.trim())
return 'Select an existing context.'
if (step === 1 && contextMode === 'new' && !toKebabCase(contextName))
@@ -873,6 +910,27 @@ export function HostWizard({
if (existingHostNames.includes(normalizedHostName)) {
throw new Error('Identifier already in use — choose another name.')
}
+ // Hard preflight — defense in depth for the step gates (R5-H1). Everything
+ // the server validates is checked HERE, before the first apiSend, so a
+ // value the server would reject can never leave an orphaned sibling
+ // (secret/context/channel) ahead of the failing host create. This is
+ // purely additive: no write ordering or upsert behavior changes.
+ const displayHostIssue = validateDisplayField(displayHostValue(hostName), 'spec.host')
+ if (displayHostIssue) {
+ throw new Error(displayHostPreflightMessage(hostName) || 'Agent name is not valid.')
+ }
+ if (!isValidResourceSlug(hostName)) {
+ throw new Error('Agent name is not a valid identifier.')
+ }
+ if (contextMode === 'new' && !isValidResourceSlug(contextName)) {
+ throw new Error('Context name is not a valid identifier.')
+ }
+ if (!shouldSkipChannels && channelMode === 'new' && !isValidResourceSlug(channelName)) {
+ throw new Error('Channel name is not a valid identifier.')
+ }
+ if (secretMode === 'new' && !isValidDNSSubdomain(toKebabCase(newSecretName))) {
+ throw new Error('Secret name is not a valid identifier.')
+ }
const normalizedContextName = toKebabCase(contextName)
const resolvedContextName =
contextMode === 'existing' ? selectedContextOption?.contextId || '' : normalizedContextName
diff --git a/control-ui/components/__tests__/HostWizard.display-preflight.test.tsx b/control-ui/components/__tests__/HostWizard.display-preflight.test.tsx
new file mode 100644
index 000000000..7f4625ca7
--- /dev/null
+++ b/control-ui/components/__tests__/HostWizard.display-preflight.test.tsx
@@ -0,0 +1,183 @@
+import React from 'react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import * as api from '../../lib/api'
+import { HostWizard } from '../HostWizard'
+import { ToastProvider } from '../Toast'
+
+/**
+ * Regression guard for R5-H1: the step-0 gate validates the DERIVED slug
+ * (toKebabCase), but toKebabCase STRIPS control/bidi characters and truncates
+ * nothing about the free-text display value. So a name like "agent‮name"
+ * (a Right-to-Left-Override bidi char) derives a clean, valid slug ("agentname")
+ * that sails through the slug gate — yet the RAW display value the server stores
+ * as spec.host is rejected (422). Because the secret/context are created BEFORE
+ * the host in submitAll, that late rejection orphans the siblings.
+ *
+ * The fix validates the free-text spec.host display value with the shared
+ * @clerum/display-field rule (the SAME rule the server applies), both in the
+ * step-0 gate (live feedback) and as a hard check at the top of submitAll
+ * (defense in depth) BEFORE any write.
+ *
+ * These tests FAIL against the pre-fix head, where nothing validated the raw
+ * display value: the bidi name enabled Next and the whole wizard reached Create,
+ * POSTing the secret before the host create failed.
+ */
+
+vi.mock('../../lib/api', () => ({
+ apiGet: vi.fn().mockResolvedValue({ items: [] }),
+ apiSend: vi.fn().mockResolvedValue({}),
+ getAdminUsers: vi.fn().mockResolvedValue({ items: [] }),
+ getAdminTeams: vi.fn().mockResolvedValue({ items: [] }),
+ updateAgentUsers: vi.fn().mockResolvedValue({ agentName: '', userIds: [] }),
+ updateAgentTeams: vi.fn().mockResolvedValue({ agentName: '', teamIds: [] }),
+ getLlmModels: vi.fn().mockResolvedValue({
+ rows: [
+ {
+ id: 'm1',
+ provider: 'openai',
+ model: 'gpt-5.4-mini',
+ vendor: 'OpenAI',
+ display_name: null,
+ context_window_tokens: null,
+ enabled: true,
+ created_at: '',
+ updated_at: '',
+ },
+ ],
+ }),
+ isSilentApiError: vi.fn().mockReturnValue(false),
+}))
+
+if (!Element.prototype.scrollIntoView) {
+ Element.prototype.scrollIntoView = () => {}
+}
+
+// A Right-to-Left-Override (U+202E) bidi character: the canonical Trojan-Source
+// vector. toKebabCase strips it, so the derived slug is clean ("agentname").
+const BIDI_NAME = 'agent‮name'
+
+async function renderWizard() {
+ const onCreated = vi.fn().mockResolvedValue(undefined)
+ const onClose = vi.fn()
+ const utils = render(
+ <ToastProvider>
+ <HostWizard
+ mcpServers={[{ metadata: { name: 'mcp-a' } }]}
+ existingSecrets={[{ name: 'secret-a' }]}
+ onCreated={onCreated}
+ onClose={onClose}
+ />
+ </ToastProvider>
+ )
+ await act(async () => {
+ await Promise.resolve()
+ await Promise.resolve()
+ })
+ return { ...utils, onCreated, onClose }
+}
+
+// Drive the wizard from step 0 toward the final Create/Skip action, filling the
+// minimal valid values each step needs. Pre-fix, a bidi name slips past step 0
+// and this reaches "Skip channel setup" (which submits). Post-fix, the step-0
+// gate keeps Next disabled and this bails harmlessly on the first iteration —
+// so it never throws on absent later-step controls in either version.
+async function driveTowardCreate() {
+ for (let i = 0; i < 10; i += 1) {
+ // Last step: submit via "Skip channel setup" so channel fields aren't needed.
+ const skipBtn = screen.queryByRole('button', { name: /Skip channel setup/i })
+ if (skipBtn) {
+ fireEvent.click(skipBtn)
+ return
+ }
+
+ // Step 1: pick a new context with a valid name so its gate can pass.
+ const newCtx = screen.queryByLabelText(/Create new context/i) as HTMLInputElement | null
+ if (newCtx) {
+ if (!newCtx.checked) fireEvent.click(newCtx)
+ const ctxInput = screen.queryByPlaceholderText(/context-name/i) as HTMLInputElement | null
+ if (ctxInput && !ctxInput.value) fireEvent.change(ctxInput, { target: { value: 'ctx1' } })
+ }
+
+ // Step 2: make the OpenAI primary usable, then wait for the model to seed
+ // (async, once the allowlist loads) so Next isn't transiently disabled.
+ const openAiKey = screen.queryByLabelText(/OpenAI API key/i) as HTMLInputElement | null
+ if (openAiKey && !openAiKey.value) {
+ fireEvent.change(openAiKey, { target: { value: 'sk-openai' } })
+ await waitFor(() => {
+ const n = screen.queryByRole('button', { name: 'Next' }) as HTMLButtonElement | null
+ expect(Boolean(n && !n.disabled)).toBe(true)
+ })
+ }
+
+ const nextBtn = screen.queryByRole('button', { name: 'Next' }) as HTMLButtonElement | null
+ if (!nextBtn || nextBtn.disabled) return
+ fireEvent.click(nextBtn)
+ }
+}
+
+afterEach(() => {
+ cleanup()
+ vi.clearAllMocks()
+})
+
+describe('HostWizard — step 0 gates the free-text spec.host display value (R5-H1)', () => {
+ it('INV-1: keeps Next DISABLED for a name whose slug is valid but display carries a bidi char', async () => {
+ await renderWizard()
+ await waitFor(() => expect(api.getAdminUsers).toHaveBeenCalled())
+
+ fireEvent.change(screen.getByPlaceholderText(/agent-name/i), { target: { value: BIDI_NAME } })
+
+ // The derived slug is clean and valid, so the slug/identifier hint reports no
+ // error — only the display-value gate blocks.
+ expect(screen.getByRole('button', { name: 'Next' })).toBeDisabled()
+ expect(screen.getByText(/control or formatting characters/i)).toBeInTheDocument()
+ })
+
+ it('INV-1 baseline: enables Next for an ordinary display name', async () => {
+ await renderWizard()
+ await waitFor(() => expect(api.getAdminUsers).toHaveBeenCalled())
+
+ fireEvent.change(screen.getByPlaceholderText(/agent-name/i), { target: { value: 'My Agent' } })
+
+ expect(screen.getByRole('button', { name: 'Next' })).not.toBeDisabled()
+ expect(screen.queryByText(/control or formatting characters/i)).not.toBeInTheDocument()
+ })
+
+ it('INV-3: keeps Next DISABLED when the display value exceeds the max length but the slug is valid', async () => {
+ await renderWizard()
+ await waitFor(() => expect(api.getAdminUsers).toHaveBeenCalled())
+
+ // "ab" + 130 dots: toKebabCase strips the dots → slug "ab" (valid, ≤63),
+ // but the raw display value is 132 chars — over the 120 display max the
+ // server enforces. The slug gate alone would let this through.
+ const longDisplay = `ab${'.'.repeat(130)}`
+ fireEvent.change(screen.getByPlaceholderText(/agent-name/i), { target: { value: longDisplay } })
+
+ expect(screen.getByRole('button', { name: 'Next' })).toBeDisabled()
+ expect(screen.getByText(/too long \(max 120 characters\)/i)).toBeInTheDocument()
+ })
+})
+
+describe('HostWizard — an invalid display value never reaches the server as a side-effect (R5-H1)', () => {
+ it('INV-2: fires NO create apiSend when the display value is invalid (bidi char)', async () => {
+ await renderWizard()
+ await waitFor(() => expect(api.getAdminUsers).toHaveBeenCalled())
+
+ fireEvent.change(screen.getByPlaceholderText(/agent-name/i), { target: { value: BIDI_NAME } })
+
+ // Pre-fix: the bidi name slips through, the flow reaches Create, and the
+ // secret is POSTed before the host create fails — apiSend IS called (bug).
+ // Post-fix: the step-0 gate blocks before any step advances.
+ await driveTowardCreate()
+ await act(async () => {
+ await Promise.resolve()
+ })
+
+ // The observable invariant (T4): no create request escaped for an invalid
+ // display value, so no orphaned sibling can exist.
+ expect(api.apiSend).not.toHaveBeenCalled()
+ // And the operator sees why.
+ expect(screen.getByText(/control or formatting characters/i)).toBeInTheDocument()
+ })
+})
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index 6d08b519c..5af96b36f 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,13 +1,14 @@
{
"name": "clerum-control-ui",
- "version": "0.1.396",
+ "version": "0.1.397",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.396",
+ "version": "0.1.397",
"dependencies": {
+ "@clerum/display-field": "file:../packages/display-field",
"@clerum/llm-providers": "file:../packages/llm-providers",
"@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",
"@uiw/react-md-editor": "^4.1.0",
@@ -30,6 +31,11 @@
"vitest": "^4.0.18"
}
},
+ "../packages/display-field": {
+ "name": "@clerum/display-field",
+ "version": "0.1.0",
+ "license": "MIT"
+ },
"../packages/llm-providers": {
"name": "@clerum/llm-providers",
"version": "0.1.0",
@@ -151,6 +157,10 @@
"specificity": "bin/cli.js"
}
},
+ "node_modules/@clerum/display-field": {
+ "resolved": "../packages/display-field",
+ "link": true
+ },
"node_modules/@clerum/llm-providers": {
"resolved": "../packages/llm-providers",
"link": true
diff --git a/control-ui/package.json b/control-ui/package.json
index 0e21fe746..cb7490b04 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.396",
+ "version": "0.1.397",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
@@ -49,6 +49,7 @@
"test:watch": "vitest"
},
"dependencies": {
+ "@clerum/display-field": "file:../packages/display-field",
"@clerum/llm-providers": "file:../packages/llm-providers",
"@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",
"@uiw/react-md-editor": "^4.1.0",