Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: escape single quote when building error message for required property #716

Merged
merged 5 commits into from
May 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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!'))
})