CVE-2022-23624 (published 2022-02-07T23:15Z)

Frourio-express is a minimal full stack framework, for TypeScript. Frourio-express users who uses frourio-express version prior to v0.26.0 and integration with class-validator through `validators/` folder are subject to a input validation vulnerability. Validators do not work properly for request bodies and queries in specific situations and some input is not validated at all. Users are advised to update frourio to v0.26.0 or later and to install `class-transformer` and `reflect-metadata`.

Severity: MEDIUM
CVSS v2 base score: 6.5 (AV:N/AC:L/Au:S/C:P/I:P/A:P)
CVSS v3 base score: 8.8, HIGH (CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H)

Weakness information:
cwe_id: CWE-20
cwe_name: Improper Input Validation
description: The product receives input or data, but it does
        not validate or incorrectly validates that the input has the
        properties that are required to process the data safely and
        correctly.
extended_description: 
	   Input validation is a frequently-used technique
	   for checking potentially dangerous inputs in order to
	   ensure that the inputs are safe for processing within the
	   code, or when communicating with other components.  When
	   software does not validate input properly, an attacker is
	   able to craft the input in a form that is not expected by
	   the rest of the application. This will lead to parts of the
	   system receiving unintended input, which may result in
	   altered control flow, arbitrary control of a resource, or
	   arbitrary code execution.
	   Input validation is not the only technique for
	   processing input, however.  Other techniques attempt to
	   transform potentially-dangerous input into something safe, such
	   as filtering (CWE-790) - which attempts to remove dangerous
	   inputs - or encoding/escaping (CWE-116), which attempts to
	   ensure that the input is not misinterpreted when it is included
	   in output to another component. Other techniques exist as well
	   (see CWE-138 for more examples.)
	   Input validation can be applied to:
	   
	     raw data - strings, numbers, parameters, file contents, etc.
	     metadata - information about the raw data, such as headers or size
	   
	   Data can be simple or structured.  Structured data
	   can be composed of many nested layers, composed of
	   combinations of metadata and raw data, with other simple or
	   structured data.
	   Many properties of raw data or metadata may need
	   to be validated upon entry into the code, such
	   as:
	   
	     specified quantities such as size, length, frequency, price, rate, number of operations, time, etc.
	     implied or derived quantities, such as the actual size of a file instead of a specified size
	     indexes, offsets, or positions into more complex data structures
	     symbolic keys or other elements into hash tables, associative arrays, etc.
	     well-formedness, i.e. syntactic correctness - compliance with expected syntax 
	     lexical token correctness - compliance with rules for what is treated as a token
	     specified or derived type - the actual type of the input (or what the input appears to be)
	     consistency - between individual data elements, between raw data and metadata, between references, etc.
	     conformance to domain-specific rules, e.g. business logic 
	     equivalence - ensuring that equivalent inputs are treated the same
	     authenticity, ownership, or other attestations about the input, e.g. a cryptographic signature to prove the source of the data
	   
	   Implied or derived properties of data must often
	   be calculated or inferred by the code itself.  Errors in
	   deriving properties may be considered a contributing factor
	   to improper input validation.
	   
	   Note that "input validation" has very different
	   meanings to different people, or within different
	   classification schemes.  Caution must be used when
	   referencing this CWE entry or mapping to it.  For example,
	   some weaknesses might involve inadvertently giving control
	   to an attacker over an input when they should not be able
	   to provide an input at all, but sometimes this is referred
	   to as input validation.
	   Finally, it is important to emphasize that the
	   distinctions between input validation and output escaping
	   are often blurred, and developers must be careful to
	   understand the difference, including how input validation
	   is not always sufficient to prevent vulnerabilities,
	   especially when less stringent data types must be
	   supported, such as free-form text. Consider a SQL injection
	   scenario in which a person's last name is inserted into a
	   query. The name "O'Reilly" would likely pass the validation
	   step since it is a common last name in the English
	   language. However, this valid name cannot be directly
	   inserted into the database because it contains the "'"
	   apostrophe character, which would need to be escaped or
	   otherwise transformed. In this case, removing the
	   apostrophe might reduce the risk of SQL injection, but it
	   would produce incorrect behavior because the wrong name
	   would be recorded.
       
         
cwe_id: CWE-1321
cwe_name: Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution')
description: The product receives input from an upstream component that specifies attributes that are to be initialized or updated in an object, but it does not properly control modifications of attributes of the object prototype.
extended_description: 
				By adding or modifying attributes of an object prototype, it is possible to create attributes that exist on every object, or replace critical attributes with malicious ones. This can be problematic if the product depends on existence or non-existence of certain attributes, or uses pre-defined attributes of object prototype (such as hasOwnProperty, toString or valueOf).
				This weakness is usually exploited by using a special attribute of objects called proto,  constructor or prototype. Such attributes give access to the object prototype. This weakness is often found in code that assigns object attributes based on user input, or merges or clones objects recursively.
			
			

Fix information:
repo_url: https://github.com/frouriojs/frourio-express
commit_details: repo_url: https://github.com/frouriojs/frourio-express
author: Luma
author_date: 2022-02-04 17:58:54+09:00
msg: feat(validation): use class-transformer to support validation of nested objects

Co-authored-by: SegaraRai <SegaraRai@users.noreply.github.com>
repository: repo_url: https://github.com/frouriojs/frourio-express
repo_name: frouriojs/frourio-express
description: Fast and type-safe full stack framework, for TypeScript
repo_language: TypeScript
owner: frouriojs
file_changes: filename: index.spec.ts
change_type: ModificationType.MODIFY
diff: @@ -204,6 +204,89 @@ test('POST: 400', async () => {
   ).rejects.toHaveProperty('response.status', 400)
 })
 
+test('POST: nested validation', async () => {
+  const res1 = await client.users.post({
+    body: {
+      id: 123,
+      name: 'foo',
+      location: {
+        country: 'JP',
+        stateProvince: 'Tokyo'
+      }
+    }
+  })
+  expect(res1.status).toBe(204)
+
+  // Note that extraneous properties are allowed by default
+  const res2 = await client.users.post({
+    body: {
+      id: 123,
+      name: 'foo',
+      location: {
+        country: 'JP',
+        stateProvince: 'Tokyo',
+        extra1: {
+          extra1a: 'bar',
+          extra1b: 'baz'
+        }
+      },
+      extra2: 'qux'
+    } as any
+  })
+  expect(res2.status).toBe(204)
+})
+
+test('POST: 400 (nested validation)', async () => {
+  // id is not a number
+  await expect(
+    client.users.post({
+      body: {
+        id: '123',
+        name: 'foo',
+        location: {
+          country: 'JP',
+          stateProvince: 'Tokyo'
+        }
+      } as any
+    })
+  ).rejects.toHaveProperty('response.status', 400)
+
+  // location is missing
+  await expect(
+    client.users.post({
+      body: { id: 123, name: 'foo' } as any
+    })
+  ).rejects.toHaveProperty('response.status', 400)
+
+  // country is not a valid 2-letter country code
+  await expect(
+    client.users.post({
+      body: {
+        id: 123,
+        name: 'foo',
+        location: {
+          country: 'XX',
+          stateProvince: 'Tokyo'
+        }
+      } as any
+    })
+  ).rejects.toHaveProperty('response.status', 400)
+
+  // stateProvince is not a string
+  await expect(
+    client.users.post({
+      body: {
+        id: 123,
+        name: 'foo',
+        location: {
+          country: 'JP',
+          stateProvince: 1234
+        }
+      } as any
+    })
+  ).rejects.toHaveProperty('response.status', 400)
+})
+
 test('controller dependency injection', async () => {
   let val = 0
   const id = '5'

programming_language: TypeScript
filename: package.json
change_type: ModificationType.MODIFY
diff: @@ -97,6 +97,7 @@
     "@typescript-eslint/eslint-plugin": "^4.28.1",
     "@typescript-eslint/parser": "^4.28.1",
     "axios": "^0.21.1",
+    "class-transformer": "^0.5.1",
     "class-validator": "^0.13.1",
     "eslint": "^7.30.0",
     "eslint-config-prettier": "^8.3.0",
@@ -111,6 +112,7 @@
     "multer": "^1.4.2",
     "node-fetch": "^2.6.1",
     "prettier": "^2.3.2",
+    "reflect-metadata": "^0.1.13",
     "rimraf": "^3.0.2",
     "standard-version": "^9.3.0",
     "ts-jest": "^27.0.3",

programming_language: JavaScript
filename: $server.ts
change_type: ModificationType.MODIFY
diff: @@ -1,13 +1,17 @@
 /* eslint-disable */
 // prettier-ignore
+import 'reflect-metadata'
+// prettier-ignore
+import { ClassTransformOptions, plainToInstance } from 'class-transformer'
+// prettier-ignore
+import { validateOrReject, ValidatorOptions } from 'class-validator'
+// prettier-ignore
 import path from 'path'
 // prettier-ignore
 import express, { Express, RequestHandler, Request } from 'express'
 // prettier-ignore
 import multer, { Options } from 'multer'
 // prettier-ignore
-import { validateOrReject, ValidatorOptions } from 'class-validator'
-// prettier-ignore
 import fastJson, { Schema } from 'fast-json-stringify'
 // prettier-ignore
 import * as Validators from './validators'
@@ -47,6 +51,7 @@ import type { LowerHttpMethod, AspidaMethods, HttpStatusOk, AspidaMethodParams }
 // prettier-ignore
 export type FrourioOptions = {
   basePath?: string
+  transformer?: ClassTransformOptions
   validator?: ValidatorOptions
   multer?: Options
 }
@@ -305,6 +310,7 @@ const asyncMethodToHandlerWithSchema = (
 // prettier-ignore
 export default (app: Express, options: FrourioOptions = {}) => {
   const basePath = options.basePath ?? ''
+  const transformerOptions: ClassTransformOptions = { enableCircularCheck: true, ...options.transformer }
   const validatorOptions: ValidatorOptions = { validationError: { target: false }, ...options.validator }
   const hooks0 = hooksFn0(app)
   const hooks1 = hooksFn1(app)
@@ -332,7 +338,7 @@ export default (app: Express, options: FrourioOptions = {}) => {
     callParserIfExistsQuery(parseNumberTypeQueryParams([['requiredNum', false, false], ['optionalNum', true, false], ['optionalNumArr', true, true], ['emptyNum', true, false], ['requiredNumArr', false, true]])),
     callParserIfExistsQuery(parseBooleanTypeQueryParams([['bool', false, false], ['optionalBool', true, false], ['boolArray', false, true], ['optionalBoolArray', true, true]])),
     createValidateHandler(req => [
-      Object.keys(req.query).length ? validateOrReject(Object.assign(new Validators.Query(), req.query), validatorOptions) : null
+      Object.keys(req.query).length ? validateOrReject(plainToInstance(Validators.Query, req.query, transformerOptions), validatorOptions) : null
     ]),
     asyncMethodToHandlerWithSchema(controller0.get, responseSchema0.get)
   ])
@@ -346,8 +352,8 @@ export default (app: Express, options: FrourioOptions = {}) => {
     uploader,
     formatMulterData([]),
     createValidateHandler(req => [
-      validateOrReject(Object.assign(new Validators.Query(), req.query), validatorOptions),
-      validateOrReject(Object.assign(new Validators.Body(), req.body), validatorOptions)
+      validateOrReject(plainToInstance(Validators.Query, req.query, transformerOptions), validatorOptions),
+      validateOrReject(plainToInstance(Validators.Body, req.body, transformerOptions), validatorOptions)
     ]),
     methodToHandler(controller0.post)
   ])
@@ -372,7 +378,7 @@ export default (app: Express, options: FrourioOptions = {}) => {
     uploader,
     formatMulterData([['requiredArr', false], ['optionalArr', true], ['empty', true], ['vals', false], ['files', false]]),
     createValidateHandler(req => [
-      validateOrReject(Object.assign(new Validators.MultiForm(), req.body), validatorOptions)
+      validateOrReject(plainToInstance(Validators.MultiForm, req.body, transformerOptions), validatorOptions)
     ]),
     methodToHandler(controller3.post)
   ])
@@ -417,7 +423,7 @@ export default (app: Express, options: FrourioOptions = {}) => {
     hooks0.preParsing,
     parseJSONBoby,
     createValidateHandler(req => [
-      validateOrReject(Object.assign(new Validators.UserInfo(), req.body), validatorOptions)
+      validateOrReject(plainToInstance(Validators.UserInfo, req.body, transformerOptions), validatorOptions)
     ]),
     ...ctrlHooks1.preHandler,
     methodToHandler(controller7.post)

programming_language: TypeScript
filename: controller.ts
change_type: ModificationType.MODIFY
diff: @@ -5,5 +5,15 @@ export type AdditionalRequest = {
 }
 
 export default defineController(() => ({
-  get: ({ params }) => ({ status: 200, body: { id: params.userId, name: 'bbb' } })
+  get: ({ params }) => ({
+    status: 200,
+    body: {
+      id: params.userId,
+      name: 'bbb',
+      location: {
+        country: 'JP',
+        stateProvince: 'Tokyo'
+      }
+    }
+  })
 }))

programming_language: TypeScript
filename: controller.ts
change_type: ModificationType.MODIFY
diff: @@ -16,6 +16,18 @@ const hooks = defineHooks(() => ({
 export { hooks, AdditionalRequest }
 
 export default defineController(() => ({
-  get: async () => ({ status: 200, body: [{ id: 1, name: 'aa' }] }),
+  get: async () => ({
+    status: 200,
+    body: [
+      {
+        id: 1,
+        name: 'aa',
+        location: {
+          country: 'JP',
+          stateProvince: 'Tokyo'
+        }
+      }
+    ]
+  }),
   post: () => ({ status: 204 })
 }))

programming_language: TypeScript
filename: index.ts
change_type: ModificationType.MODIFY
diff: @@ -1,3 +1,4 @@
+import { Type } from 'class-transformer'
 import {
   IsNumberString,
   IsBooleanString,
@@ -8,7 +9,10 @@ import {
   IsString,
   Allow,
   IsOptional,
-  ArrayNotEmpty
+  ArrayNotEmpty,
+  IsISO31661Alpha2,
+  ValidateNested,
+  IsObject
 } from 'class-validator'
 import type { ReadStream } from 'fs'
 
@@ -52,12 +56,27 @@ export class Body {
   file: File | ReadStream
 }
 
+export class UserInfoLocation {
+  @IsISO31661Alpha2()
+  country: string
+
+  @IsString()
+  stateProvince: string
+}
+
 export class UserInfo {
   @IsInt()
   id: number
 
   @MaxLength(20)
   name: string
+
+  // @Type decorator is required to validate nested object properly
+  // @IsObject decorator is required or class-validator will not throw an error when the property is missing
+  @ValidateNested()
+  @IsObject()
+  @Type(() => UserInfoLocation)
+  location: UserInfoLocation
 }
 
 export class MultiForm {

programming_language: TypeScript
filename: $server.ts
change_type: ModificationType.MODIFY
diff: @@ -1,9 +1,13 @@
 /* eslint-disable */
 // prettier-ignore
-import express, { Express, RequestHandler, Request } from 'express'
+import 'reflect-metadata'
+// prettier-ignore
+import { ClassTransformOptions, plainToInstance } from 'class-transformer'
 // prettier-ignore
 import { validateOrReject, ValidatorOptions } from 'class-validator'
 // prettier-ignore
+import express, { Express, RequestHandler, Request } from 'express'
+// prettier-ignore
 import * as Validators from './validators'
 // prettier-ignore
 import hooksFn0 from './api/hooks'
@@ -27,6 +31,7 @@ import type { LowerHttpMethod, AspidaMethods, HttpStatusOk, AspidaMethodParams }
 // prettier-ignore
 export type FrourioOptions = {
   basePath?: string
+  transformer?: ClassTransformOptions
   validator?: ValidatorOptions
 }
 
@@ -144,6 +149,7 @@ const asyncMethodToHandler = (
 // prettier-ignore
 export default (app: Express, options: FrourioOptions = {}) => {
   const basePath = options.basePath ?? ''
+  const transformerOptions: ClassTransformOptions = { enableCircularCheck: true, ...options.transformer }
   const validatorOptions: ValidatorOptions = { validationError: { target: false }, ...options.validator }
   const hooks0 = hooksFn0(app)
   const hooks1 = hooksFn1(app)
@@ -160,7 +166,7 @@ export default (app: Express, options: FrourioOptions = {}) => {
     hooks0.onRequest,
     ctrlHooks0.onRequest,
     createValidateHandler(req => [
-      Object.keys(req.query).length ? validateOrReject(Object.assign(new Validators.Query(), req.query), validatorOptions) : null
+      Object.keys(req.query).length ? validateOrReject(plainToInstance(Validators.Query, req.query, transformerOptions), validatorOptions) : null
     ]),
     asyncMethodToHandler(controller0.get)
   ])
@@ -170,8 +176,8 @@ export default (app: Express, options: FrourioOptions = {}) => {
     ctrlHooks0.onRequest,
     parseJSONBoby,
     createValidateHandler(req => [
-      validateOrReject(Object.assign(new Validators.Query(), req.query), validatorOptions),
-      validateOrReject(Object.assign(new Validators.Body(), req.body), validatorOptions)
+      validateOrReject(plainToInstance(Validators.Query, req.query, transformerOptions), validatorOptions),
+      validateOrReject(plainToInstance(Validators.Body, req.body, transformerOptions), validatorOptions)
     ]),
     methodToHandler(controller0.post)
   ])
@@ -209,7 +215,7 @@ export default (app: Express, options: FrourioOptions = {}) => {
     hooks1.onRequest,
     parseJSONBoby,
     createValidateHandler(req => [
-      validateOrReject(Object.assign(new Validators.UserInfo(), req.body), validatorOptions)
+      validateOrReject(plainToInstance(Validators.UserInfo, req.body, transformerOptions), validatorOptions)
     ]),
     ...ctrlHooks1.preHandler,
     methodToHandler(controller4.post)

programming_language: TypeScript
filename: $server.ts
change_type: ModificationType.MODIFY
diff: @@ -1,13 +1,17 @@
 /* eslint-disable */
 // prettier-ignore
+import 'reflect-metadata'
+// prettier-ignore
+import { ClassTransformOptions, plainToInstance } from 'class-transformer'
+// prettier-ignore
+import { validateOrReject, ValidatorOptions } from 'class-validator'
+// prettier-ignore
 import path from 'path'
 // prettier-ignore
 import express, { Express, RequestHandler, Request } from 'express'
 // prettier-ignore
 import multer, { Options } from 'multer'
 // prettier-ignore
-import { validateOrReject, ValidatorOptions } from 'class-validator'
-// prettier-ignore
 import * as Validators from './validators'
 // prettier-ignore
 import hooksFn0 from './api/hooks'
@@ -33,6 +37,7 @@ import type { LowerHttpMethod, AspidaMethods, HttpStatusOk, AspidaMethodParams }
 // prettier-ignore
 export type FrourioOptions = {
   basePath?: string
+  transformer?: ClassTransformOptions
   validator?: ValidatorOptions
   multer?: Options
 }
@@ -174,6 +179,7 @@ const asyncMethodToHandler = (
 // prettier-ignore
 export default (app: Express, options: FrourioOptions = {}) => {
   const basePath = options.basePath ?? ''
+  const transformerOptions: ClassTransformOptions = { enableCircularCheck: true, ...options.transformer }
   const validatorOptions: ValidatorOptions = { validationError: { target: false }, ...options.validator }
   const hooks0 = hooksFn0(app)
   const hooks1 = hooksFn1(app)
@@ -191,7 +197,7 @@ export default (app: Express, options: FrourioOptions = {}) => {
     hooks0.onRequest,
     ctrlHooks0.onRequest,
     createValidateHandler(req => [
-      Object.keys(req.query).length ? validateOrReject(Object.assign(new Validators.Query(), req.query), validatorOptions) : null
+      Object.keys(req.query).length ? validateOrReject(plainToInstance(Validators.Query, req.query, transformerOptions), validatorOptions) : null
     ]),
     asyncMethodToHandler(controller0.get)
   ])
@@ -202,8 +208,8 @@ export default (app: Express, options: FrourioOptions = {}) => {
     uploader,
     formatMulterData([]),
     createValidateHandler(req => [
-      validateOrReject(Object.assign(new Validators.Query(), req.query), validatorOptions),
-      validateOrReject(Object.assign(new Validators.Body(), req.body), validatorOptions)
+      validateOrReject(plainToInstance(Validators.Query, req.query, transformerOptions), validatorOptions),
+      validateOrReject(plainToInstance(Validators.Body, req.body, transformerOptions), validatorOptions)
     ]),
     methodToHandler(controller0.post)
   ])
@@ -218,7 +224,7 @@ export default (app: Express, options: FrourioOptions = {}) => {
     uploader,
     formatMulterData([['empty', false], ['vals', false], ['files', false]]),
     createValidateHandler(req => [
-      validateOrReject(Object.assign(new Validators.MultiForm(), req.body), validatorOptions)
+      validateOrReject(plainToInstance(Validators.MultiForm, req.body, transformerOptions), validatorOptions)
     ]),
     methodToHandler(controller2.post)
   ])
@@ -251,7 +257,7 @@ export default (app: Express, options: FrourioOptions = {}) => {
     hooks1.onRequest,
     parseJSONBoby,
     createValidateHandler(req => [
-      validateOrReject(Object.assign(new Validators.UserInfo(), req.body), validatorOptions)
+      validateOrReject(plainToInstance(Validators.UserInfo, req.body, transformerOptions), validatorOptions)
     ]),
     ...ctrlHooks1.preHandler,
     methodToHandler(controller5.post)

programming_language: TypeScript
filename: buildServerFile.ts
change_type: ModificationType.MODIFY
diff: @@ -1,6 +1,7 @@
 import path from 'path'
 import { addPrettierIgnore } from './addPrettierIgnore'
 import createControllersText from './createControllersText'
+import checkRequisites from './checkRequisites'
 
 const genHandlerText = (isAsync: boolean) => `
 const ${isAsync ? 'asyncM' : 'm'}ethodToHandler = (
@@ -77,13 +78,19 @@ export default (input: string, project?: string) => {
   const hasMethodToHandlerWithSchema = controllers.includes(' methodToHandlerWithSchema(')
   const hasAsyncMethodToHandlerWithSchema = controllers.includes(' asyncMethodToHandlerWithSchema(')
 
+  checkRequisites({ hasValidator })
+
   return {
-    text: addPrettierIgnore(`/* eslint-disable */${hasMulter ? "\nimport path from 'path'" : ''}
+    text: addPrettierIgnore(`/* eslint-disable */${
+      hasValidator
+        ? "\nimport 'reflect-metadata'" +
+          "\nimport { ClassTransformOptions, plainToInstance } from 'class-transformer'" +
+          "\nimport { validateOrReject, ValidatorOptions } from 'class-validator'"
+        : ''
+    }${hasMulter ? "\nimport path from 'path'" : ''}
 import ${hasJSONBody ? 'express, ' : ''}{ Express, RequestHandler${
       hasValidator ? ', Request' : ''
     } } from 'express'${hasMulter ? "\nimport multer, { Options } from 'multer'" : ''}${
-      hasValidator ? "\nimport { validateOrReject, ValidatorOptions } from 'class-validator'" : ''
-    }${
       hasMethodToHandlerWithSchema || hasAsyncMethodToHandlerWithSchema
         ? "\nimport fastJson, { Schema } from 'fast-json-stringify'"
         : ''
@@ -94,7 +101,7 @@ ${hasValidator ? `import * as Validators from './validators'\n` : ''}${imports}$
 
 export type FrourioOptions = {
   basePath?: string
-${hasValidator ? '  validator?: ValidatorOptions\n' : ''}${
+${hasValidator ? '  transformer?: ClassTransformOptions\n  validator?: ValidatorOptions\n' : ''}${
       hasMulter
         ? `  multer?: Options
 }
@@ -299,7 +306,8 @@ export default (app: Express, options: FrourioOptions = {}) => {
   const basePath = options.basePath ?? ''
 ${
   hasValidator
-    ? '  const validatorOptions: ValidatorOptions = { validationError: { target: false }, ...options.validator }\n'
+    ? '  const transformerOptions: ClassTransformOptions = { enableCircularCheck: true, ...options.transformer }\n' +
+      '  const validatorOptions: ValidatorOptions = { validationError: { target: false }, ...options.validator }\n'
     : ''
 }${consts}${
       hasMulter

programming_language: TypeScript
filename: checkRequisites.ts
change_type: ModificationType.ADD
diff: @@ -0,0 +1,21 @@
+const shouldRequirePacakge = (name: string) => {
+  try {
+    require.resolve(name)
+  } catch (e: unknown) {
+    if (e instanceof Error && (e as any).code === 'MODULE_NOT_FOUND') {
+      console.warn(
+        `[WARN] Package "${name}" is necessary but not importable. Did you forget to install?`
+      )
+    } else {
+      throw e
+    }
+  }
+}
+
+export default ({ hasValidator }: { hasValidator: boolean }): void => {
+  if (hasValidator) {
+    shouldRequirePacakge('class-validator')
+    shouldRequirePacakge('class-transformer')
+    shouldRequirePacakge('reflect-metadata')
+  }
+}

programming_language: TypeScript
filename: createControllersText.ts
change_type: ModificationType.MODIFY
diff: @@ -470,9 +470,9 @@ ${validateInfo
     v.type
       ? `      ${
           v.hasQuestion ? `Object.keys(req.${v.name}).length ? ` : ''
-        }validateOrReject(Object.assign(new Validators.${checker.typeToString(v.type)}(), req.${
+        }validateOrReject(plainToInstance(Validators.${checker.typeToString(v.type)}, req.${
           v.name
-        }), validatorOptions)${v.hasQuestion ? ' : null' : ''}`
+        }, transformerOptions), validatorOptions)${v.hasQuestion ? ' : null' : ''}`
       : ''
   )
   .join(',\n')}\n    ])`

programming_language: TypeScript
filename: yarn.lock
change_type: ModificationType.MODIFY
diff: @@ -1682,6 +1682,11 @@ cjs-module-lexer@^1.0.0:
   resolved "https://registry.yarnpkg.com/cjs-module-lexer/-/cjs-module-lexer-1.2.1.tgz#2fd46d9906a126965aa541345c499aaa18e8cd73"
   integrity sha512-jVamGdJPDeuQilKhvVn1h3knuMOZzr8QDnpk+M9aMlCaMkTDd6fBWPhiDqFvFZ07pL0liqabAiuy8SY4jGHeaw==
 
+class-transformer@^0.5.1:
+  version "0.5.1"
+  resolved "https://registry.yarnpkg.com/class-transformer/-/class-transformer-0.5.1.tgz#24147d5dffd2a6cea930a3250a677addf96ab336"
+  integrity sha512-SQa1Ws6hUbfC98vKGxZH3KFY0Y1lm5Zm0SY8XX9zbK7FJCyVEac3ATW0RIpwzW+oOfmHE5PMPufDG9hCfoEOMw==
+
 class-validator@^0.13.1:
   version "0.13.1"
   resolved "https://registry.yarnpkg.com/class-validator/-/class-validator-0.13.1.tgz#381b2001ee6b9e05afd133671fbdf760da7dec67"
@@ -4931,6 +4936,11 @@ redent@^3.0.0:
     indent-string "^4.0.0"
     strip-indent "^3.0.0"
 
+reflect-metadata@^0.1.13:
+  version "0.1.13"
+  resolved "https://registry.yarnpkg.com/reflect-metadata/-/reflect-metadata-0.1.13.tgz#67ae3ca57c972a2aa1642b10fe363fe32d49dc08"
+  integrity sha512-Ts1Y/anZELhSsjMcU605fU9RE4Oi3p5ORujwbIKXfWa+0Zxs510Qrmrce5/Jowq3cHSZSJqBjypxmHarc+vEWg==
+
 regexpp@^3.0.0, regexpp@^3.1.0:
   version "3.1.0"
   resolved "https://registry.yarnpkg.com/regexpp/-/regexpp-3.1.0.tgz#206d0ad0a5648cffbdb8ae46438f3dc51c9f78e2"

programming_language: Shell