Skip to content

Validation at the trust boundary

A partner’s CI system posts a webhook to Relay with items[2].id set to the number 7. Relay’s handler does JSON.parse(text) as Webhook. The cast compiles, so the 7 goes into the job queue, and a worker later calls id.startsWith("ci-") on it and crashes. The crash is far from the cause, and the log says nothing about the request that started it.

The trust boundary is the line where bytes from outside become values inside. Everything on the outside is unknown. Lesson 5 of M2 wrote one parser by hand. A real API has many bodies, so this lesson builds a small reusable kit, and puts two checks in front of it that a parser alone cannot do.

await request.json() reads the whole body into memory before you can say no. A 2 GB body is a denial of service. Check the size before parsing, in two steps. The content-length header is cheap but the client chooses it, so also count the bytes as they arrive and stop when the limit is passed:

async function readLimited(request: Request, maxBytes: number): Promise<string | null> {
if (Number(request.headers.get("content-length") ?? 0) > maxBytes) return null
if (request.body === null) return ""
const chunks: Uint8Array[] = []
let size = 0
for await (const chunk of request.body) {
size += chunk.byteLength
if (size > maxBytes) return null
chunks.push(chunk)
}
return new TextDecoder().decode(Buffer.concat(chunks))
}

Returning from the for await loop cancels the stream, so the rest of the body is never read. Web Streams shows the same limit as a TransformStream. A chunked request has no content-length, which is why the byte count is needed too.

Check the signature before you trust anything

Section titled “Check the signature before you trust anything”

Relay’s webhook sources sign each body with a shared secret (HMAC-SHA256) and send the signature in a header. A body without a valid signature may come from anyone, so Relay should not even parse it:

const encoder = new TextEncoder()
function fromHex(hex: string): Uint8Array<ArrayBuffer> | null {
if (hex.length % 2 !== 0 || !/^[0-9a-f]*$/i.test(hex)) return null
return Uint8Array.from(hex.match(/../g) ?? [], (byte) => Number.parseInt(byte, 16))
}
async function verifySignature(secret: string, body: string, signatureHex: string): Promise<boolean> {
const signature = fromHex(signatureHex)
if (signature === null) return false
const key = await crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["verify"])
return crypto.subtle.verify("HMAC", key, signature, encoder.encode(body))
}

Two details prevent real bugs. The signature covers the raw text, so verify before JSON.parse: re-serializing parsed JSON changes whitespace and key order, and the signatures stop matching. And crypto.subtle.verify is built for this check, so use it instead of comparing. Comparing hex strings with === stops at the first different character, and the response time leaks how much of a forged signature was right.

So the order is: size, then signature, then parse, then decode. Each step runs only if the one before it passed, and each failure has its own status (413, 401, 400, 400).

The decoder from M2 returned a type. To build bodies from parts, make the decoder a value: a function from unknown and a path to a result.

type DecodeResult<T> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly error: string }
type Decoder<T> = (input: unknown, path: string) => DecodeResult<T>
const string: Decoder<string> = (input, path) =>
typeof input === "string" ? { ok: true, value: input } : { ok: false, error: `${path}: expected string` }
const number: Decoder<number> = (input, path) =>
typeof input === "number" && Number.isFinite(input)
? { ok: true, value: input }
: { ok: false, error: `${path}: expected number` }
console.log(string("a", "body.id"), number("1", "body.attempts"))

path is a string like body.items[2].id. Each decoder that goes deeper extends it, so the failure says where the data is wrong. number rejects NaN and Infinity: JSON cannot produce them, but a decoder is also used on values that did not come from JSON.

array, object, literal and union take decoders and return a decoder. The interesting one is object. Its output type is computed from the shape you give it:

type DecodeResult<T> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly error: string }
type Decoder<T> = (input: unknown, path: string) => DecodeResult<T>
type Infer<D> = D extends Decoder<infer T> ? T : never
declare const string: Decoder<string>
function object<S extends Record<string, Decoder<unknown>>>(shape: S): Decoder<{ [K in keyof S]: Infer<S[K]> }>
function object(shape: Record<string, Decoder<unknown>>): Decoder<Record<string, unknown>> {
return (input, path) => {
if (typeof input !== "object" || input === null || Array.isArray(input)) {
return { ok: false, error: `${path}: expected object` }
}
const out: Record<string, unknown> = {}
for (const [key, field] of Object.entries(shape)) {
const r = field(Object.hasOwn(input, key) ? Reflect.get(input, key) : undefined, `${path}.${key}`)
if (!r.ok) return r
out[key] = r.value
}
return { ok: true, value: out }
}
}
const delivery = object({ id: string, source: string })
type Delivery = Infer<typeof delivery> // { id: string; source: string }

Infer<typeof delivery> is the point of the kit. You describe the shape once, as a value, and the type is derived from it. They cannot drift apart, which is the bug that as Webhook hides.

The overload is the same trick as matchRoute in M4: the public signature computes a precise type, and the implementation only sees Decoder<unknown>s. The two are compatible, so no cast is needed.

Three choices in object come from real incidents:

  • Object.hasOwn makes an inherited key count as missing. A body {"constructor": ...} or {"toString": ...} must not satisfy a field by accident.
  • The output holds only the keys in the shape. Extra keys the sender added ("admin": true) are dropped here, so they cannot travel further into Relay.
  • The first failing field returns at once. One path is a clear message. Collecting every problem is validation that accumulates, which is more work for the caller to read.

literal("ci") accepts exactly that value, and its type is the literal "ci". union tries each variant and takes the first that succeeds:

type DecodeResult<T> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly error: string }
type Decoder<T> = (input: unknown, path: string) => DecodeResult<T>
type Infer<D> = D extends Decoder<infer T> ? T : never
function literal<const V extends string | number | boolean>(expected: V): Decoder<V> {
return (input, path) =>
input === expected ? { ok: true, value: expected } : { ok: false, error: `${path}: expected ${JSON.stringify(expected)}` }
}
function union<const Ds extends readonly Decoder<unknown>[]>(...variants: Ds): Decoder<Infer<Ds[number]>>
function union(...variants: readonly Decoder<unknown>[]): Decoder<unknown> {
return (input, path) => {
for (const variant of variants) {
const r = variant(input, path)
if (r.ok) return r
}
return { ok: false, error: `${path}: no variant matched` }
}
}
const source = union(literal("ci"), literal("cron"))
type Source = Infer<typeof source> // "ci" | "cron"

const on the type parameter keeps "ci" as a literal instead of widening it to string. The union’s own message is deliberately short: for objects tagged with a type field, check the tag with literal in each variant so the failing path points at the tag.

With the kit, the body that caused the crash is one declaration, and its type is derived:

type DecodeResult<T> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly error: string }
type Decoder<T> = (input: unknown, path: string) => DecodeResult<T>
type Infer<D> = D extends Decoder<infer T> ? T : never
declare const string: Decoder<string>
declare const number: Decoder<number>
declare function array<T>(item: Decoder<T>): Decoder<T[]>
declare function object<S extends Record<string, Decoder<unknown>>>(shape: S): Decoder<{ [K in keyof S]: Infer<S[K]> }>
const webhookBody = object({
delivery: string,
items: array(object({ id: string, attempts: number })),
})
type Webhook = Infer<typeof webhookBody>
declare const json: unknown
const result = webhookBody(json, "body")
if (!result.ok) console.log(result.error) // body.items[2].id: expected string
else console.log(result.value.items.length)

The partner’s body now fails at the door with body.items[2].id: expected string, and the handler answers 400 with that message. The sender can fix their bug without asking you for logs.

Build the kit and the webhook decoder. The starter coerces values (String(input)) instead of checking them, and object copies whatever it is given. The header lists each rule and message.

  • Everything from the network is unknown. Decode it once, at the edge, and pass typed values inward.
  • Order the checks: size (header, then counted bytes), signature (on the raw text), parse, decode.
  • A decoder (input: unknown, path: string) => DecodeResult<T> is a plain function. Infer derives the type from the decoder, so type and check cannot drift.
  • Error paths such as body.items[2].id turn a crash in a worker into a precise 400.
  • Use Object.hasOwn, drop extra keys, and use a const type parameter to keep literals.