Merge feature/input-validation: Standard Schema validation of handler args
CI / build (push) Has been cancelled

RC blocker B complete. @body/@query/@param/@headers accept any Standard Schema
(~standard: zod/valibot/arktype) — core stays zero-dep. resolveArgs is async and
validates: parsed/coerced value goes to the handler arg (ctx stays raw), invalid
→ 422 { error, source, issues } via ValidationError (checked before HttpError).
Handler run is async; WS open awaits it. Fail-fast; async schemas awaited;
throwing validate → 500. Plan review caught the WS async-await resequencing
before implementation.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-07-06 21:51:55 -05:00
commit b8670772e9
11 files changed
+289 -23

No files matched your search

+63
View File
@@ -369,6 +369,69 @@ const app = createApp({ modules: [ApiModule], limits: { maxParts: 500 } });
A malformed multipart body (bad boundary, missing headers, truncated part) → 400.
## 9. Validation
`@body`, `@query`, `@headers`, and `@param` accept an optional **Standard Schema**
(the [`~standard` interface](https://standardschema.dev) shared by zod, valibot, arktype,
and others). green-tea's core has **zero runtime dependency** on any of them — bring
whichever validator you already use:
```typescript
import { z } from 'zod';
import { Route, Post, body } from '@green-tea/core';
const CreateUser = z.object({ email: z.string().email() });
@Route('/users')
class UserController {
@Post('/')
create(@body(CreateUser) user: { email: string }) {
return { created: user.email };
}
}
```
The value the handler receives is the schema's **parsed/coerced output**, not the raw
input — `ctx.body` (via `@ctx()` or a `@needs`-fed step) stays exactly what the transport
parsed. Query strings are always strings on the wire, so a schema is often the coercion
point:
```typescript
const ListQuery = z.object({ page: z.coerce.number() });
@Get('/list')
list(@query(ListQuery) q: { page: number }) {
return { page: q.page, isNum: typeof q.page === 'number' }; // GET /list?page=2 → true
}
```
> **Access shape (asymmetry).** `@param('id', Schema)` takes the key in slot 1 and the schema
> in slot 2 — `@param` always needs a name to say which route param it binds. `@body(Schema)`,
> `@query(Schema)`, and `@headers(Schema)` take the schema as their only argument, validating
> the whole parsed object (all of `body`/`query`/`headers`).
A failing schema short-circuits the request with **422**:
```json
{ "error": "Validation failed", "source": "body", "issues": [{ "path": "email", "message": "Invalid email" }] }
```
`source` is which envelope failed (`'body' | 'query' | 'params' | 'headers'`); `issues` is
the schema's issues flattened to `{ path, message }` (`path` is dot-joined).
**Caveats:**
- **Fail-fast.** Arguments validate in order; the **first** failing one throws — later args in
the same handler are not checked in that request.
- **Steps see raw input.** Only the resolved handler argument is coerced/validated; a `@Step`
reading the same data via `ctx.body`/`ctx.query`/etc. always sees the untouched value.
- **A throwing schema is a 500, not a 422.** The Standard Schema contract says `validate()`
returns `{ issues }` on failure — it isn't supposed to throw. If it does anyway, that
propagates as an uncaught error (→ 500), since it signals a bug in the schema, not user input.
- **Async schemas are awaited** — `validate()` returning a `Promise` works transparently.
**Not covered yet:** response/output validation, validating a `@Step`'s own inputs, and
mesh remote-route validation are all out of scope for this feature.
## Inspect & test the graph
### Visualize with Mermaid
+3 -3
View File
@@ -43,7 +43,7 @@ interface RoutePlan {
steps: GraphNode[];
handlerName: string;
needs: string[];
run: (ctx: any) => unknown;
run: (ctx: any) => Promise<unknown>;
transformer: typeof JsonTransformer;
duplicates?: 'array' | 'last';
}
@@ -114,7 +114,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
steps: [],
handlerName: route.handlerName,
needs: getHandlerNeeds(argSpecs),
run: (c: any) => inst[route.handlerName](...resolveArgs(argSpecs, c)),
run: async (c: any) => inst[route.handlerName](...(await resolveArgs(argSpecs, c))),
transformer: getTransformer(C, route.handlerName) ?? JsonTransformer,
duplicates: route.duplicates,
});
@@ -358,7 +358,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
headers: req.headers, inbound, abort,
protocol: (req.socket as any).encrypted ? 'https' : 'http', ip: req.socket.remoteAddress ?? '' };
for (const s of planSteps(plan)) { ctx = { ...ctx, ...(await s.run(ctx)) }; }
const out = plan.run(ctx);
const out = await plan.run(ctx);
if (!isAsyncIterable(out)) throw new Error(`@Ws handler '${plan.handlerName}' must return an AsyncIterable`);
return out as AsyncIterable<unknown>;
},
+2 -1
View File
@@ -8,7 +8,7 @@ export type { GraphView } from './graph-viz';
export { Provider, Step, Route, Get, Module, Transformer } from './metadata';
export type { Plugin } from './plugin';
export { JsonTransformer } from './transformers';
export { HttpError, Unauthorized, NotFound, Redirect, NotModified } from './signals';
export { HttpError, Unauthorized, NotFound, Redirect, NotModified, ValidationError } from './signals';
export { Bus } from './bus';
export { flow, Flow } from './flow';
export type { StepFn, CompiledFlow } from './flow';
@@ -26,6 +26,7 @@ export type { MeshConfig } from './app';
export type { RequestLimits } from './http';
export type { TlsOptions, CorsOptions, SecurityOptions } from './security';
export type { UploadedFile, MultipartBody } from './multipart';
export type { StandardSchemaV1 } from './standard-schema';
export { connectLink } from './mesh/link';
export { buildRemote, envelopeFrom } from './mesh/teacup';
export { buildManifest, createMeshControl, MESH_CONTROL_PATH } from './mesh/teapot';
+23 -9
View File
@@ -1,12 +1,14 @@
import 'reflect-metadata';
import type { Ctor } from './metadata';
import { isStandardSchema, type StandardSchemaV1 } from './standard-schema';
import { ValidationError } from './signals';
export type Query = Record<string, string>;
export type Headers = Record<string, string | string[] | undefined>;
export type Context = Record<string, unknown>;
type ArgSource = 'ctx' | 'needs' | 'params' | 'query' | 'body' | 'headers' | 'inbound' | 'abort';
export interface ArgSpec { index: number; source: ArgSource; key?: string; keys?: string[] }
export interface ArgSpec { index: number; source: ArgSource; key?: string; keys?: string[]; schema?: StandardSchemaV1 }
const ARGS = Symbol('gt:args');
@@ -21,13 +23,17 @@ function record(target: object, methodKey: string | symbol | undefined, spec: Ar
}
function envelope(source: ArgSource) {
return (arg?: string | string[]): ParameterDecorator =>
return (arg?: string | string[] | StandardSchemaV1, schema?: StandardSchemaV1): ParameterDecorator =>
(target, methodKey, index) => {
const spec: ArgSpec = Array.isArray(arg)
? { index, source, keys: arg }
: typeof arg === 'string'
? { index, source, key: arg }
: { index, source };
const spec: ArgSpec = { index, source };
if (Array.isArray(arg)) spec.keys = arg;
else if (typeof arg === 'string') spec.key = arg;
else if (isStandardSchema(arg)) spec.schema = arg;
else if (arg !== undefined) throw new Error(`@${source}: expected a Standard Schema or a string/array key`);
if (schema !== undefined) {
if (!isStandardSchema(schema)) throw new Error(`@${source}: second argument must be a Standard Schema`);
spec.schema = schema;
}
record(target, methodKey, spec);
};
}
@@ -62,11 +68,19 @@ export function getHandlerNeeds(specs: ArgSpec[]): string[] {
return specs.filter((s) => s.source === 'needs' && s.key).map((s) => s.key as string);
}
export function resolveArgs(specs: ArgSpec[], context: Context): unknown[] {
export async function resolveArgs(specs: ArgSpec[], context: Context): Promise<unknown[]> {
if (specs.length === 0) return [];
const max = Math.max(...specs.map((s) => s.index));
const args: unknown[] = new Array(max + 1).fill(undefined);
for (const s of specs) args[s.index] = resolveOne(s, context);
for (const s of specs) {
let value = resolveOne(s, context);
if (s.schema) {
const result = await s.schema['~standard'].validate(value);
if (result.issues) throw new ValidationError([...result.issues], s.source);
value = result.value;
}
args[s.index] = value;
}
return args;
}
+8
View File
@@ -1,3 +1,5 @@
import type { StandardIssue } from './standard-schema';
export class HttpError extends Error {
constructor(readonly status: number, message?: string, readonly body?: unknown) {
super(message ?? `HTTP ${status}`);
@@ -21,6 +23,12 @@ export class Redirect extends HttpError {
constructor(readonly location: string) { super(302); }
}
export class ValidationError extends HttpError {
constructor(public issues: StandardIssue[], public source: string) {
super(422, 'Validation failed');
}
}
export function isHttpError(e: unknown): e is HttpError {
return e instanceof HttpError;
}
+34
View File
@@ -0,0 +1,34 @@
// src/standard-schema.ts — vendored Standard Schema (~standard) types + helpers. No imports.
export interface StandardSchemaV1<Input = unknown, Output = Input> {
readonly '~standard': {
readonly version: 1;
readonly vendor: string;
validate(value: unknown): StandardResult<Output> | Promise<StandardResult<Output>>;
readonly types?: { readonly input: Input; readonly output: Output };
};
}
export type StandardResult<T> =
| { readonly value: T; readonly issues?: undefined }
| { readonly issues: ReadonlyArray<StandardIssue> };
export interface StandardIssue {
readonly message: string;
readonly path?: ReadonlyArray<PropertyKey | { readonly key: PropertyKey }>;
}
export function isStandardSchema(x: unknown): x is StandardSchemaV1 {
return (
typeof x === 'object' && x !== null &&
'~standard' in x &&
typeof (x as { ['~standard']?: { validate?: unknown } })['~standard']?.validate === 'function'
);
}
export function flattenPath(issue: StandardIssue): string {
if (!issue.path) return '';
return issue.path
.map((seg) => (typeof seg === 'object' && seg !== null && 'key' in seg ? seg.key : seg))
.map((k) => String(k))
.join('.');
}
+13 -1
View File
@@ -1,5 +1,6 @@
import { isHttpError, Redirect } from './signals';
import { isHttpError, Redirect, ValidationError } from './signals';
import type { TransformerFn } from './metadata';
import { flattenPath } from './standard-schema';
export const JsonTransformer: TransformerFn = (value) => ({
status: 200,
@@ -8,6 +9,17 @@ export const JsonTransformer: TransformerFn = (value) => ({
});
export function errorToResponse(e: unknown): { status: number; headers: Record<string, string>; body: string } {
if (e instanceof ValidationError) {
return {
status: 422,
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
error: 'Validation failed',
source: e.source,
issues: e.issues.map((i) => ({ path: flattenPath(i), message: i.message })),
}),
};
}
if (isHttpError(e)) {
const headers: Record<string, string> = { 'content-type': 'application/json' };
if (e instanceof Redirect) headers.location = e.location;
+58 -7
View File
@@ -1,6 +1,7 @@
import 'reflect-metadata';
import { expect, test, describe, it } from 'vitest';
import { needs, ctx, param, query, inbound, abort, getArgs, getHandlerNeeds, resolveArgs } from '../src/params';
import { needs, ctx, param, query, body, inbound, abort, getArgs, getHandlerNeeds, resolveArgs } from '../src/params';
import { ValidationError } from '../src/signals';
class Ctl {
handler(
@@ -27,13 +28,13 @@ test('getHandlerNeeds extracts only @needs keys', () => {
expect(getHandlerNeeds(getArgs(Ctl, 'handler'))).toEqual(['user']);
});
test('resolveArgs builds positional args from context', () => {
test('resolveArgs builds positional args from context', async () => {
const context = {
user: { id: 'u1' },
params: { id: '7' },
query: { a: '1', b: '2', c: '3' },
};
const args = resolveArgs(getArgs(Ctl, 'handler'), context);
const args = await resolveArgs(getArgs(Ctl, 'handler'), context);
expect(args[0]).toEqual({ id: 'u1' });
expect(args[1]).toBe('7');
expect(args[2]).toEqual({ a: '1', b: '2', c: '3' });
@@ -41,18 +42,18 @@ test('resolveArgs builds positional args from context', () => {
expect(args[4]).toBe(context);
});
test('a handler with no arg decorators resolves to no args', () => {
test('a handler with no arg decorators resolves to no args', async () => {
class Bare { ping() { return 1; } }
expect(resolveArgs(getArgs(Bare, 'ping'), {})).toEqual([]);
expect(await resolveArgs(getArgs(Bare, 'ping'), {})).toEqual([]);
});
describe('@inbound / @abort', () => {
it('resolves inbound and abort from reserved context keys, not as bags', () => {
it('resolves inbound and abort from reserved context keys, not as bags', async () => {
class Ctl { handle(@inbound() inc: AsyncIterable<unknown>, @abort() sig: AbortSignal) { return [inc, sig]; } }
const specs = getArgs(Ctl, 'handle');
const ac = new AbortController();
const inc = (async function* () {})();
const args = resolveArgs(specs, { inbound: inc, abort: ac.signal });
const args = await resolveArgs(specs, { inbound: inc, abort: ac.signal });
expect(args[0]).toBe(inc);
expect(args[1]).toBe(ac.signal);
});
@@ -62,3 +63,53 @@ describe('@inbound / @abort', () => {
expect(getHandlerNeeds(getArgs(Ctl, 'handle'))).toEqual([]);
});
});
const numFromStr = {
'~standard': {
version: 1 as const, vendor: 'test',
validate: (v: unknown) => {
const n = Number(v);
return Number.isNaN(n) ? { issues: [{ message: 'not a number', path: ['n'] }] } : { value: n };
},
},
};
const asyncSchema = {
'~standard': { version: 1 as const, vendor: 'test', validate: async (v: unknown) => ({ value: `async:${v}` }) },
};
describe('resolveArgs validation', () => {
it('valid: substitutes the parsed/coerced value; ctx source untouched', async () => {
class C { m(@query(numFromStr) _q: number) {} }
const specs = getArgs(C, 'm');
const ctx: any = { query: '42' };
const args = await resolveArgs(specs, ctx);
expect(args[0]).toBe(42);
expect(ctx.query).toBe('42');
});
it('invalid: throws ValidationError with source', async () => {
class C { m(@body(numFromStr) _b: number) {} }
const specs = getArgs(C, 'm');
await expect(resolveArgs(specs, { body: 'nope' })).rejects.toBeInstanceOf(ValidationError);
await resolveArgs(specs, { body: 'nope' }).catch((e) => { expect(e.source).toBe('body'); expect(e.issues[0].message).toBe('not a number'); });
});
it('async schema is awaited', async () => {
class C { m(@body(asyncSchema) _b: string) {} }
const args = await resolveArgs(getArgs(C, 'm'), { body: 'x' });
expect(args[0]).toBe('async:x');
});
it('@param(name, schema) validates the named param (slot-2 schema)', async () => {
class C { m(@param('id', numFromStr) _id: number) {} }
const args = await resolveArgs(getArgs(C, 'm'), { params: { id: '7' } });
expect(args[0]).toBe(7);
});
it('non-schema decorators unchanged: @body("key"), @body(), @query(["a","b"])', async () => {
class C { m(@body('x') _x: any, @body() _b: any, @query(['a', 'b']) _q: any) {} }
const args = await resolveArgs(getArgs(C, 'm'), { body: { x: 1, y: 2 }, query: { a: 'A', b: 'B', c: 'C' } });
expect(args[0]).toBe(1);
expect(args[1]).toEqual({ x: 1, y: 2 });
expect(args[2]).toEqual({ a: 'A', b: 'B' });
});
it('decoration-time guard: a non-schema object throws', () => {
expect(() => { class C { m(@body({} as any) _b: any) {} } return C; }).toThrow();
});
});
+23
View File
@@ -0,0 +1,23 @@
import { describe, it, expect } from 'vitest';
import { isStandardSchema, flattenPath } from '../src/standard-schema';
const schema = { '~standard': { version: 1, vendor: 't', validate: (v: unknown) => ({ value: v }) } };
describe('isStandardSchema', () => {
it('true for a Standard Schema, false for string/array/plain object/null', () => {
expect(isStandardSchema(schema)).toBe(true);
expect(isStandardSchema('id')).toBe(false);
expect(isStandardSchema(['a', 'b'])).toBe(false);
expect(isStandardSchema({})).toBe(false);
expect(isStandardSchema(null)).toBe(false);
expect(isStandardSchema({ '~standard': {} })).toBe(false); // no validate fn
});
});
describe('flattenPath', () => {
it('flattens key + {key} segments to a dot string', () => {
expect(flattenPath({ message: 'x', path: ['address', 'city'] })).toBe('address.city');
expect(flattenPath({ message: 'x', path: ['items', 0, { key: 'qty' }] })).toBe('items.0.qty');
expect(flattenPath({ message: 'x' })).toBe('');
});
});
+19 -2
View File
@@ -1,6 +1,6 @@
import { expect, test } from 'vitest';
import { describe, expect, it, test } from 'vitest';
import { JsonTransformer, errorToResponse } from '../src/transformers';
import { Unauthorized, Redirect } from '../src/signals';
import { HttpError, Unauthorized, Redirect, ValidationError } from '../src/signals';
test('JsonTransformer serializes value with json content-type', () => {
expect(JsonTransformer({ a: 1 })).toEqual({
@@ -21,3 +21,20 @@ test('errorToResponse sets location for Redirect', () => {
test('unknown error becomes 500', () => {
expect(errorToResponse(new Error('boom')).status).toBe(500);
});
describe('errorToResponse ValidationError', () => {
it('maps ValidationError to 422 with source + flattened issues (before generic HttpError)', () => {
const err = new ValidationError([{ message: 'Invalid email', path: ['email'] }], 'body');
const r = errorToResponse(err);
expect(r.status).toBe(422);
expect(JSON.parse(r.body)).toEqual({
error: 'Validation failed', source: 'body',
issues: [{ path: 'email', message: 'Invalid email' }],
});
});
it('still maps a plain HttpError to { error: message }', () => {
const r = errorToResponse(new HttpError(403, 'Nope'));
expect(r.status).toBe(403);
expect(JSON.parse(r.body)).toEqual({ error: 'Nope' });
});
});
+43
View File
@@ -0,0 +1,43 @@
import { describe, it, expect, afterEach } from 'vitest';
import { createApp, Route, Get, Post, Module, body, query, param } from '../src';
const numQuery = { '~standard': { version: 1 as const, vendor: 't', validate: (v: any) => {
const n = Number(v?.page); return Number.isNaN(n) ? { issues: [{ message: 'bad', path: ['page'] }] } : { value: { page: n } }; } } };
const userBody = { '~standard': { version: 1 as const, vendor: 't', validate: (v: any) =>
(typeof v?.email === 'string' && v.email.includes('@')) ? { value: v } : { issues: [{ message: 'Invalid email', path: ['email'] }] } } };
const idParam = { '~standard': { version: 1 as const, vendor: 't', validate: (v: any) => {
const n = Number(v); return Number.isNaN(n) ? { issues: [{ message: 'nan', path: [] }] } : { value: n }; } } };
let app: any;
afterEach(async () => { await app?.close(); });
describe('validation over http', () => {
it('valid body → 200 with parsed value; query coerced to number; param coerced', async () => {
@Route('/') class C {
@Post('/u') create(@body(userBody) b: any) { return { ok: b.email }; }
@Get('/list') list(@query(numQuery) q: any) { return { page: q.page, isNum: typeof q.page === 'number' }; }
@Get('/u/:id') get(@param('id', idParam) id: any) { return { id, isNum: typeof id === 'number' }; }
}
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
app = createApp({ modules: [CMod] });
const server = await app.listen(0);
const port = (server.address() as any).port;
const ok = await fetch(`http://127.0.0.1:${port}/u`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ email: 'a@b.com' }) });
expect(await ok.json()).toEqual({ ok: 'a@b.com' });
const li = await fetch(`http://127.0.0.1:${port}/list?page=2`);
expect(await li.json()).toEqual({ page: 2, isNum: true });
const g = await fetch(`http://127.0.0.1:${port}/u/7`);
expect(await g.json()).toEqual({ id: 7, isNum: true });
});
it('invalid body → 422 with source + issues', async () => {
@Route('/') class C { @Post('/u') create(@body(userBody) b: any) { return b; } }
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
app = createApp({ modules: [CMod] });
const server = await app.listen(0);
const port = (server.address() as any).port;
const r = await fetch(`http://127.0.0.1:${port}/u`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ email: 'nope' }) });
expect(r.status).toBe(422);
expect(await r.json()).toEqual({ error: 'Validation failed', source: 'body', issues: [{ path: 'email', message: 'Invalid email' }] });
});
});