validator.test.ts
This file
Path
src/validator/validator.test.ts
1,440 lines 路 35.4 KiB 路 TypeScript
Last changed by
fix(validator): prevent type diff bug in form data parsing (#4753)EdamAmexbefore adoption4bb70fa
History of this fileTake it
1/* eslint-disable @typescript-eslint/no-unused-vars */2import * as z from 'zod'3import type { Context } from '../context'4import { Hono } from '../hono'5import { HTTPException } from '../http-exception'6import { cloneRawRequest } from '../request'7import type {8 ErrorHandler,9 ExtractSchema,10 ExtractSchemaForStatusCode,11 FormValue,12 MiddlewareHandler,13 TypedResponse,14 ValidationTargets,15} from '../types'16import type { ContentfulStatusCode, StatusCode } from '../utils/http-status'17import type { Equal, Expect } from '../utils/types'18import type { ValidationFunction } from './validator'19import { validator } from './validator'2021// Helper type to extract the response type from the validation function22// eslint-disable-next-line @typescript-eslint/no-explicit-any23type InferValidatorResponse<VF> = VF extends (value: any, c: any) => infer R24 ? R extends Promise<infer PR>25 ? // eslint-disable-next-line @typescript-eslint/no-explicit-any26 PR extends Response | TypedResponse<any, any, any>27 ? PR28 : never29 : // eslint-disable-next-line @typescript-eslint/no-explicit-any30 R extends Response | TypedResponse<any, any, any>31 ? R32 : never33 : never3435// Reference implementation for only testing36const zodValidator = <37 T extends z.ZodSchema,38 E extends {},39 P extends string,40 Target extends keyof ValidationTargets,41>(42 target: Target,43 schema: T44) => {45 const validationFunc = (value: unknown, c: Context<E, P>) => {46 const result = schema.safeParse(value)47 if (!result.success) {48 return c.text('Invalid!', 400)49 }50 return result.data as z.output<T>51 }5253 type ResponseType = InferValidatorResponse<typeof validationFunc>5455 return validator(target, validationFunc) as MiddlewareHandler<56 E,57 P,58 { in: { [K in Target]: z.input<T> }; out: { [K in Target]: z.output<T> } },59 ResponseType60 >61}6263describe('Basic', () => {64 const app = new Hono()6566 const route = app.get(67 '/search',68 async (_c, next) => {69 await next()70 },71 validator('query', (value, c) => {72 type verify = Expect<Equal<Record<string, string | string[]>, typeof value>>73 if (!value.q) {74 return c.text('Invalid!', 400)75 }76 }),77 (c) => {78 return c.text('Valid!', 200)79 }80 )8182 type Expected = {83 '/search': {84 $get:85 | {86 input: {87 query: {}88 }89 output: 'Invalid!'90 outputFormat: 'text'91 status: 40092 }93 | {94 input: {95 query: {}96 }97 output: 'Valid!'98 outputFormat: 'text'99 status: 200100 }101 }102 }103104 type Actual = ExtractSchema<typeof route>105106 type verify = Expect<Equal<Expected, Actual>>107108 it('Should return 200 response', async () => {109 const res = await app.request('http://localhost/search?q=foo')110 expect(res.status).toBe(200)111 })112113 it('Should return 400 response', async () => {114 const res = await app.request('http://localhost/search')115 expect(res.status).toBe(400)116 })117})118119const onErrorHandler: ErrorHandler = (e, c) => {120 if (e instanceof HTTPException) {121 return c.json({ message: e.message, success: false }, e.status)122 }123 return c.json({ message: e.message }, 500)124}125126describe('JSON', () => {127 const app = new Hono()128 app.post(129 '/post',130 validator('json', (value) => value),131 (c) => {132 return c.json(c.req.valid('json'))133 }134 )135136 it('Should return 200 response with a valid JSON data', async () => {137 const res = await app.request('http://localhost/post', {138 method: 'POST',139 body: JSON.stringify({ foo: 'bar' }),140 headers: {141 'Content-Type': 'application/json',142 },143 })144 expect(res.status).toBe(200)145 const data = await res.json()146 expect(data).toEqual({ foo: 'bar' })147 })148149 it('Should not validate if Content-Type is not set', async () => {150 const res = await app.request('http://localhost/post', {151 method: 'POST',152 body: JSON.stringify({ foo: 'bar' }),153 })154 expect(res.status).toBe(200)155 const data = await res.json()156 expect(data.foo).toBeUndefined()157 })158159 it('Should not validate if Content-Type is wrong', async () => {160 const res = await app.request('http://localhost/post', {161 method: 'POST',162 headers: {163 'Content-Type': 'text/plain;charset=utf-8',164 },165 body: JSON.stringify({ foo: 'bar' }),166 })167 expect(res.status).toBe(200)168 })169170 it('Should validate if Content-Type is a application/json with a charset', async () => {171 const res = await app.request('http://localhost/post', {172 method: 'POST',173 headers: {174 'Content-Type': 'application/json',175 },176 body: JSON.stringify({ foo: 'bar' }),177 })178 expect(res.status).toBe(200)179 expect(await res.json()).toEqual({ foo: 'bar' })180 })181182 it('Should validate if Content-Type is a subtype like application/merge-patch+json', async () => {183 const res = await app.request('http://localhost/post', {184 method: 'POST',185 headers: {186 'Content-Type': 'application/merge-patch+json',187 },188 body: JSON.stringify({ foo: 'bar' }),189 })190 expect(res.status).toBe(200)191 expect(await res.json()).toEqual({ foo: 'bar' })192 })193194 it('Should validate if Content-Type is application/vnd.api+json', async () => {195 const res = await app.request('http://localhost/post', {196 method: 'POST',197 headers: {198 'Content-Type': 'application/vnd.api+json',199 },200 body: JSON.stringify({ foo: 'bar' }),201 })202 expect(res.status).toBe(200)203 expect(await res.json()).toEqual({ foo: 'bar' })204 })205206 it('Should not validate if Content-Type does not start with application/json', async () => {207 const res = await app.request('http://localhost/post', {208 method: 'POST',209 headers: {210 'Content-Type': 'Xapplication/json',211 },212 body: JSON.stringify({ foo: 'bar' }),213 })214 expect(res.status).toBe(200)215 const data = await res.json()216 expect(data.foo).toBeUndefined()217 })218})219220describe('Malformed JSON', () => {221 const app = new Hono()222 app.post(223 '/post',224 validator('json', (value) => value),225 (c) => {226 return c.json(c.req.valid('json'))227 }228 )229230 it('Should return 400 response if the body data is not a valid JSON', async () => {231 const formData = new FormData()232 formData.append('foo', 'bar')233 const res = await app.request('http://localhost/post', {234 method: 'POST',235 headers: {236 'Content-Type': 'application/json',237 },238 body: formData,239 })240 expect(res.status).toBe(400)241 })242})243244describe('FormData', () => {245 const app = new Hono()246 app.post(247 '/post',248 validator('form', (value) => value),249 (c) => {250 return c.json(c.req.valid('form'))251 }252 )253254 it('Should return 200 response with a valid form data', async () => {255 const formData = new FormData()256 formData.append('message', 'hi')257 const res = await app.request('http://localhost/post', {258 method: 'POST',259 body: formData,260 })261 expect(res.status).toBe(200)262 expect(await res.json()).toEqual({ message: 'hi' })263 })264265 it('Should validate a URL Encoded Data', async () => {266 const params = new URLSearchParams()267 params.append('foo', 'bar')268 const res = await app.request('/post', {269 method: 'POST',270 body: params,271 headers: {272 'content-type': 'application/x-www-form-urlencoded',273 },274 })275 expect(res.status).toBe(200)276 expect(await res.json()).toEqual({277 foo: 'bar',278 })279 })280281 it('Should validate if Content-Type is a application/x-www-form-urlencoded with a charset', async () => {282 const params = new URLSearchParams()283 params.append('foo', 'bar')284 const res = await app.request('/post', {285 method: 'POST',286 body: params,287 headers: {288 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',289 },290 })291 expect(res.status).toBe(200)292 expect(await res.json()).toEqual({293 foo: 'bar',294 })295 })296297 it('Should return `foo[]` as an array', async () => {298 const form = new FormData()299 form.append('foo[]', 'bar1')300 form.append('foo[]', 'bar2')301 const res = await app.request('/post', {302 method: 'POST',303 body: form,304 })305 expect(res.status).toBe(200)306 expect(await res.json()).toEqual({307 'foo[]': ['bar1', 'bar2'],308 })309 })310311 it('Should return `foo` as an array if multiple values are appended', async () => {312 const form = new FormData()313 form.append('foo', 'bar1')314 form.append('foo', 'bar2')315 form.append('foo', 'bar3')316 const res = await app.request('/post', {317 method: 'POST',318 body: form,319 })320 expect(res.status).toBe(200)321 expect(await res.json()).toEqual({322 foo: ['bar1', 'bar2', 'bar3'],323 })324 })325})326327describe('Malformed FormData request', () => {328 const app = new Hono()329 app.post(330 '/post',331 validator('form', (value) => value),332 (c) => {333 return c.json(c.req.valid('form'))334 }335 )336 app.onError(onErrorHandler)337338 it('Should return 400 response, for malformed content type header', async () => {339 const res = await app.request('http://localhost/post', {340 method: 'POST',341 body: 'hi',342 headers: {343 'content-type': 'multipart/form-data',344 },345 })346 expect(res.status).toBe(400)347 const data = await res.json()348 expect(data['success']).toBe(false)349 expect(data['message']).toMatch(/^Malformed FormData request./)350 })351})352353describe('JSON and FormData', () => {354 const app = new Hono()355 app.post(356 '/',357 validator('json', (value) => value),358 validator('form', (value) => value),359 async (c) => {360 const jsonData = c.req.valid('json')361 const formData = c.req.valid('form')362 return c.json({363 json: jsonData,364 form: formData,365 })366 }367 )368369 it('Should validate a JSON request', async () => {370 const res = await app.request('/', {371 method: 'POST',372 body: JSON.stringify({ foo: 'bar' }),373 headers: {374 'Content-Type': 'application/json',375 },376 })377 expect(res.status).toBe(200)378 const data = await res.json()379 expect(data.json).toEqual({ foo: 'bar' })380 })381382 it('Should validate a FormData request', async () => {383 const form = new FormData()384 form.append('foo', 'bar')385 const res = await app.request('/', {386 method: 'POST',387 body: form,388 })389 expect(res.status).toBe(200)390 const data = await res.json()391 expect(data.form).toEqual({ foo: 'bar' })392 })393})394395describe('Cached contents', () => {396 describe('json', () => {397 const app = new Hono()398 const bodyTypes = ['json', 'text', 'arrayBuffer', 'blob']399400 for (const type of bodyTypes) {401 app.post(402 `/${type}`,403 async (c, next) => {404 // @ts-expect-error not type safe405 await c.req[type]()406 await next()407 },408 validator('json', (value) => {409 if (value instanceof Promise) {410 throw new Error('Value is Promise')411 }412 return value413 }),414 async (c) => {415 const data = await c.req.json()416 return c.json(data, 200)417 }418 )419 }420421 for (const type of bodyTypes) {422 const endpoint = `/${type}`423 it(`Should return the cached JSON content - ${endpoint}`, async () => {424 const res = await app.request(endpoint, {425 method: 'POST',426 body: JSON.stringify({ message: 'Hello' }),427 headers: {428 'Content-Type': 'application/json',429 },430 })431 expect(res.status).toBe(200)432 expect(await res.json()).toEqual({ message: 'Hello' })433 })434 }435 })436437 describe('Cached content', () => {438 const app = new Hono()439 const bodyTypes = ['formData', 'text', 'arrayBuffer', 'blob']440441 for (const type of bodyTypes) {442 app.post(443 `/${type}`,444 async (c, next) => {445 // @ts-expect-error not type safe446 await c.req[type]()447 await next()448 },449 validator('form', (value) => {450 if (value instanceof Promise) {451 throw new Error('Value is Promise')452 }453 return value454 }),455 async (c) => {456 return c.json({ message: 'OK' }, 200)457 }458 )459 }460461 for (const type of bodyTypes) {462 const endpoint = `/${type}`463 it(`Should return the cached FormData content - ${endpoint}`, async () => {464 const form = new FormData()465 form.append('message', 'Hello')466 const res = await app.request(endpoint, {467 method: 'POST',468 body: form,469 })470 expect(res.status).toBe(200)471 expect(await res.json()).toEqual({ message: 'OK' })472 })473 }474 })475})476477describe('Validator middleware with a custom validation function', () => {478 const app = new Hono()479480 const validationFunction: ValidationFunction<{ id: string }, { id: number }> = (v) => {481 return {482 id: Number(v.id),483 }484 }485486 const route = app.post('/post', validator('json', validationFunction), (c) => {487 const post = c.req.valid('json')488 type Expected = {489 id: number490 }491 type verify = Expect<Equal<Expected, typeof post>>492 return c.json({493 post,494 })495 })496497 type Expected = {498 '/post': {499 $post:500 | {501 input: {502 json: {503 id: number504 }505 }506 output: {}507 outputFormat: string508 status: StatusCode509 }510 | {511 input: {512 json: {513 id: number514 }515 }516 output: {517 post: {518 id: number519 }520 }521 outputFormat: 'json'522 status: ContentfulStatusCode523 }524 }525 }526527 type Actual = ExtractSchema<typeof route>528 type verify2 = Expect<Equal<Expected, Actual>>529530 it('Should validate JSON with transformation and return 200 response', async () => {531 const res = await app.request('http://localhost/post', {532 method: 'POST',533 headers: {534 'Content-Type': 'application/json',535 },536 body: JSON.stringify({537 id: '123',538 }),539 })540 expect(res.status).toBe(200)541 expect(await res.json()).toEqual({542 post: {543 id: 123,544 },545 })546 })547})548549describe('Validator middleware with Zod validates JSON', () => {550 const app = new Hono()551552 const schema = z.object({553 id: z.number(),554 title: z.string(),555 })556557 const route = app.post('/post', zodValidator('json', schema), (c) => {558 const post = c.req.valid('json')559 type Expected = {560 id: number561 title: string562 }563 type verify = Expect<Equal<Expected, typeof post>>564 return c.json({565 post: post,566 })567 })568569 type Expected = {570 '/post': {571 $post:572 | {573 input: {574 json: {575 id: number576 title: string577 }578 }579 output: 'Invalid!'580 outputFormat: 'text'581 status: 400582 }583 | {584 input: {585 json: {586 id: number587 title: string588 }589 }590 output: {591 post: {592 id: number593 title: string594 }595 }596 outputFormat: 'json'597 status: ContentfulStatusCode598 }599 }600 }601602 type Actual = ExtractSchema<typeof route>603604 type verify2 = Expect<Equal<Expected, Actual>>605606 it('Should validate JSON and return 200 response', async () => {607 const res = await app.request('http://localhost/post', {608 method: 'POST',609 headers: {610 'Content-Type': 'application/json',611 },612 body: JSON.stringify({613 id: 123,614 title: 'Hello',615 }),616 })617 expect(res.status).toBe(200)618 expect(await res.json()).toEqual({619 post: {620 id: 123,621 title: 'Hello',622 },623 })624 })625626 it('Should validate JSON and return 400 response', async () => {627 const res = await app.request('http://localhost/post', {628 method: 'POST',629 headers: {630 'Content-Type': 'application/json',631 },632 body: JSON.stringify({633 id: '123',634 title: 'Hello',635 }),636 })637 expect(res.status).toBe(400)638 expect(await res.text()).toBe('Invalid!')639 })640})641642describe('Validator middleware with Zod validates Form data', () => {643 const app = new Hono()644645 const schema = z.object({646 id: z.string(),647 title: z.string(),648 })649 app.post('/post', zodValidator('form', schema), (c) => {650 const post = c.req.valid('form')651 return c.json({652 post: post,653 })654 })655656 it('Should validate Form data and return 200 response', async () => {657 const form = new FormData()658 form.append('id', '123')659 form.append('title', 'Hello')660 const res = await app.request('http://localhost/post', {661 method: 'POST',662 body: form,663 })664 expect(res.status).toBe(200)665 expect(await res.json()).toEqual({666 post: {667 id: '123',668 title: 'Hello',669 },670 })671 })672673 it('Should validate Form data and return 400 response', async () => {674 const res = await app.request('http://localhost/post', {675 method: 'POST',676 })677 expect(res.status).toBe(400)678 expect(await res.text()).toBe('Invalid!')679 })680})681682describe('Validator middleware with Zod validates query params', () => {683 const app = new Hono()684685 const schema = z.object({686 page: z687 .string()688 .refine((v) => {689 return !isNaN(Number(v))690 })691 .transform((v) => {692 return Number(v)693 }),694 tag: z.array(z.string()),695 })696697 app.get('/search', zodValidator('query', schema), (c) => {698 const res = c.req.valid('query')699 return c.json({700 page: res.page,701 tags: res.tag,702 })703 })704705 it('Should validate query params and return 200 response', async () => {706 const res = await app.request('http://localhost/search?page=123&tag=a&tag=b')707 expect(res.status).toBe(200)708 expect(await res.json()).toEqual({709 page: 123,710 tags: ['a', 'b'],711 })712 })713714 it('Should validate query params and return 400 response', async () => {715 const res = await app.request('http://localhost/search?page=onetwothree')716 expect(res.status).toBe(400)717 expect(await res.text()).toBe('Invalid!')718 })719})720721describe('Validator middleware with Zod validates param', () => {722 const app = new Hono()723724 const schema = z.object({725 id: z726 .string()727 .regex(/^[0-9]+$/)728 .transform((v) => {729 return Number(v)730 }),731 title: z.string(),732 })733 app.get('/users/:id/books/:title', zodValidator('param', schema), (c) => {734 const param = c.req.valid('param')735 return c.json({736 param: param,737 })738 })739740 it('Should validate Form data and return 200 response', async () => {741 const res = await app.request('http://localhost/users/123/books/Hello')742 expect(res.status).toBe(200)743 expect(await res.json()).toEqual({744 param: {745 id: 123,746 title: 'Hello',747 },748 })749 })750751 it('Should validate Form data and return 400 response', async () => {752 const res = await app.request('http://localhost/users/0.123/books/Hello')753 expect(res.status).toBe(400)754 expect(await res.text()).toBe('Invalid!')755 })756})757758describe('Validator middleware with Zod validates header values', () => {759 const app = new Hono()760761 const schema = z.object({762 'x-request-id': z.string().uuid(),763 })764765 app.get('/ping', zodValidator('header', schema), (c) => {766 const data = c.req.valid('header')767 const xRequestId = data['x-request-id']768 return c.json({769 xRequestId,770 })771 })772773 it('Should validate header values and return 200 response', async () => {774 const res = await app.request('/ping', {775 headers: {776 'x-request-id': '6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b',777 },778 })779 expect(res.status).toBe(200)780 expect(await res.json()).toEqual({781 xRequestId: '6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b',782 })783 })784785 it('Should validate header values and return 400 response', async () => {786 const res = await app.request('http://localhost/ping', {787 headers: {788 'x-request-id': 'invalid-key',789 },790 })791 expect(res.status).toBe(400)792 expect(await res.text()).toBe('Invalid!')793 })794})795796describe('Validator middleware with Zod validates cookies', () => {797 const app = new Hono()798799 const schema = z.object({800 debug: z.enum(['0', '1']),801 })802803 app.get('/api/user', zodValidator('cookie', schema), (c) => {804 const { debug } = c.req.valid('cookie')805 return c.json({806 debug,807 })808 })809810 it('Should validate cookies and return 200 response', async () => {811 const res = await app.request('/api/user', {812 headers: {813 Cookie: 'debug=0',814 },815 })816 expect(res.status).toBe(200)817 expect(await res.json()).toEqual({818 debug: '0',819 })820 })821822 it('Should validate cookies and return 400 response', async () => {823 const res = await app.request('/api/user', {824 headers: {825 Cookie: 'debug=true',826 },827 })828 expect(res.status).toBe(400)829 expect(await res.text()).toBe('Invalid!')830 })831})832833describe('Validator middleware with Zod multiple validators', () => {834 const app = new Hono<{ Variables: { id: number } }>()835 const route = app.post(836 '/posts',837 zodValidator(838 'query',839 z.object({840 page: z841 .string()842 .refine((v) => {843 return !isNaN(Number(v))844 })845 .transform((v) => {846 return Number(v)847 }),848 })849 ),850 zodValidator(851 'form',852 z.object({853 title: z.string(),854 })855 ),856 (c) => {857 const id = c.get('id')858 type verify = Expect<Equal<number, typeof id>>859 const formValidatedData = c.req.valid('form')860 type verify2 = Expect<Equal<{ title: string }, typeof formValidatedData>>861 const { page } = c.req.valid('query')862 const { title } = c.req.valid('form')863 return c.json({ page, title })864 }865 )866867 type Actual = ExtractSchema<typeof route>868869 type Expected = {870 '/posts': {871 $post:872 | {873 input: {874 query: {875 page: string876 }877 } & {878 form: {879 title: string880 }881 }882 output: 'Invalid!'883 outputFormat: 'text'884 status: 400885 }886 | {887 input: {888 query: {889 page: string890 }891 } & {892 form: {893 title: string894 }895 }896 output: {897 page: number898 title: string899 }900 outputFormat: 'json'901 status: ContentfulStatusCode902 }903 }904 }905906 type verify = Expect<Equal<Expected, Actual>>907908 it('Should validate both query param and form data and return 200 response', async () => {909 const form = new FormData()910 form.append('title', 'Hello')911 const res = await app.request('http://localhost/posts?page=2', {912 method: 'POST',913 body: form,914 })915 expect(res.status).toBe(200)916 expect(await res.json()).toEqual({917 page: 2,918 title: 'Hello',919 })920 })921922 it('Should validate both query param and form data and return 400 response', async () => {923 const res = await app.request('http://localhost/posts?page=2', {924 method: 'POST',925 })926 expect(res.status).toBe(400)927 expect(await res.text()).toBe('Invalid!')928 })929})930931it('With path parameters', () => {932 const app = new Hono()933934 const route = app.put(935 '/posts/:id',936 validator('param', () => {937 return {938 id: '123',939 }940 }),941 validator('form', () => {942 return {943 title: 'Foo',944 }945 }),946 (c) => {947 return c.text('Valid!')948 }949 )950951 type Expected = {952 '/posts/:id': {953 $put: {954 input: {955 form: {956 title: FormValue | FormValue[]957 }958 } & {959 param: {960 id: string961 }962 }963 output: 'Valid!'964 outputFormat: 'text'965 status: ContentfulStatusCode966 }967 }968 }969970 type Actual = ExtractSchema<typeof route>971 type verify = Expect<Equal<Expected, Actual>>972})973974it('`on`', () => {975 const app = new Hono()976977 const route = app.on(978 'PURGE',979 '/purge',980 validator('form', () => {981 return {982 tag: 'foo',983 }984 }),985 validator('query', () => {986 return {987 q: 'bar',988 }989 }),990 (c) => {991 return c.json({992 success: true,993 })994 }995 )996997 type Expected = {998 '/purge': {999 $purge: {1000 input: {1001 form: {1002 tag: FormValue | FormValue[]1003 }1004 } & {1005 query: {1006 q: string | string[]1007 }1008 }1009 output: {1010 success: true1011 }1012 outputFormat: 'json'1013 status: ContentfulStatusCode1014 }1015 }1016 }10171018 type Actual = ExtractSchema<typeof route>1019 type verify = Expect<Equal<Expected, Actual>>1020})10211022it('`app.on`', () => {1023 const app = new Hono()10241025 const route = app1026 .get(1027 '/posts',1028 validator('query', () => {1029 return {1030 page: '2',1031 }1032 }),1033 (c) => {1034 return c.json({1035 posts: [1036 {1037 title: 'foo',1038 },1039 ],1040 })1041 }1042 )1043 .post(1044 validator('json', () => {1045 return {1046 title: 'Hello',1047 }1048 }),1049 validator('query', () => {1050 return {1051 title: 'Hello',1052 }1053 }),1054 (c) => {1055 return c.json({1056 success: true,1057 })1058 }1059 )10601061 type Actual = ExtractSchema<typeof route>1062 //type verify = Expect<Equal<Expected, Actual>>1063})10641065describe('Clone Request object', () => {1066 describe('json', () => {1067 const app = new Hono()1068 app.post(1069 '/',1070 validator('json', () => {1071 return {1072 foo: 'bar',1073 }1074 }),1075 async (c) => {1076 // `c.req.json()` should not throw the error1077 await c.req.json()1078 // `c.req.text()` should not throw the error1079 await c.req.text()1080 // `c.req.arrayBuffer()` should not throw the error1081 await c.req.arrayBuffer()1082 // `c.req.blob()` should not throw the error1083 await c.req.blob()1084 return c.text('foo')1085 }1086 )10871088 it('Should not throw the error with c.req.json()', async () => {1089 const req = new Request('http://localhost', {1090 method: 'POST',1091 headers: {1092 'Content-Type': 'application/json',1093 },1094 body: JSON.stringify({ foo: 'bar' }),1095 })1096 const res = await app.request(req)1097 expect(res.status).toBe(200)1098 })1099 })11001101 describe('form', () => {1102 const app = new Hono()1103 app.post(1104 '/',1105 validator('form', () => {1106 return {1107 foo: 'bar',1108 }1109 }),1110 async (c) => {1111 // `c.req.parseBody()` should not throw the error1112 await c.req.parseBody()1113 // `c.req.text()` should not throw the error1114 await c.req.text()1115 // `c.req.arrayBuffer()` should not throw the error1116 await c.req.arrayBuffer()1117 // `c.req.blob()` should not throw the error1118 await c.req.blob()1119 return c.text('foo')1120 }1121 )11221123 app.post(1124 '/cached',1125 async (c, next) => {1126 await c.req.parseBody()1127 await next()1128 },1129 validator('form', (value) => {1130 if (value instanceof FormData) {1131 throw new Error('The value should not be a FormData')1132 }1133 return value1134 }),1135 (c) => {1136 const v = c.req.valid('form')1137 return c.json(v)1138 }1139 )11401141 it('Should not throw the error with c.req.parseBody()', async () => {1142 const body = new FormData()1143 body.append('foo', 'bar')1144 const req = new Request('http://localhost', {1145 method: 'POST',1146 body: body,1147 })1148 const res = await app.request(req)1149 expect(res.status).toBe(200)1150 })11511152 it('Should not be an instance of FormData if the formData is cached', async () => {1153 const body = new FormData()1154 body.append('foo', 'bar')1155 const req = new Request('http://localhost/cached', {1156 method: 'POST',1157 body: body,1158 })1159 const res = await app.request(req)1160 expect(res.status).toBe(200)1161 expect(await res.json()).toEqual({ foo: 'bar' })1162 })1163 })1164})11651166describe('Async validator function', () => {1167 const app = new Hono()11681169 app.get(1170 '/posts',1171 validator('query', async () => {1172 return {1173 page: '1',1174 }1175 }),1176 (c) => {1177 const { page } = c.req.valid('query')1178 return c.json({ page })1179 }1180 )11811182 it('Should get the values from the async function', async () => {1183 const res = await app.request('/posts')1184 expect(res.status).toBe(200)1185 expect(await res.json()).toEqual({1186 page: '1',1187 })1188 })1189})11901191describe('Validator with using Zod directly', () => {1192 it('Should exclude Response & TypedResponse type', () => {1193 const testSchema = z.object({1194 name: z.string(),1195 age: z.number(),1196 type: z.enum(['a']),1197 })1198 const app = new Hono()11991200 const route = app.post(1201 '/posts',1202 validator('json', (value, c) => {1203 const parsed = testSchema.safeParse(value)1204 if (!parsed.success) {1205 return c.json({ foo: 'bar' }, 401)1206 }1207 return parsed.data1208 }),1209 (c) => {1210 const data = c.req.valid('json')1211 expectTypeOf(data.name).toEqualTypeOf<string>()1212 return c.json(1213 {1214 message: 'Created!',1215 },1216 2011217 )1218 }1219 )12201221 expectTypeOf<ExtractSchemaForStatusCode<typeof route, 201>>().toEqualTypeOf<{1222 '/posts': {1223 $post: {1224 input: {1225 json: {1226 type: 'a'1227 name: string1228 age: number1229 }1230 }1231 output: {1232 message: string1233 }1234 outputFormat: 'json'1235 status: 2011236 }1237 }1238 }>()12391240 expectTypeOf<ExtractSchemaForStatusCode<typeof route, 401>>().toEqualTypeOf<{1241 '/posts': {1242 $post: {1243 input: {1244 json: {1245 type: 'a'1246 name: string1247 age: number1248 }1249 }1250 output: {1251 foo: string1252 }1253 outputFormat: 'json'1254 status: 4011255 }1256 }1257 }>()1258 })1259})12601261describe('Transform', () => {1262 it('Should be number when the type is transformed', () => {1263 const route = new Hono().get(1264 '/',1265 validator('query', async () => {1266 return {1267 page: 1,1268 }1269 }),1270 (c) => {1271 const { page } = c.req.valid('query')1272 expectTypeOf(page).toEqualTypeOf<number>()1273 return c.json({ page })1274 }1275 )12761277 type Expected = {1278 '/': {1279 $get: {1280 input: {1281 query: {1282 page: string | string[]1283 }1284 }1285 output: {1286 page: number1287 }1288 outputFormat: 'json'1289 status: ContentfulStatusCode1290 }1291 }1292 }12931294 type Actual = ExtractSchema<typeof route>1295 type verify = Expect<Equal<Expected, Actual>>12961297 // Temporary: let's see what the actual type is1298 type TestActual = Actual1299 })13001301 it('Should be number and union when the type is transformed', () => {1302 const app = new Hono()1303 const route = app.get(1304 '/',1305 validator('query', () => {1306 return {1307 page: 1,1308 orderBy: 'asc',1309 } as {1310 page: number1311 orderBy: 'asc' | 'desc'1312 ordreByWithdefault?: 'asc' | 'desc' | undefined1313 }1314 }),1315 (c) => {1316 const { page, orderBy, ordreByWithdefault } = c.req.valid('query')1317 expectTypeOf(page).toEqualTypeOf<number>()1318 expectTypeOf(orderBy).toEqualTypeOf<'asc' | 'desc'>()1319 expectTypeOf(ordreByWithdefault).toEqualTypeOf<'asc' | 'desc' | undefined>()1320 return c.json({ page, orderBy, ordreByWithdefault })1321 }1322 )13231324 type Expected = {1325 '/': {1326 $get: {1327 input: {1328 query: {1329 page: string | string[]1330 orderBy: 'asc' | 'desc'1331 ordreByWithdefault?: 'asc' | 'desc' | undefined1332 }1333 }1334 output: {1335 page: number1336 orderBy: 'asc' | 'desc'1337 ordreByWithdefault: 'asc' | 'desc' | undefined1338 }1339 outputFormat: 'json'1340 status: ContentfulStatusCode1341 }1342 }1343 }13441345 type Actual = ExtractSchema<typeof route>1346 type verify = Expect<Equal<Expected, Actual>>13471348 // Temporary: let's see what the actual type is1349 type TestActual = Actual1350 })1351})13521353describe('Raw Request cloning after validation', () => {1354 it('Should allow the `cloneRawRequest` util to clone the request object after validation', async () => {1355 const app = new Hono()13561357 app.post(1358 '/json-validation',1359 validator('json', (data) => data),1360 async (c) => {1361 const clonedReq = await cloneRawRequest(c.req)1362 const clonedJSON = await clonedReq.json()13631364 return c.json({1365 originalMethod: c.req.raw.method,1366 clonedMethod: clonedReq.method,1367 clonedUrl: clonedReq.url,1368 clonedHeaders: {1369 contentType: clonedReq.headers.get('Content-Type'),1370 customHeader: clonedReq.headers.get('X-Custom-Header'),1371 },1372 originalCache: c.req.raw.cache,1373 clonedCache: clonedReq.cache,1374 originalCredentials: c.req.raw.credentials,1375 clonedCredentials: clonedReq.credentials,1376 originalMode: c.req.raw.mode,1377 clonedMode: clonedReq.mode,1378 originalRedirect: c.req.raw.redirect,1379 clonedRedirect: clonedReq.redirect,1380 originalReferrerPolicy: c.req.raw.referrerPolicy,1381 clonedReferrerPolicy: clonedReq.referrerPolicy,1382 cloned: JSON.stringify(clonedJSON) === JSON.stringify(await c.req.json()),1383 payload: clonedJSON,1384 })1385 }1386 )13871388 const testData = { message: 'test', userId: 123 }1389 const res = await app.request('/json-validation', {1390 method: 'POST',1391 headers: {1392 'Content-Type': 'application/json',1393 'X-Custom-Header': 'test-value',1394 },1395 body: JSON.stringify(testData),1396 cache: 'no-cache',1397 credentials: 'include',1398 mode: 'cors',1399 redirect: 'follow',1400 referrerPolicy: 'origin',1401 })14021403 expect(res.status).toBe(200)14041405 const result = await res.json()14061407 expect(result.originalMethod).toBe('POST')1408 expect(result.clonedMethod).toBe('POST')1409 expect(result.clonedUrl).toBe('http://localhost/json-validation')1410 expect(result.clonedHeaders.contentType).toBe('application/json')1411 expect(result.clonedHeaders.customHeader).toBe('test-value')1412 expect(result.clonedCache).toBe(result.originalCache)1413 expect(result.clonedCredentials).toBe(result.originalCredentials)1414 expect(result.clonedMode).toBe(result.originalMode)1415 expect(result.clonedRedirect).toBe(result.originalRedirect)1416 expect(result.clonedReferrerPolicy).toBe(result.originalReferrerPolicy)1417 expect(result.cloned).toBe(true)1418 expect(result.payload).toMatchObject(testData)1419 })1420})14211422describe('Form validator prototype pollution prevention', () => {1423 it('should store __proto__ as data and not misdetect inherited keys', async () => {1424 const app = new Hono()1425 app.post(1426 '/form',1427 validator('form', (value) => value),1428 (c) => c.json(c.req.valid('form'))1429 )14301431 const form = new FormData()1432 form.append('__proto__', 'evil')1433 form.append('toString', 'hello')14341435 const res = await app.request('/form', { method: 'POST', body: form })1436 const result = await res.json()1437 expect(result['__proto__']).toBe('evil')1438 expect(result['toString']).toBe('hello')1439 })1440})