Implementing Message Validation
1. Validating Message Format
| Layer | Check |
|---|---|
| Transport | Frame size ≤ limit |
| Encoding | Valid UTF-8 / valid binary header |
| Envelope | Required fields present |
| Payload | Type-specific schema |
2. Using Validation Libraries
| Library | Lang | Strength |
|---|---|---|
| zod | TS | Type inference, ergonomic |
| valibot | TS | Tree-shakable, smaller |
| ajv | JS | Fast JSON Schema |
| joi | JS | Mature, server-oriented |
| Pydantic | Python | Server-side parity |
3. Sanitizing Input Data
| Threat | Action |
|---|---|
| XSS (rendered text) | Escape on render (DOMPurify) |
| SQL injection | Parameterized queries |
| Path traversal | Strip ../ from paths |
| Prototype pollution | Reject keys: __proto__, constructor |
4. Validating Message Types
Example: Discriminated union
const Msg = z.discriminatedUnion("type", [
z.object({ "type": z.literal("chat"), "text": z.string() }),
z.object({ "type": z.literal("typing"), "userId": z.string() }),
]);
| Pattern | Detail |
|---|---|
| Allowlist | Reject unknown types |
| Discriminator | Single field selects schema |
| Version tag | Route to right validator |
5. Checking Required Fields
| Tool | Syntax |
|---|---|
| zod | z.string() required by default |
| JSON Schema | "required": ["id","type"] |
| Manual | if (!msg.id) reject() |
6. Validating Data Types
| Type | Validator |
|---|---|
| string | z.string() |
| number | z.number().finite() |
| UUID | z.string().uuid() |
| URL | z.string().url() |
| enum | z.enum([...]) |
| date | z.string().datetime() |
7. Enforcing Length Limits
| Field | Suggested Limit |
|---|---|
| Chat text | 2000 chars |
| Username | 32 chars |
| Channel name | 64 chars |
| Total message | 64 KB |
8. Validating Ranges
Example: Numeric range
z.number().int().min(0).max(100); // percent
z.number().gte(-90).lte(90); // latitude
| Check | Method |
|---|---|
| Min/Max | .min(n)/.max(n) |
| Inclusive | .gte/.lte |
| Multiple of | .multipleOf(n) |
9. Using Custom Validators
| Hook | Use |
|---|---|
.refine() | Boolean check |
.superRefine() | Multi-issue |
.transform() | Coerce + validate |
10. Handling Validation Errors
| Strategy | When |
|---|---|
| Drop + log | Untrusted traffic |
| Send error msg | Trusted client (UX feedback) |
| Close 1008 (policy) | Repeated abuse |
| Rate-limit sender | Combined with above |