Validate Untrusted Input At A Single Boundary
A boundary parser that validates raw external input once and hands typed, sanitized values to the rest of the program.
Code
export type FieldKind = "string" | "number" | "boolean";
export interface FieldSpec {
readonly name: string;
readonly kind: FieldKind;
readonly required?: boolean;
readonly min?: number;
readonly max?: number;
readonly minLength?: number;
readonly maxLength?: number;
}
export type BoundaryResult<T> =
| { readonly ok: true; readonly value: T }
| { readonly ok: false; readonly violations: string[] };
function checkConstraints(spec: FieldSpec, value: string | number | boolean): string | null {
if (typeof value === "string") {
if (spec.minLength !== undefined && value.length < spec.minLength) {
return spec.name + " shorter than " + spec.minLength + " characters";
}
if (spec.maxLength !== undefined && value.length > spec.maxLength) {
return spec.name + " longer than " + spec.maxLength + " characters";
}
}
if (typeof value === "number") {
if (spec.min !== undefined && value < spec.min) {
return spec.name + " below minimum " + spec.min;
}
if (spec.max !== undefined && value > spec.max) {
return spec.name + " above maximum " + spec.max;
}
}
return null;
}
export function parseBoundary<T extends Record<string, unknown>>(
raw: unknown,
specs: readonly FieldSpec[],
): BoundaryResult<T> {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
return { ok: false, violations: ["payload must be an object"] };
}
const record = raw as Record<string, unknown>;
const violations: string[] = [];
const out: Record<string, unknown> = {};
const known = new Set(specs.map((s) => s.name));
for (const key of Object.keys(record)) {
if (!known.has(key)) violations.push("unknown field: " + key);
}
for (const spec of specs) {
const value = record[spec.name];
if (value === undefined || value === null) {
if (spec.required !== false) violations.push(spec.name + " is required");
continue;
}
if (typeof value !== spec.kind) {
violations.push(spec.name + " must be a " + spec.kind);
continue;
}
const problem = checkConstraints(spec, value as string | number | boolean);
if (problem) {
violations.push(problem);
continue;
}
out[spec.name] = value;
}
if (violations.length > 0) return { ok: false, violations };
return { ok: true, value: out as T };
}Validating in every consumer duplicates rules and drifts, while casting raw input to any hides the missing checks entirely.
Use case: engineers accepting JSON or query input from unknown clients
Inputs / outputs
- Input: a raw unknown value plus a field spec list (name, kind, constraints)
- Output: a typed record, or a list of field level rejections
Error conditions
- missing required field
- wrong primitive kind
- constraint violation (min/max/length)
- unknown field present
Approach
one pass over the spec; collect all violations; build the typed record only when the violation list is empty.
Implementation
export type FieldKind = "string" | "number" | "boolean";
export interface FieldSpec {
readonly name: string;
readonly kind: FieldKind;
readonly required?: boolean;
readonly min?: number;
readonly max?: number;
readonly minLength?: number;
readonly maxLength?: number;
}
export type BoundaryResult<T> =
| { readonly ok: true; readonly value: T }
| { readonly ok: false; readonly violations: string[] };
function checkConstraints(spec: FieldSpec, value: string | number | boolean): string | null {
if (typeof value === "string") {
if (spec.minLength !== undefined && value.length < spec.minLength) {
return spec.name + " shorter than " + spec.minLength + " characters";
}
if (spec.maxLength !== undefined && value.length > spec.maxLength) {
return spec.name + " longer than " + spec.maxLength + " characters";
}
}
if (typeof value === "number") {
if (spec.min !== undefined && value < spec.min) {
return spec.name + " below minimum " + spec.min;
}
if (spec.max !== undefined && value > spec.max) {
return spec.name + " above maximum " + spec.max;
}
}
return null;
}
export function parseBoundary<T extends Record<string, unknown>>(
raw: unknown,
specs: readonly FieldSpec[],
): BoundaryResult<T> {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
return { ok: false, violations: ["payload must be an object"] };
}
const record = raw as Record<string, unknown>;
const violations: string[] = [];
const out: Record<string, unknown> = {};
const known = new Set(specs.map((s) => s.name));
for (const key of Object.keys(record)) {
if (!known.has(key)) violations.push("unknown field: " + key);
}
for (const spec of specs) {
const value = record[spec.name];
if (value === undefined || value === null) {
if (spec.required !== false) violations.push(spec.name + " is required");
continue;
}
if (typeof value !== spec.kind) {
violations.push(spec.name + " must be a " + spec.kind);
continue;
}
const problem = checkConstraints(spec, value as string | number | boolean);
if (problem) {
violations.push(problem);
continue;
}
out[spec.name] = value;
}
if (violations.length > 0) return { ok: false, violations };
return { ok: true, value: out as T };
}
Verification tests
import { test } from "node:test";
import assert from "node:assert/strict";
import { parseBoundary } from "./example.ts";
const specs = [
{ name: "email", kind: "string" as const, minLength: 5, maxLength: 64 },
{ name: "age", kind: "number" as const, min: 0, max: 150 },
{ name: "subscribe", kind: "boolean" as const },
];
test("accepts a valid payload and types it", () => {
const result = parseBoundary(
{ email: "[email protected]", age: 30, subscribe: true },
specs,
);
assert.equal(result.ok, true);
if (result.ok) {
assert.equal(result.value.email, "[email protected]");
assert.equal(result.value.age, 30);
}
});
test("reports every violation at once", () => {
const result = parseBoundary(
{ email: "ab", age: 900 },
specs,
);
assert.equal(result.ok, false);
if (!result.ok) {
assert.ok(result.violations.some((v) => v.includes("shorter than")));
assert.ok(result.violations.some((v) => v.includes("above maximum")));
assert.ok(result.violations.some((v) => v.includes("required")));
}
});
test("rejects unknown fields", () => {
const result = parseBoundary(
{ email: "[email protected]", age: 30, subscribe: false, isAdmin: true },
specs,
);
assert.equal(result.ok, false);
if (!result.ok) {
assert.ok(result.violations.some((v) => v === "unknown field: isAdmin"));
}
});
test("rejects a non-object payload", () => {
const result = parseBoundary("nope", specs);
assert.equal(result.ok, false);
});
Dependencies and running
No external dependencies (standard library only).
Runtime: node >= 18 Entry point: node –experimental-strip-types example.ts
Limitations and error handling
flat records only (no nested objects); no coercion of strings to numbers.
Verification boundary
execution tests ran offline in an isolated temp dir with a sanitized environment; no network, no writes outside the sandbox
Interactive Tools for This Topic
Report a problem with this exampleOpens a pre-filled issue on GitHub.