Skip to content

Commit 5acd57b

Browse files
committed
fix(validator): read multipart and URL-encoded bodies
withValidator parses form bodies through parseBody, restores bracketed fields as nested objects and arrays, and leaves JSON bodies on json().
1 parent 31745e8 commit 5acd57b

4 files changed

Lines changed: 355 additions & 3 deletions

File tree

‎docs/guide/pages-routing/actions-and-forms.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -443,6 +443,8 @@ export const action = defineHandler(async (c) => {
443443
});
444444
```
445445

446+
`withValidator({ body })` accepts the same upload. Nested names such as `profile[name]`, `tags[0]`, and `tags[]` are objects and arrays again. A multipart schema has to coerce the rest: booleans arrive as `'1'` or `'0'`, numbers and dates as strings, and `null` as `''`.
447+
446448
Pick the storage key on the server and allow only the file types you expect. See [Serving Files](../storage.md#serving-files) to send them back safely.
447449

448450
## Choosing a Primitive

‎packages/void/src/runtime/validator.ts‎

Lines changed: 174 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,172 @@ async function validateSlot(
4545
return { ok: true, value: result.value };
4646
}
4747

48+
type FormEntry = string | File;
49+
50+
const MAX_FORM_DEPTH = 32;
51+
const MAX_FORM_NODES = 10_000;
52+
const MAX_FORM_INDEX = 10_000;
53+
const DANGEROUS_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
54+
55+
function isFormContentType(contentType: string | undefined): boolean {
56+
const mediaType = contentType?.split(';', 1)[0]?.trim().toLowerCase();
57+
return mediaType === 'multipart/form-data' || mediaType === 'application/x-www-form-urlencoded';
58+
}
59+
60+
/**
61+
* `objectToFormData` writes nested fields as `a[b]`, array items as `a[0]`,
62+
* and file lists as `a[]`. Split one of those keys into path segments.
63+
* A key that is not entirely bracket-encoded stays a single literal segment.
64+
*/
65+
function formKeySegments(key: string): Array<string> {
66+
const bracket = key.indexOf('[');
67+
if (bracket <= 0 || !key.endsWith(']')) {
68+
return [key];
69+
}
70+
71+
const segments = [key.slice(0, bracket)];
72+
const rest = key.slice(bracket);
73+
const pattern = /\[([^[\]]*)\]/g;
74+
let consumed = 0;
75+
let match: RegExpExecArray | null;
76+
while ((match = pattern.exec(rest)) !== null) {
77+
if (match.index !== consumed) {
78+
return [key];
79+
}
80+
segments.push(match[1] ?? '');
81+
consumed = pattern.lastIndex;
82+
if (segments.length > MAX_FORM_DEPTH) {
83+
throw new Error('Form field is nested too deeply');
84+
}
85+
}
86+
if (consumed !== rest.length) {
87+
return [key];
88+
}
89+
return segments;
90+
}
91+
92+
function arrayIndex(segment: string): number | null {
93+
if (segment !== '0' && !/^[1-9]\d*$/.test(segment)) {
94+
return null;
95+
}
96+
if (segment.length > 5) {
97+
throw new Error('Form field index is out of range');
98+
}
99+
const index = Number(segment);
100+
if (index > MAX_FORM_INDEX) {
101+
throw new Error('Form field index is out of range');
102+
}
103+
return index;
104+
}
105+
106+
function isContainerRecord(value: unknown): value is Record<string, unknown> {
107+
return (
108+
typeof value === 'object' && value !== null && !Array.isArray(value) && !(value instanceof Blob)
109+
);
110+
}
111+
112+
function own(record: Record<string, unknown>, key: string): unknown {
113+
if (DANGEROUS_KEYS.has(key)) {
114+
return Object.getOwnPropertyDescriptor(record, key)?.value;
115+
}
116+
return record[key];
117+
}
118+
119+
function setOwn(record: Record<string, unknown>, key: string, value: unknown): void {
120+
if (DANGEROUS_KEYS.has(key)) {
121+
Object.defineProperty(record, key, {
122+
value,
123+
writable: true,
124+
enumerable: true,
125+
configurable: true,
126+
});
127+
return;
128+
}
129+
record[key] = value;
130+
}
131+
132+
/**
133+
* Rebuild the object `objectToFormData` flattened. Numeric segments and `[]`
134+
* become arrays. Scalars are left as the client encoded them.
135+
*/
136+
function formRecordToObject(
137+
record: Record<string, FormEntry | Array<FormEntry>>,
138+
): Record<string, unknown> {
139+
const root: Record<string, unknown> = {};
140+
let nodes = 0;
141+
142+
const createContainer = (asArray: boolean): Record<string, unknown> | Array<unknown> => {
143+
if (++nodes > MAX_FORM_NODES) {
144+
throw new Error('Form field has too many nested values');
145+
}
146+
return asArray ? [] : {};
147+
};
148+
149+
const read = (parent: Record<string, unknown> | Array<unknown>, segment: string): unknown => {
150+
if (Array.isArray(parent)) {
151+
return segment === '' ? undefined : parent[Number(segment)];
152+
}
153+
return own(parent, segment);
154+
};
155+
156+
const write = (
157+
parent: Record<string, unknown> | Array<unknown>,
158+
segment: string,
159+
value: unknown,
160+
): void => {
161+
if (Array.isArray(parent)) {
162+
if (segment === '') {
163+
parent.push(value);
164+
return;
165+
}
166+
const index = arrayIndex(segment);
167+
if (index === null) {
168+
throw new Error('Form field shape is inconsistent');
169+
}
170+
parent[index] = value;
171+
return;
172+
}
173+
setOwn(parent, segment, value);
174+
};
175+
176+
const assign = (segments: Array<string>, value: FormEntry): void => {
177+
let parent: Record<string, unknown> | Array<unknown> = root;
178+
for (let i = 0; i < segments.length - 1; i++) {
179+
const segment = segments[i] as string;
180+
const next = segments[i + 1] as string;
181+
const nextIsArray = next === '' || arrayIndex(next) !== null;
182+
const child = read(parent, segment);
183+
const childIsContainer = nextIsArray ? Array.isArray(child) : isContainerRecord(child);
184+
const container = childIsContainer
185+
? (child as Record<string, unknown> | Array<unknown>)
186+
: createContainer(nextIsArray);
187+
if (!childIsContainer) {
188+
write(parent, segment, container);
189+
}
190+
parent = container;
191+
}
192+
write(parent, segments[segments.length - 1] as string, value);
193+
};
194+
195+
for (const [key, raw] of Object.entries(record)) {
196+
const segments = formKeySegments(key);
197+
const values = Array.isArray(raw) ? raw : [raw];
198+
for (const value of values) {
199+
assign(segments, value);
200+
}
201+
}
202+
return root;
203+
}
204+
205+
async function readBody(c: CloudContext): Promise<unknown> {
206+
if (!isFormContentType(c.req.header('content-type'))) {
207+
return c.req.json();
208+
}
209+
// `[]` keys are arrays at runtime even when the declared return type is not.
210+
const parsed = (await c.req.parseBody()) as Record<string, FormEntry | Array<FormEntry>>;
211+
return formRecordToObject(parsed);
212+
}
213+
48214
export async function runValidation<V extends ValidatorSlots>(
49215
validators: V,
50216
c: CloudContext,
@@ -82,12 +248,18 @@ export async function runValidation<V extends ValidatorSlots>(
82248

83249
if (validators.body) {
84250
let raw: unknown;
251+
const formBody = isFormContentType(c.req.header('content-type'));
85252
try {
86-
raw = await c.req.json();
253+
// Multipart and URL-encoded bodies are what `useForm` sends for files.
254+
// JSON stays on `c.req.json()` so scalar types there are unchanged.
255+
raw = await readBody(c);
87256
} catch {
88257
return {
89258
ok: false,
90-
response: Response.json({ error: 'Invalid JSON body' }, { status: 400 }),
259+
response: Response.json(
260+
{ error: formBody ? 'Invalid form body' : 'Invalid JSON body' },
261+
{ status: 400 },
262+
),
91263
};
92264
}
93265
const result = await validateSlot(validators.body, raw);

‎packages/void/test/unit/define-handler.test.ts‎

Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { Hono } from 'hono';
22
import type { MiddlewareHandler } from 'hono';
33
import { describe, expect, it } from 'vite-plus/test';
4+
import { objectToFormData } from '../../src/pages/navigation-engine.ts';
45
import {
56
defineHandler,
67
defineMiddleware,
@@ -350,4 +351,176 @@ describe('defineHandler.withValidator', () => {
350351
body: { name: 'Bob' },
351352
});
352353
});
354+
355+
it('passes a multipart file to the schema and the handler', async () => {
356+
const photo = new File(['hello'], 'photo.png', { type: 'image/png' });
357+
let seenBySchema: unknown;
358+
const handler = defineHandler.withValidator({
359+
body: {
360+
'~standard': {
361+
version: 1,
362+
vendor: 'test',
363+
validate(value: unknown) {
364+
seenBySchema = value;
365+
const uploaded = (value as { photo?: unknown }).photo;
366+
if (!(uploaded instanceof File)) {
367+
return { issues: [{ message: 'expected a file', path: ['photo'] }] };
368+
}
369+
return { value };
370+
},
371+
},
372+
},
373+
})((_c, { body }) => {
374+
const received = body as { title: string; photo: File };
375+
return {
376+
title: received.title,
377+
name: received.photo.name,
378+
type: received.photo.type,
379+
size: received.photo.size,
380+
};
381+
});
382+
383+
const app = createValidatedApp('post', '/test', handler);
384+
const res = await app.request(
385+
new Request('http://localhost/test', {
386+
method: 'POST',
387+
body: objectToFormData({ title: 'Sunset', photo }),
388+
}),
389+
);
390+
391+
expect(res.status).toBe(200);
392+
expect(await res.json()).toEqual({
393+
title: 'Sunset',
394+
name: 'photo.png',
395+
type: 'image/png',
396+
size: photo.size,
397+
});
398+
const parsed = seenBySchema as { title: string; photo: File };
399+
expect(parsed.title).toBe('Sunset');
400+
expect(parsed.photo).toBeInstanceOf(File);
401+
expect(parsed.photo.name).toBe('photo.png');
402+
expect(await parsed.photo.text()).toBe('hello');
403+
});
404+
405+
it('restores nested bracket keys from form bodies', async () => {
406+
const handler = defineHandler.withValidator({
407+
body: passSchema(),
408+
})((_c, { body }) => ({ received: body }));
409+
const app = createValidatedApp('post', '/test', handler);
410+
const takenAt = new Date('2020-01-02T03:04:05.000Z');
411+
const multipart = objectToFormData({
412+
profile: { name: 'Ada' },
413+
tags: ['work', 'urgent'],
414+
album: { photos: [{ name: 'a.png' }] },
415+
published: true,
416+
count: 2,
417+
takenAt,
418+
note: null,
419+
});
420+
multipart.append('photos[]', 'one');
421+
multipart.append('photos[]', 'two');
422+
multipart.append('__proto__[polluted]', 'yes');
423+
424+
const multipartRes = await app.request(
425+
new Request('http://localhost/test', { method: 'POST', body: multipart }),
426+
);
427+
expect(multipartRes.status).toBe(200);
428+
expect(await multipartRes.json()).toEqual({
429+
received: {
430+
profile: { name: 'Ada' },
431+
tags: ['work', 'urgent'],
432+
album: { photos: [{ name: 'a.png' }] },
433+
published: '1',
434+
count: '2',
435+
takenAt: '2020-01-02T03:04:05.000Z',
436+
note: '',
437+
photos: ['one', 'two'],
438+
['__proto__']: { polluted: 'yes' },
439+
},
440+
});
441+
expect('polluted' in Object.prototype).toBe(false);
442+
443+
const params = new URLSearchParams();
444+
params.append('profile[name]', 'Ada');
445+
params.append('tags[0]', 'work');
446+
params.append('tags[1]', 'urgent');
447+
params.append('photos[]', 'one');
448+
params.append('photos[]', 'two');
449+
const urlencodedRes = await app.request(
450+
new Request('http://localhost/test', {
451+
method: 'POST',
452+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
453+
body: params.toString(),
454+
}),
455+
);
456+
expect(urlencodedRes.status).toBe(200);
457+
expect(await urlencodedRes.json()).toEqual({
458+
received: {
459+
profile: { name: 'Ada' },
460+
tags: ['work', 'urgent'],
461+
photos: ['one', 'two'],
462+
},
463+
});
464+
});
465+
466+
it('keeps JSON body validation unchanged', async () => {
467+
const handler = defineHandler.withValidator({
468+
body: passSchema(),
469+
})((_c, { body }) => ({ received: body }));
470+
const app = createValidatedApp('post', '/test', handler);
471+
472+
const res = await app.request(
473+
new Request('http://localhost/test', {
474+
method: 'POST',
475+
headers: { 'Content-Type': 'application/json' },
476+
body: JSON.stringify({
477+
profile: { name: 'Ada' },
478+
tags: ['work'],
479+
published: true,
480+
count: 2,
481+
note: null,
482+
}),
483+
}),
484+
);
485+
486+
expect(res.status).toBe(200);
487+
expect(await res.json()).toEqual({
488+
received: {
489+
profile: { name: 'Ada' },
490+
tags: ['work'],
491+
published: true,
492+
count: 2,
493+
note: null,
494+
},
495+
});
496+
});
497+
498+
it('does not report a bad form body as invalid JSON', async () => {
499+
const handler = defineHandler.withValidator({
500+
body: failSchema('title is required'),
501+
})(() => ({ ok: true }));
502+
const app = createValidatedApp('post', '/test', handler);
503+
504+
const malformed = await app.request(
505+
new Request('http://localhost/test', {
506+
method: 'POST',
507+
headers: { 'Content-Type': 'multipart/form-data; boundary=----bad' },
508+
body: 'not a multipart body',
509+
}),
510+
);
511+
expect(malformed.status).toBe(400);
512+
expect(((await malformed.json()) as { error: string }).error).toBe('Invalid form body');
513+
514+
const invalid = await app.request(
515+
new Request('http://localhost/test', {
516+
method: 'POST',
517+
body: objectToFormData({ title: '' }),
518+
}),
519+
);
520+
expect(invalid.status).toBe(400);
521+
const json = (await invalid.json()) as ValidationIssueBody;
522+
expect(json.error).toBe('Validation failed');
523+
expect(json.issues[0]?.slot).toBe('body');
524+
expect(json.issues[0]?.issues[0]?.message).toBe('title is required');
525+
});
353526
});

0 commit comments

Comments
 (0)