Skip to content

Commit ed8ed70

Browse files
fix: escape single quote when building error message for required property (#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>
1 parent 7aeac5e commit ed8ed70

File tree

2 files changed

+71
-2
lines changed

2 files changed

+71
-2
lines changed

index.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -349,7 +349,8 @@ function buildInnerObject (context, location) {
349349

350350
for (const key of requiredProperties) {
351351
if (!propertiesKeys.includes(key)) {
352-
code += `if (obj['${key}'] === undefined) throw new Error('"${key}" is required!')\n`
352+
const sanitizedKey = JSON.stringify(key)
353+
code += `if (obj[${sanitizedKey}] === undefined) throw new Error('${sanitizedKey.replace(/'/g, '\\\'')} is required!')\n`
353354
}
354355
}
355356

@@ -387,7 +388,7 @@ function buildInnerObject (context, location) {
387388
`
388389
} else if (isRequired) {
389390
code += ` else {
390-
throw new Error('${sanitizedKey} is required!')
391+
throw new Error('${sanitizedKey.replace(/'/g, '\\\'')} is required!')
391392
}
392393
`
393394
} else {

test/sanitize7.test.js

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
'use strict'
2+
3+
const test = require('tap').test
4+
const build = require('..')
5+
6+
test('required property containing single quote, contains property', (t) => {
7+
t.plan(1)
8+
9+
const stringify = build({
10+
type: 'object',
11+
properties: {
12+
'\'': { type: 'string' }
13+
},
14+
required: [
15+
'\''
16+
]
17+
})
18+
19+
t.throws(() => stringify({}), new Error('"\'" is required!'))
20+
})
21+
22+
test('required property containing double quote, contains property', (t) => {
23+
t.plan(1)
24+
25+
const stringify = build({
26+
type: 'object',
27+
properties: {
28+
'"': { type: 'string' }
29+
},
30+
required: [
31+
'"'
32+
]
33+
})
34+
35+
t.throws(() => stringify({}), new Error('""" is required!'))
36+
})
37+
38+
test('required property containing single quote, does not contain property', (t) => {
39+
t.plan(1)
40+
41+
const stringify = build({
42+
type: 'object',
43+
properties: {
44+
a: { type: 'string' }
45+
},
46+
required: [
47+
'\''
48+
]
49+
})
50+
51+
t.throws(() => stringify({}), new Error('"\'" is required!'))
52+
})
53+
54+
test('required property containing double quote, does not contain property', (t) => {
55+
t.plan(1)
56+
57+
const stringify = build({
58+
type: 'object',
59+
properties: {
60+
a: { type: 'string' }
61+
},
62+
required: [
63+
'"'
64+
]
65+
})
66+
67+
t.throws(() => stringify({}), new Error('""" is required!'))
68+
})

0 commit comments

Comments
 (0)