From ed8ed7035af7f7b334176912949d5da83b628d46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Tauer?= Date: Mon, 6 May 2024 14:21:53 +0200 Subject: [PATCH] fix: escape single quote when building error message for required property (#716) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Escape single quote in required property * Escape single quote in case the required property is missing in the list of properties * trigger ci * Add tests for double quote in property name --------- Co-authored-by: Gürgün Dayıoğlu --- index.js | 5 ++-- test/sanitize7.test.js | 68 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 2 deletions(-) create mode 100644 test/sanitize7.test.js 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!')) +})