|
| 1 | +import Ajv from 'ajv'; |
| 2 | +import { InternalServerError, INTERNAL_SERVER_ERROR } from 'http-errors-enhanced'; |
| 3 | +import { kHttpErrorsEnhancedProperties, kHttpErrorsEnhancedResponseValidations } from "./interfaces.mjs"; |
| 4 | +import { get } from "./utils.mjs"; |
| 5 | +export function niceJoin(array, lastSeparator = ' and ', separator = ', ') { |
| 6 | + switch (array.length) { |
| 7 | + case 0: |
| 8 | + return ''; |
| 9 | + case 1: |
| 10 | + return array[0]; |
| 11 | + case 2: |
| 12 | + return array.join(lastSeparator); |
| 13 | + default: |
| 14 | + return array.slice(0, array.length - 1).join(separator) + lastSeparator + array[array.length - 1]; |
| 15 | + } |
| 16 | +} |
| 17 | +export const validationMessagesFormatters = { |
| 18 | + contentType: () => 'only JSON payloads are accepted. Please set the "Content-Type" header to start with "application/json"', |
| 19 | + json: () => 'the body payload is not a valid JSON', |
| 20 | + jsonEmpty: () => 'the JSON body payload cannot be empty if the "Content-Type" header is set', |
| 21 | + missing: () => 'must be present', |
| 22 | + unknown: () => 'is not a valid property', |
| 23 | + uuid: () => 'must be a valid GUID (UUID v4)', |
| 24 | + timestamp: () => 'must be a valid ISO 8601 / RFC 3339 timestamp (example: 2018-07-06T12:34:56Z)', |
| 25 | + date: () => 'must be a valid ISO 8601 / RFC 3339 date (example: 2018-07-06)', |
| 26 | + time: () => 'must be a valid ISO 8601 / RFC 3339 time (example: 12:34:56)', |
| 27 | + hostname: () => 'must be a valid hostname', |
| 28 | + ipv4: () => 'must be a valid IPv4', |
| 29 | + ipv6: () => 'must be a valid IPv6', |
| 30 | + paramType: (type) => { |
| 31 | + switch (type) { |
| 32 | + case 'integer': |
| 33 | + return 'must be a valid integer number'; |
| 34 | + case 'number': |
| 35 | + return 'must be a valid number'; |
| 36 | + case 'boolean': |
| 37 | + return 'must be a valid boolean (true or false)'; |
| 38 | + case 'object': |
| 39 | + return 'must be a object'; |
| 40 | + case 'array': |
| 41 | + return 'must be an array'; |
| 42 | + default: |
| 43 | + return 'must be a string'; |
| 44 | + } |
| 45 | + }, |
| 46 | + presentString: () => 'must be a non empty string', |
| 47 | + minimum: (min) => `must be a number greater than or equal to ${min}`, |
| 48 | + maximum: (max) => `must be a number less than or equal to ${max}`, |
| 49 | + minimumProperties(min) { |
| 50 | + return min === 1 ? 'cannot be a empty object' : `must be a object with at least ${min} properties`; |
| 51 | + }, |
| 52 | + maximumProperties(max) { |
| 53 | + return max === 0 ? 'must be a empty object' : `must be a object with at most ${max} properties`; |
| 54 | + }, |
| 55 | + minimumItems(min) { |
| 56 | + return min === 1 ? 'cannot be a empty array' : `must be an array with at least ${min} items`; |
| 57 | + }, |
| 58 | + maximumItems(max) { |
| 59 | + return max === 0 ? 'must be a empty array' : `must be an array with at most ${max} items`; |
| 60 | + }, |
| 61 | + enum: (values) => `must be one of the following values: ${niceJoin(values.map((f) => `"${f}"`), ' or ')}`, |
| 62 | + pattern: (pattern) => `must match pattern "${pattern.replace(/\(\?:/g, '(')}"`, |
| 63 | + invalidResponseCode: (code) => `This endpoint cannot respond with HTTP status ${code}.`, |
| 64 | + invalidResponse: (code) => `The response returned from the endpoint violates its specification for the HTTP status ${code}.`, |
| 65 | + invalidFormat: (format) => `must match format "${format}" (format)` |
| 66 | +}; |
| 67 | +export function convertValidationErrors(section, data, validationErrors) { |
| 68 | + const errors = {}; |
| 69 | + if (section === 'querystring') { |
| 70 | + section = 'query'; |
| 71 | + } |
| 72 | + // For each error |
| 73 | + for (const e of validationErrors) { |
| 74 | + let message = ''; |
| 75 | + let pattern; |
| 76 | + let value; |
| 77 | + let reason; |
| 78 | + // Normalize the key |
| 79 | + let key = e.dataPath; |
| 80 | + if (key.startsWith('.')) { |
| 81 | + key = key.substring(1); |
| 82 | + } |
| 83 | + // Remove useless quotes |
| 84 | + /* istanbul ignore next */ |
| 85 | + if (key.startsWith('[') && key.endsWith(']')) { |
| 86 | + key = key.substring(1, key.length - 1); |
| 87 | + } |
| 88 | + // Depending on the type |
| 89 | + switch (e.keyword) { |
| 90 | + case 'required': |
| 91 | + case 'dependencies': |
| 92 | + key = e.params.missingProperty; |
| 93 | + message = validationMessagesFormatters.missing(); |
| 94 | + break; |
| 95 | + case 'additionalProperties': |
| 96 | + key = e.params.additionalProperty; |
| 97 | + message = validationMessagesFormatters.unknown(); |
| 98 | + break; |
| 99 | + case 'type': |
| 100 | + message = validationMessagesFormatters.paramType(e.params.type); |
| 101 | + break; |
| 102 | + case 'minProperties': |
| 103 | + message = validationMessagesFormatters.minimumProperties(e.params.limit); |
| 104 | + break; |
| 105 | + case 'maxProperties': |
| 106 | + message = validationMessagesFormatters.maximumProperties(e.params.limit); |
| 107 | + break; |
| 108 | + case 'minItems': |
| 109 | + message = validationMessagesFormatters.minimumItems(e.params.limit); |
| 110 | + break; |
| 111 | + case 'maxItems': |
| 112 | + message = validationMessagesFormatters.maximumItems(e.params.limit); |
| 113 | + break; |
| 114 | + case 'minimum': |
| 115 | + message = validationMessagesFormatters.minimum(e.params.limit); |
| 116 | + break; |
| 117 | + case 'maximum': |
| 118 | + message = validationMessagesFormatters.maximum(e.params.limit); |
| 119 | + break; |
| 120 | + case 'enum': |
| 121 | + message = validationMessagesFormatters.enum(e.params.allowedValues); |
| 122 | + break; |
| 123 | + case 'pattern': |
| 124 | + pattern = e.params.pattern; |
| 125 | + value = get(data, key); |
| 126 | + if (pattern === '.+' && !value) { |
| 127 | + message = validationMessagesFormatters.presentString(); |
| 128 | + } |
| 129 | + else { |
| 130 | + message = validationMessagesFormatters.pattern(e.params.pattern); |
| 131 | + } |
| 132 | + break; |
| 133 | + case 'format': |
| 134 | + reason = e.params.format; |
| 135 | + // Normalize the key |
| 136 | + if (reason === 'date-time') { |
| 137 | + reason = 'timestamp'; |
| 138 | + } |
| 139 | + message = (validationMessagesFormatters[reason] || validationMessagesFormatters.invalidFormat)(reason); |
| 140 | + break; |
| 141 | + } |
| 142 | + // No custom message was found, default to input one replacing the starting verb and adding some path info |
| 143 | + if (!message.length) { |
| 144 | + message = `${e.message.replace(/^should/, 'must')} (${e.keyword})`; |
| 145 | + } |
| 146 | + // Remove useless quotes |
| 147 | + /* istanbul ignore next */ |
| 148 | + if (key.match(/(?:^['"])(?:[^.]+)(?:['"]$)/)) { |
| 149 | + key = key.substring(1, key.length - 1); |
| 150 | + } |
| 151 | + // Fix empty properties |
| 152 | + if (!key) { |
| 153 | + key = '$root'; |
| 154 | + } |
| 155 | + key = key.replace(/^\//, ''); |
| 156 | + errors[key] = message; |
| 157 | + } |
| 158 | + return { [section]: errors }; |
| 159 | +} |
| 160 | +export function addResponseValidation(route) { |
| 161 | + var _a; |
| 162 | + if (!((_a = route.schema) === null || _a === void 0 ? void 0 : _a.response)) { |
| 163 | + return; |
| 164 | + } |
| 165 | + const validators = {}; |
| 166 | + /* |
| 167 | + Add these validators to the list of the one to compile once the server is started. |
| 168 | + This makes possible to handle shared schemas. |
| 169 | + */ |
| 170 | + this[kHttpErrorsEnhancedResponseValidations].push([ |
| 171 | + this, |
| 172 | + validators, |
| 173 | + Object.entries(route.schema.response) |
| 174 | + ]); |
| 175 | + // Note that this hook is not called for non JSON payloads therefore validation is not possible in such cases |
| 176 | + route.preSerialization = async function (request, reply, payload) { |
| 177 | + const statusCode = reply.raw.statusCode; |
| 178 | + // Never validate error 500 |
| 179 | + if (statusCode === INTERNAL_SERVER_ERROR) { |
| 180 | + return payload; |
| 181 | + } |
| 182 | + // No validator, it means the HTTP status is not allowed |
| 183 | + const validator = validators[statusCode]; |
| 184 | + if (!validator) { |
| 185 | + if (request[kHttpErrorsEnhancedProperties].allowUndeclaredResponses) { |
| 186 | + return payload; |
| 187 | + } |
| 188 | + throw new InternalServerError(validationMessagesFormatters.invalidResponseCode(statusCode)); |
| 189 | + } |
| 190 | + // Now validate the payload |
| 191 | + const valid = validator(payload); |
| 192 | + if (!valid) { |
| 193 | + throw new InternalServerError(validationMessagesFormatters.invalidResponse(statusCode), { |
| 194 | + failedValidations: convertValidationErrors('response', payload, validator.errors) |
| 195 | + }); |
| 196 | + } |
| 197 | + return payload; |
| 198 | + }; |
| 199 | +} |
| 200 | +export function compileResponseValidationSchema() { |
| 201 | + // Fix CJS/ESM interoperability |
| 202 | + // @ts-expect-error |
| 203 | + let AjvConstructor = Ajv; |
| 204 | + /* istanbul ignore next */ |
| 205 | + if (AjvConstructor.default) { |
| 206 | + AjvConstructor = AjvConstructor.default; |
| 207 | + } |
| 208 | + for (const [instance, validators, schemas] of this[kHttpErrorsEnhancedResponseValidations]) { |
| 209 | + // @ts-expect-error |
| 210 | + const compiler = new AjvConstructor({ |
| 211 | + // The fastify defaults, with the exception of removeAdditional and coerceTypes, which have been reversed |
| 212 | + removeAdditional: false, |
| 213 | + useDefaults: true, |
| 214 | + coerceTypes: false, |
| 215 | + allErrors: true |
| 216 | + }); |
| 217 | + compiler.addSchema(Object.values(instance.getSchemas())); |
| 218 | + compiler.addKeyword('example'); |
| 219 | + for (const [code, schema] of schemas) { |
| 220 | + validators[code] = compiler.compile(schema); |
| 221 | + } |
| 222 | + } |
| 223 | +} |
0 commit comments