All files / src/shared ParametersValidator.ts

77.57% Statements 83/107
78.57% Branches 33/42
100% Functions 4/4
77.35% Lines 82/106

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 2151x                     1x 1x   1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x                           926x   1x   357x   357x 1043x   1043x   1043x   1043x 4x     1039x 2x 2x   2x   2x     1037x 14x   14x 14x   14x     1023x   1023x       357x 7x           548x   548x   13x 13x 13x               33x 33x 33x                                   307x 307x 307x     8x 8x 8x               134x 134x 134x     53x 53x 53x     548x       1037x   1037x   1037x   1037x 2x     1037x 111x     926x 548x   548x 7x   378x                       378x   378x 772x     378x 378x   378x                   378x         926x      
import {
  validate,
  isDefined,
  isString,
  isNumber,
  isArray,
  isBoolean,
  isObject,
  matches,
  isISO8601,
} from 'class-validator'
import Ajv from 'ajv'
import S from 'fluent-schema'
 
import { DID, DID_METHOD, JWT, COGNITO_CONFIRMATION_CODE, PASSWORD } from '../dto/shared.dto'
import SdkErrorFromCode from './SdkErrorFromCode'
 
const did = 'did'
const didMethod = 'didMethod'
const jwt = 'jwt'
const array = 'array'
const number = 'number'
const object = 'object'
const string = 'string'
const boolean = 'boolean'
const isoString = 'isoString'
const confirmationCode = 'confirmationCode'
const password = 'password'
 
const primitives = [did, didMethod, jwt, array, number, object, string, boolean, isoString, confirmationCode, password]
const jsonSchemas = {
  VCV1: S.object()
    .prop('@context', S.anyOf([S.array().items(S.anyOf([S.string(), S.object()])), S.object(), S.string()]))
    .prop('id', S.string())
    .prop('type', S.array().items(S.string()))
    .prop('holder', S.object().prop('id', S.string()).required(['id']))
    // Credential Subject may be a single item or an array of items
    .prop('credentialSubject', S.anyOf([S.array(), S.object()]))
    .prop('issuanceDate', S.string().format('date-time'))
    .prop('expirationDate', S.string().format('date-time'))
    .prop('revocation', S.object().prop('id', S.string()).required(['id']))
    .required(['@context', 'id', 'type', 'holder', 'credentialSubject', 'issuanceDate']),
}
 
const isPrimitive = (schema: string) => primitives.includes(schema)
 
export class ParametersValidator {
  static async validate(schemas: any) {
    const allErrors: any = []
 
    for (const [index, schema] of schemas.entries()) {
      const { isArray, type, isRequired, value: SchemaValue } = schema
 
      let errors: any = []
 
      const isArrayValid = Array.isArray(SchemaValue) && SchemaValue
 
      if (isArray && isArrayValid && SchemaValue.length === 0) {
        continue
      }
 
      if (isArray && !isArrayValid) {
        const message = `Parameter at index [${index}] should be an array.`
        const error = { value: SchemaValue, message }
 
        allErrors.push(error)
 
        continue
      }
 
      if (isArray) {
        const items = SchemaValue
 
        for (const item of items) {
          errors = await ParametersValidator.process({ type, isRequired, value: item }, index)
 
          allErrors.push(...errors)
        }
      } else {
        errors = await ParametersValidator.process(schema, index)
 
        allErrors.push(...errors)
      }
    }
 
    if (allErrors.length > 0) {
      throw new SdkErrorFromCode('COR-1', { errors: allErrors })
    }
  }
 
  static validatePrimitive(schema: string, value: any) {
    let message: string
    let isValid: boolean = true
 
    switch (schema) {
      case did:
        isValid = matches(value, DID)
        message = `Parameter "${value}" is not a valid. Valid format: (${DID}).`
        break
 
      case didMethod:
        isValid = matches(value, DID_METHOD)
        message = `Parameter "${value}" is not a valid. Valid format: (${DID_METHOD}).`
        break
 
      case jwt:
        isValid = matches(value, JWT)
        message = `Parameter "${value}" is not a valid JWT. Valid format: (${JWT}).`
        break
 
      case array:
        isValid = isArray(value)
        message = `Parameter "${value}" should be an array.`
        break
 
      case number:
        isValid = isNumber(value)
        message = `Parameter "${value}" should be a number.`
        break
 
      case object:
        isValid = isObject(value)
        message = `Parameter "${value}" should be an object.`
        break
 
      case string:
        isValid = isString(value)
        message = `Parameter "${value}" should be a string.`
        break
 
      case boolean:
        isValid = isBoolean(value)
        message = `Parameter "${value}" should be a boolean.`
        break
 
      case isoString:
        isValid = isISO8601(value)
        message = `Parameter "${value}" is not a valid ISO 8601 date string.`
        break
 
      case confirmationCode:
        isValid = matches(value, COGNITO_CONFIRMATION_CODE)
        message = `Parameter "${value}" is not a valid confirmation code. Valid format: (${COGNITO_CONFIRMATION_CODE}).`
        break
 
      case password:
        isValid = matches(value, PASSWORD)
        message = `Parameter "${value}" is not a password. Valid format: (${PASSWORD}).`
        break
    }
 
    return { isValid, message }
  }
 
  static async process(schema: any, index: number) {
    const { type: Schema, isRequired, value: SchemaValue } = schema
 
    const allErrors: any = []
 
    const isUndefined = !isDefined(SchemaValue)
 
    if (isRequired && isUndefined) {
      allErrors.push({ value: SchemaValue, message: `Required parameter at index [${index}] is missing.` })
    }
 
    if (isUndefined) {
      return allErrors
    }
 
    if (isPrimitive(Schema)) {
      const { isValid, message } = ParametersValidator.validatePrimitive(Schema, SchemaValue)
 
      if (!isValid) {
        allErrors.push({ value: SchemaValue, message })
      }
    } else Iif (Object.keys(jsonSchemas).indexOf(Schema) !== -1) {
      try {
        const ajv = new Ajv()
        const isValid = ajv.validate(jsonSchemas[Schema as keyof typeof jsonSchemas].valueOf(), SchemaValue)
 
        if (!isValid) {
          allErrors.push({ value: SchemaValue, message: ajv.errorsText() })
        }
      } catch (error) {
        allErrors.push({ value: SchemaValue, message: error })
      }
    } else {
      const schema = new Schema()
 
      for (const [key, value] of Object.entries(SchemaValue)) {
        schema[key] = value
      }
 
      const errors = await validate(schema)
      const schemaErrors = []
 
      for (const error of errors) {
        const { property, value, constraints } = error
 
        schemaErrors.push({
          argument: property,
          value: value,
          message: constraints,
        })
      }
 
      Iif (schemaErrors.length > 0) {
        allErrors.push(schemaErrors)
      }
    }
 
    return allErrors
  }
}