Skip to content

Feature/zod validation middleware - #139

Open
dubemoyibe-star wants to merge 3 commits into
Epta-Node:mainfrom
dubemoyibe-star:feature/zod-validation-middleware
Open

Feature/zod validation middleware#139
dubemoyibe-star wants to merge 3 commits into
Epta-Node:mainfrom
dubemoyibe-star:feature/zod-validation-middleware

Conversation

@dubemoyibe-star

@dubemoyibe-star dubemoyibe-star commented Jul 19, 2026

Copy link
Copy Markdown

Zod Schema Validation Middleware for API Request Bodies

Overview

API endpoints in backend/src/api/routes/ and backend/src/api/app.ts performed
ad-hoc, inline validation (if (!taskName || !prompt) ...). This led to
inconsistent validation, missing edge cases, and error responses that leaked
internal Zod details (parse.error.flatten()).

This change introduces a reusable validate() middleware backed by centralized
Zod schemas, enforcing a consistent { error, details } 400 contract across
every API endpoint. Input is sanitized (strings trimmed, numbers coerced) and
TypeScript types are derived from the schemas via z.infer — no manual
duplication.

zod (^3.23.8) was already a transitive dependency in package.json; no new
dependency was required.

Files

New

File Purpose
backend/src/api/schemas/common.schema.ts Shared fragments: TaskStatusSchema, PaginationQuerySchema, IdParamSchema, trimmedString() helper. Exports inferred types.
backend/src/api/schemas/task.schema.ts CreateTaskSchema, TaskQuerySchema, TaskIdParamSchema (+ inferred input types).
backend/src/api/schemas/agent.schema.ts RegisterAgentSchema, AgentListQuerySchema, AgentIdParamSchema (+ inferred input types).
backend/src/api/middleware/validate.ts Reusable validate({ body, query, params }) middleware.
backend/tests/validation.test.ts Unit tests for the middleware and schemas (no SQLite needed).

Modified

File Change
backend/src/api/app.ts POST/GET/DELETE /api/tasks now use validate() + shared task schemas, replacing inline checks.
backend/src/api/routes/agents.ts All :id params, the agent list query, and the register body now use validate() + shared agent schemas.
backend/src/api/routes/tasks.ts Router rewritten to use validate() + shared task schemas (consistent with app.ts).

The validate() middleware

router.post("/tasks", validate({ body: CreateTaskSchema }), handler);
  • Validates req.body, req.query, and/or req.params against the supplied
    Zod schemas.
  • On failure responds with 400 and a structured body:
    { "error": "Validation failed", "details": [{ "path": "body.prompt", "message": "prompt is required" }] }
  • Does not leak Zod internals — only path + human-readable message.
  • Sanitizes input on the way through: trimmedString strips surrounding
    whitespace (and rejects whitespace-only), z.coerce.number() turns query
    strings into real numbers. Parsed values are written back onto req so
    downstream handlers receive the cleaned, coerced data.

Schema highlights

  • CreateTaskSchema: prompt (trimmed, 1–10000 chars), maxBudgetXLM
    (>= 0.1), optional agentPreferences[] and walletPublicKey.
  • TaskQuerySchema: pagination (page, pageSize coerced + clamped 1–100),
    optional status enum, sort enum (default createdAt:desc), optional q.
  • RegisterAgentSchema: trimmed agentId, non-empty capabilities[],
    pricingXLM >= 0, endpoint URL, trimmed stellarPublicKey.
  • AgentListQuerySchema: optional capability, coerced minReputation /
    maxPriceXLM, status enum.

Acceptance criteria status

  • Zod schemas defined for all API endpoints (tasks + agents).
  • validate() middleware exists and is reusable.
  • Invalid requests return { error: string, details: FieldError[] }.
  • Input sanitized (trim strings, coerce numbers).
  • TypeScript types derived from Zod schemas (z.infer) — no manual duplication.
  • Applied to existing routes (app.ts, routes/agents.ts, routes/tasks.ts).

Validation

  • npx tsc -p tsconfig.json --noEmit → passes.
  • npx jest tests/validation.test.ts → 6/6 pass (covers 400 shape, trimming,
    numeric coercion, enum rejection, agent registration).
  • tests/middleware.test.ts and other non-DB suites continue to pass.

Known environment limitation

The SQLite-backed suites (tests/tasks.test.ts, tests/agents.test.ts,
tests/replay.test.ts, tests/e2e/stream.test.ts) currently fail to load
in this sandbox because the native better-sqlite3 addon is not compiled for
the installed Node 24 runtime (no Visual Studio build tools available to rebuild
it). This is pre-existing and unrelated to this change — it occurs at
createApp → createEventStore before any validation runs (confirmed via
git stash on the original code). The validation logic is covered directly by
tests/validation.test.ts, which exercises the real middleware and schemas over
HTTP without needing SQLite.

Examples

Before:

const parse = CreateTaskSchema.safeParse(req.body);
if (!parse.success) {
  res.status(400).json({ error: parse.error.flatten() }); // leaks internals
  return;
}

After:

router.post("/", validate({ body: CreateTaskSchema }), (req, res) => {
  const { prompt } = req.body as CreateTaskInput; // sanitized + typed
  // ...
});

Closes #106

@vercel

vercel Bot commented Jul 19, 2026

Copy link
Copy Markdown

@dubemoyibe-star is attempting to deploy a commit to the Jaja's projects Team on Vercel.

A member of the Team first needs to authorize it.

@devJaja
devJaja self-requested a review July 20, 2026 23:36
@devJaja

devJaja commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

Resolve the conflicts @dubemoyibe-star

@devJaja

devJaja commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

Nice Implementation @dubemoyibe-star
Fix the CI checks failing

@dubemoyibe-star

Copy link
Copy Markdown
Author

Nice Implementation @dubemoyibe-star Fix the CI checks failing

Ok then
I'm on it

@devJaja

devJaja commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

@dubemoyibe-star
Still waiting for the changes

@devJaja

devJaja commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

@dubemoyibe-star Resolve the conflicts please

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Backend] Add Zod Schema Validation Middleware for API Request Bodies

2 participants