Skip to content

Commit

Permalink
fix: escape single quote when building error message for required pro…
Browse files Browse the repository at this point in the history
…perty (#716)

* 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 <hey@gurgun.day>
  • Loading branch information
tomastauer and gurgunday committed May 6, 2024
1 parent 7aeac5e commit ed8ed70
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 2 deletions.
5 changes: 3 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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`
}
}

Expand Down Expand Up @@ -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 {
Expand Down
68 changes: 68 additions & 0 deletions test/sanitize7.test.js
Original file line number Diff line number Diff line change
@@ -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!'))
})

0 comments on commit ed8ed70

Please sign in to comment.