diff --git a/index.js b/index.js index b9be60a6..862c7c83 100644 --- a/index.js +++ b/index.js @@ -349,7 +349,8 @@ function buildInnerObject (context, location) { for (const key of requiredProperties) { if (!propertiesKeys.includes(key)) { - code += `if (obj['${key}'] === undefined) throw new Error('"${key}" is required!')\n` + const sanitizedKey = JSON.stringify(key) + code += `if (obj[${sanitizedKey}] === undefined) throw new Error('${sanitizedKey.replace(/'/g, '\\\'')} is required!')\n` } } @@ -387,7 +388,7 @@ function buildInnerObject (context, location) { ` } else if (isRequired) { code += ` else { - throw new Error('${sanitizedKey} is required!') + throw new Error('${sanitizedKey.replace(/'/g, '\\\'')} is required!') } ` } else { diff --git a/test/sanitize7.test.js b/test/sanitize7.test.js new file mode 100644 index 00000000..530c1856 --- /dev/null +++ b/test/sanitize7.test.js @@ -0,0 +1,68 @@ +'use strict' + +const test = require('tap').test +const build = require('..') + +test('required property containing single quote, contains property', (t) => { + t.plan(1) + + const stringify = build({ + type: 'object', + properties: { + '\'': { type: 'string' } + }, + required: [ + '\'' + ] + }) + + t.throws(() => stringify({}), new Error('"\'" is required!')) +}) + +test('required property containing double quote, contains property', (t) => { + t.plan(1) + + const stringify = build({ + type: 'object', + properties: { + '"': { type: 'string' } + }, + required: [ + '"' + ] + }) + + t.throws(() => stringify({}), new Error('""" is required!')) +}) + +test('required property containing single quote, does not contain property', (t) => { + t.plan(1) + + const stringify = build({ + type: 'object', + properties: { + a: { type: 'string' } + }, + required: [ + '\'' + ] + }) + + t.throws(() => stringify({}), new Error('"\'" is required!')) +}) + +test('required property containing double quote, does not contain property', (t) => { + t.plan(1) + + const stringify = build({ + type: 'object', + properties: { + a: { type: 'string' } + }, + required: [ + '"' + ] + }) + + t.throws(() => stringify({}), new Error('""" is required!')) +})