Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 34 additions & 1 deletion src/dynamic-handle.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Kind } from '@sinclair/typebox'
import { TransformDecodeError } from '@sinclair/typebox/value'
import type { Context } from './context'
import { parseCookie } from './cookies'
Expand All @@ -10,8 +11,13 @@ import {
} from './error'
import type { AnyElysia, CookieOptions } from './index'
import { parseQuery } from './parse-query'
import { getSchemaProperties, type ElysiaTypeCheck } from './schema'
import {
getSchemaProperties,
unwrapImportSchema,
type ElysiaTypeCheck
} from './schema'
import type { TypeCheck } from './type-system'
import { fileType } from './type-system/utils'
import type { Handler, LifeCycleStore, SchemaValidator } from './types'
import { hasSetImmediate, redirect, StatusMap, signCookie } from './utils'

Expand Down Expand Up @@ -616,6 +622,33 @@ export const createDynamicHandler = (app: AnyElysia) => {
// Zod returns { value: ... } wrapper
context.body = decoded?.value ?? decoded
}

// Validate file contents by magic bytes, mirroring the AOT path
// (`compose.ts`) which injects `fileType(...)` for File/Files
// fields that declare an extension. Without this, dynamic mode
// (`aot: false`) only checks the client-supplied MIME type and
// accepts a file whose bytes do not match the declared type.
if (validator.body) {
const bodyProperties = getSchemaProperties(
unwrapImportSchema(validator.body.schema)
)

if (bodyProperties)
for (const key in bodyProperties) {
const property = bodyProperties[key]

if (
property.extension &&
(property[Kind] === 'File' ||
property[Kind] === 'Files')
)
await fileType(
(context.body as any)?.[key],
property.extension,
`body.${key}`
)
}
}
}

if (hooks.beforeHandle)
Expand Down
32 changes: 32 additions & 0 deletions test/validator/body.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -836,6 +836,38 @@ describe('Body Validator', () => {
}
})

it('validate actual file in dynamic mode', async () => {
const app = new Elysia({ aot: false }).post(
'/upload',
({ body: { file } }) => file.size,
{
body: t.Object({
file: t.File({
type: 'image'
})
})
}
)

{
const { request, size } = upload('/upload', {
file: 'millenium.jpg'
})

const response = await app.handle(request).then((r) => r.text())
expect(+response).toBe(size)
}

{
const { request } = upload('/upload', {
file: 'fake.jpg'
})

const status = await app.handle(request).then((r) => r.status)
expect(status).toBe(422)
}
})

it('validate actual file with multiple type', async () => {
const app = new Elysia().post(
'/upload',
Expand Down