Skip to content
Myr

Merge commit from fork

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* fix(jsx): prevent CSS injection via `;` in style object values * apply the patch Co-authored-by: Taku Amano <taku@taaas.jp> ---------

authored by Yusuke Wada · committed by GitHub · parent 568c2ec · Browse files · 4 files+388 added−13 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Taku Amano <taku@taaas.jp>

Diff stats

4 files+388 added−13 removed

  • tests:+278 added−0 removed
  • other:+110 added−13 removed

4 files+388 added−13 removed

modified:src/jsx/index.test.tsx+104 added
517 unmodified lines
518 it('should render variable without any name conversion', () => {519 const template = <h1 style={{ '--myVar': 1 }}>Hello</h1>520 expect(template.toString()).toBe('<h1 style="--myVar:1px">Hello</h1>')521 })522523 describe('CSS injection prevention', () => {524 it('should drop style values containing ";" to prevent CSS injection', () => {525 const userInput =526 'transparent;background:url(https://attacker.example/a.png);position:fixed;top:0'527 const template = <div style={{ color: userInput }} />528 const out = template.toString() as string529 expect(out).not.toContain('background:url')530 expect(out).not.toContain('position:fixed')531 expect(out).not.toContain('color:')532 expect(out).toBe('<div style=""></div>')533 })534535 it('should drop only the unsafe property and keep other safe properties', () => {536 const template = <div style={{ color: 'red;background:blue', backgroundColor: 'white' }} />537 const out = template.toString() as string538 expect(out).toBe('<div style="background-color:white"></div>')539 expect(out).not.toContain('background:blue')540 })541542 it('should drop style values that try to hide declaration separators in CSS comments', () => {543 const template = (544 <div545 style={{546 color: 'red/*(*/;background:blue;position:fixed;top:0',547 backgroundColor: 'white',548 }}549 />550 )551 const out = template.toString() as string552 expect(out).toBe('<div style="background-color:white"></div>')553 expect(out).not.toContain('position:fixed')554 })555556 it('should drop style values that try to expose declarations through CSS curly blocks', () => {557 const template = (558 <div559 style={{560 color: 'red{;background:blue}',561 backgroundColor: 'white',562 }}563 />564 )565 const out = template.toString() as string566 expect(out).toBe('<div style="background-color:white"></div>')567 expect(out).not.toContain('background:blue')568 })569570 it('should drop unterminated style values that can swallow following declarations', () => {571 const template = <div style={{ color: 'red/*', display: 'none' }} />572 const out = template.toString() as string573 expect(out).toBe('<div style="display:none"></div>')574 expect(out).not.toContain('color:')575 })576577 it('should drop style property names that can inject declarations', () => {578 const template = (579 <div580 style={{581 'color;background-image': 'url(https://attacker.example/a.png)',582 backgroundColor: 'white',583 }}584 />585 )586 const out = template.toString() as string587 expect(out).toBe('<div style="background-color:white"></div>')588 expect(out).not.toContain('background-image')589 })590591 it('should still HTML-escape safe style values', () => {592 const template = <h1 style={{ fontFamily: '"DejaVu Sans Mono", monospace' }}>Hello</h1>593 expect(template.toString()).toBe(594 '<h1 style="font-family:&quot;DejaVu Sans Mono&quot;, monospace">Hello</h1>'595 )596 })597598 it('should keep semicolons inside quoted style values', () => {599 const template = <h1 style={{ fontFamily: '"a;b", sans-serif' }}>Hello</h1>600 expect(template.toString()).toBe(601 '<h1 style="font-family:&quot;a;b&quot;, sans-serif">Hello</h1>'602 )603 })604605 it('should drop quoted style values that use newlines to expose declaration separators', () => {606 const template = (607 <div608 style={{609 fontFamily: '"\n;background:url(https://attacker.example/a.png)',610 backgroundColor: 'white',611 }}612 />613 )614 expect(template.toString()).toBe('<div style="background-color:white"></div>')615 })616617 it('should keep numeric style values working', () => {618 const template = <div style={{ fontSize: 10, lineHeight: 1.5 }} />619 expect(template.toString()).toBe('<div style="font-size:10px;line-height:1.5"></div>')620 })621622 it('should not throw when style values contain ";"', () => {623 expect(() => (<div style={{ color: 'red;evil:1' }} />).toString()).not.toThrow()624 })625 })626 })627628 describe('HtmlEscaped in props', () => {629 it('should not be double-escaped', () => {
722 unmodified lines
modified:src/jsx/jsx-runtime.test.tsx+28 added
modified:src/jsx/utils.test.ts+146 added
212 unmodified lines
213 '1px'214 )215 })216 })217218 describe('Should skip values containing ";" to prevent CSS injection', () => {219 it('skips a value with ";"', () => {220 const fn = vi.fn()221 styleObjectForEach({ color: 'red;background:blue' }, fn)222 expect(fn).not.toBeCalled()223 })224225 it('keeps safe siblings while skipping unsafe ones', () => {226 const fn = vi.fn()227 styleObjectForEach({ color: 'red;background:blue', backgroundColor: 'white' }, fn)228 expect(fn).toBeCalledTimes(1)229 expect(fn).toBeCalledWith('background-color', 'white')230 })231232 it('does not throw for unsafe values', () => {233 expect(() => styleObjectForEach({ color: 'a;b' }, () => {})).not.toThrow()234 })235236 it('keeps semicolons inside quoted strings', () => {237 const fn = vi.fn()238 styleObjectForEach({ fontFamily: '"a;b", sans-serif' }, fn)239 expect(fn).toBeCalledWith('font-family', '"a;b", sans-serif')240 })241242 test.each([243 ['LF', '\n'],244 ['CR', '\r'],245 ['FF', '\f'],246 ])('skips quoted strings that contain %s before a declaration separator', (_, newline) => {247 const fn = vi.fn()248 styleObjectForEach(249 { fontFamily: `"${newline};background:url(https://example.com/a.png)` },250 fn251 )252 expect(fn).not.toBeCalled()253 })254255 it('keeps semicolons inside CSS functions', () => {256 const fn = vi.fn()257 styleObjectForEach({ backgroundImage: 'url("data:image/svg+xml;utf8,<svg></svg>")' }, fn)258 expect(fn).toBeCalledWith('background-image', 'url("data:image/svg+xml;utf8,<svg></svg>")')259 })260261 test.each([['square brackets', 'red[;background:blue]']])(262 'keeps semicolons inside CSS simple blocks with %s',263 (_, value) => {264 const fn = vi.fn()265 styleObjectForEach({ color: value }, fn)266 expect(fn).toBeCalledWith('color', value)267 }268 )269270 test.each([271 ['opening curly block', 'red{;background:blue}'],272 ['closing curly block', 'red};background:blue'],273 ])('skips CSS values containing %s', (_, value) => {274 const fn = vi.fn()275 styleObjectForEach({ color: value, backgroundColor: 'white' }, fn)276 expect(fn).toBeCalledTimes(1)277 expect(fn).toBeCalledWith('background-color', 'white')278 })279280 test.each([281 ['square brackets', 'red[;background:blue];position:fixed'],282 ['curly braces', 'red{;background:blue};position:fixed'],283 ])('skips top-level semicolons after CSS simple blocks with %s', (_, value) => {284 const fn = vi.fn()285 styleObjectForEach({ color: value }, fn)286 expect(fn).not.toBeCalled()287 })288289 it('skips top-level semicolons after CSS comments', () => {290 const fn = vi.fn()291 styleObjectForEach({ color: 'red/*(*/;background:blue;position:fixed;top:0' }, fn)292 expect(fn).not.toBeCalled()293 })294295 test.each([296 ['comment', 'red/*'],297 ['double-quoted string', '"abc'],298 ['single-quoted string', "'abc"],299 ['function block', 'red('],300 ['square block', 'red['],301 ['curly block', 'red{'],302 ['unmatched function closer', 'red)'],303 ['unmatched square closer', 'red]'],304 ['unmatched curly closer', 'red}'],305 ['mismatched simple block closer', 'red[)'],306 ['escape', 'red\\'],307 ])('skips unterminated CSS %s that can swallow following declarations', (_, value) => {308 const fn = vi.fn()309 styleObjectForEach({ color: value, display: 'none' }, fn)310 expect(fn).toBeCalledTimes(1)311 expect(fn).toBeCalledWith('display', 'none')312 })313314 test.each([315 ['comment that closes exactly at end of value', 'red/* hi */'],316 ['CSS hex escape that decodes to a delimiter byte', 'red\\3b '],317 ['vertical tab inside a quoted string', '"\vfoo"'],318 ['trailing solidus that is not a comment start', 'a/'],319 ])('keeps CSS-safe edge case — %s', (_, value) => {320 const fn = vi.fn()321 styleObjectForEach({ color: value }, fn)322 expect(fn).toBeCalledWith('color', value)323 })324325 it('skips style property names that can break declaration boundaries', () => {326 const fn = vi.fn()327 styleObjectForEach({ 'color;background-image': 'url(https://example.com/a.png)' }, fn)328 styleObjectForEach({ 'color:background': 'red' }, fn)329 expect(fn).not.toBeCalled()330 })331332 it('keeps safe property names that use digits', () => {333 const fn = vi.fn()334 styleObjectForEach({ '--my-var-1': '15px', '--myVar-2': '20px' }, fn)335 expect(fn).toHaveBeenNthCalledWith(1, '--my-var-1', '15px')336 expect(fn).toHaveBeenNthCalledWith(2, '--myVar-2', '20px')337 })338339 it('keeps vendor-prefixed property names', () => {340 const fn = vi.fn()341 styleObjectForEach({ WebkitLineClamp: '2' }, fn)342 expect(fn).toBeCalledWith('-webkit-line-clamp', '2')343 })344345 it('keeps validating style property names after the valid style property name cache is reset', () => {346 for (let i = 0; i < 1025; i++) {347 styleObjectForEach({ [`--cache-${i}`]: '1px' }, () => {})348 }349350 const fn = vi.fn()351 styleObjectForEach({ '--after-reset-1': '2px', 'color:background': 'red' }, fn)352 expect(fn).toBeCalledTimes(1)353 expect(fn).toBeCalledWith('--after-reset-1', '2px')354 })355356 it('skips unsupported runtime values without throwing', () => {357 const fn = vi.fn()358 expect(() => styleObjectForEach({ color: false, backgroundColor: 'white' }, fn)).not.toThrow()359 expect(fn).toBeCalledTimes(1)360 expect(fn).toBeCalledWith('background-color', 'white')361 })362 })363})
modified:src/jsx/utils.ts+110 added-13 removed
78 unmodified lines
79 cacheValidName(validAttributeNameCache, validAttributeNameCacheMax, name)80 return true81}8283// eslint-disable-next-line no-control-regex84const invalidStylePropertyNameCharRe = /[\s"'():;\\/\[\]{}\x00-\x1f\x7f-\x9f]/85const validStylePropertyNameCache = new Set<string>()86const validStylePropertyNameCacheMax = 10248788const isValidStylePropertyName = (name: string): boolean => {89 if (validStylePropertyNameCache.has(name)) {90 return true91 }92 const len = name.length93 if (len === 0) {94 return false95 }96 for (let i = 0; i < len; i++) {97 const c = name.charCodeAt(i)98 if (99 !(100 (c >= 0x61 && c <= 0x7a) || // a-z101 (c >= 0x41 && c <= 0x5a) || // A-Z102 (c >= 0x30 && c <= 0x39) || // 0-9103 c === 0x2d || // -104 c === 0x5f // _105 )106 ) {107 // non-fast-path character found — fall back to regex for the full name108 if (!invalidStylePropertyNameCharRe.test(name)) {109 cacheValidName(validStylePropertyNameCache, validStylePropertyNameCacheMax, name)110 return true111 } else {112 return false113 }114 }115 }116 cacheValidName(validStylePropertyNameCache, validStylePropertyNameCacheMax, name)117 return true118}119120const unsafeStyleValueCharRe = /[;"'\\/\[\](){}]/121122const hasUnsafeStyleValue = (value: string): boolean => {123 if (!unsafeStyleValueCharRe.test(value)) {124 return false125 }126127 let quote = 0128 const blockStack: number[] = []129 for (let i = 0, len = value.length; i < len; i++) {130 const c = value.charCodeAt(i)131 if (c === 0x5c) {132 if (i === len - 1) {133 return true134 }135 i++136 } else if (quote !== 0) {137 if (c === 0x0a || c === 0x0c || c === 0x0d) {138 return true139 }140 if (c === quote) {141 quote = 0142 }143 } else if (c === 0x2f && value.charCodeAt(i + 1) === 0x2a) {144 const end = value.indexOf('*/', i + 2)145 if (end === -1) {146 return true147 }148 i = end + 1149 } else if (c === 0x22 || c === 0x27) {150 quote = c151 } else if (c === 0x28) {152 blockStack.push(0x29)153 } else if (c === 0x5b) {154 blockStack.push(0x5d)155 } else if (c === 0x7b || c === 0x7d) {156 return true157 } else if (c === 0x29 || c === 0x5d) {158 if (blockStack[blockStack.length - 1] !== c) {159 return true160 }161 blockStack.pop()162 } else if (c === 0x3b && blockStack.length === 0) {163 return true164 }165 }166 return quote !== 0 || blockStack.length !== 0167}168169export const styleObjectForEach = (84 style: Record<string, string | number>,170 style: Record<string, unknown>,171 fn: (key: string, value: string | null) => void172): void => {173 for (const [k, v] of Object.entries(style)) {174 const key =175 k[0] === '-' || !/[A-Z]/.test(k)176 ? k // a CSS variable or a lowercase only property177 : k.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`) // a camelCase property. convert to kebab-case92 fn(93 key,94 v == null95 ? null96 : typeof v === 'number'97 ? !key.match(98 /^(?:a|border-im|column(?:-c|s)|flex(?:$|-[^b])|grid-(?:ar|[^a])|font-w|li|or|sca|st|ta|wido|z)|ty$/99 )100 ? `${v}px`101 : `${v}`102 : v103 )178 if (!isValidStylePropertyName(key)) {179 continue180 }181 if (v == null) {182 fn(key, null)183 continue184 }185 let value: string186 if (typeof v === 'number') {187 value = !key.match(188 /^(?:a|border-im|column(?:-c|s)|flex(?:$|-[^b])|grid-(?:ar|[^a])|font-w|li|or|sca|st|ta|wido|z)|ty$/189 )190 ? `${v}px`191 : `${v}`192 } else if (typeof v === 'string') {193 if (hasUnsafeStyleValue(v)) {194 continue195 }196 value = v197 } else {198 continue199 }200 fn(key, value)201 }202}