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): validate attribute names to prevent XSS via key injection * fix(jsx/dom): handle invalid attribute names in DOM renderer

authored by Taku Amano · committed by GitHub · parent fa2c74f · Browse files · 8 files+287 added−12 removed
This commit

State

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

Diff stats

8 files+287 added−12 removed

  • tests:+225 added−1 removed
  • other:+62 added−11 removed

8 files+287 added−12 removed

modified:src/jsx/dom/index.test.tsx+76 added
94 unmodified lines
95 global.document = dom.window.document96 global.HTMLElement = dom.window.HTMLElement97 global.SVGElement = dom.window.SVGElement98 global.Text = dom.window.Text99 global.DOMException = dom.window.DOMException100 root = document.getElementById('root') as HTMLElement101 })102103 it('simple App', () => {
90 unmodified lines
194 render(<App />, root)195 expect(root.innerHTML).toBe('<div x-value="value"></div>')196 })197198 it('ignores invalid attribute keys without interrupting updates', async () => {199 const invalidKey = '" onfocus="alert(1)'200201 const App = () => {202 const [includeInvalid, setIncludeInvalid] = useState(true)203 return includeInvalid ? (204 <div id='safe' {...{ [invalidKey]: 'x' }} onClick={() => setIncludeInvalid(false)}>205 Hello206 </div>207 ) : (208 <div class='updated'>Hello</div>209 )210 }211212 render(<App />, root)213 expect(root.innerHTML).toBe('<div id="safe">Hello</div>')214215 root.querySelector('div')?.click()216 await Promise.resolve()217218 expect(root.innerHTML).toBe('<div class="updated">Hello</div>')219 })220221 it('rethrows unexpected errors while setting attributes', () => {222 const error = new Error('boom')223 const originalSetAttribute = dom.window.Element.prototype.setAttribute224 const setAttributeSpy = vi225 .spyOn(dom.window.Element.prototype, 'setAttribute')226 .mockImplementation(function (this: Element, key: string, value: string) {227 if (key === 'data-boom') {228 throw error229 }230 return originalSetAttribute.call(this, key, value)231 })232233 try {234 expect(() => render(<div data-boom='x'>Hello</div>, root)).toThrow(error)235 } finally {236 setAttributeSpy.mockRestore()237 }238 })239240 it('rethrows unexpected errors while removing attributes', () => {241 render(<div data-boom='x'>Hello</div>, root)242243 const error = new Error('boom')244 const originalRemoveAttribute = dom.window.Element.prototype.removeAttribute245 const removeAttributeSpy = vi246 .spyOn(dom.window.Element.prototype, 'removeAttribute')247 .mockImplementation(function (this: Element, key: string) {248 if (key === 'data-boom') {249 throw error250 }251 return originalRemoveAttribute.call(this, key)252 })253254 try {255 expect(() => render(<div data-boom={undefined}>Hello</div>, root)).toThrow(error)256 } finally {257 removeAttributeSpy.mockRestore()258 }259 })260261 it('ref', () => {262 const App = () => {263 const ref = useRef<HTMLDivElement>(null)264 return <div ref={ref} />
2380 unmodified lines
2645 expect(document.querySelector('title')).toBeInstanceOf(dom.window.HTMLTitleElement)2646 expect(document.querySelector('svg title')).toBeInstanceOf(dom.window.SVGTitleElement)2647 })26482649 it('skips invalid attribute keys in SVG while preserving valid ones', () => {2650 const App = () => {2651 return (2652 <svg>2653 <g {...{ ['" onload="alert(1)']: 'x', viewBox: '0 0 10 10' }} />2654 </svg>2655 )2656 }2657 render(<App />, root)2658 expect(root.innerHTML).toBe('<svg><g viewBox="0 0 10 10"></g></svg>')2659 })26602661 describe('attribute', () => {2662 describe('camelCase', () => {2663 test.each`2664 key
235 unmodified lines
modified:src/jsx/dom/render.ts+27 added-9 removed
153 unmodified lines
154 select.selectedIndex = 0155 }156}157158// Unlike SSR (which uses isValidAttributeName for upfront validation),159// the DOM renderer relies on try/catch for performance—invalid attribute160// names are rare at runtime, so avoiding the per-attribute regex check is faster.161const isIgnorableAttributeError = (error: unknown): boolean =>162 error instanceof DOMException && error.name === 'InvalidCharacterError'163164const applyProps = (165 container: SupportedElement,166 attributes: Props,167 oldAttributes?: Props
60 unmodified lines
228 }229230 const k = toAttributeName(container, key)231232 try {226 if (value === null || value === undefined || value === false) {227 container.removeAttribute(k)228 } else if (value === true) {229 container.setAttribute(k, '')230 } else if (typeof value === 'string' || typeof value === 'number') {231 container.setAttribute(k, value as string)232 } else {233 container.setAttribute(k, value.toString())233 if (value === null || value === undefined || value === false) {234 container.removeAttribute(k)235 } else if (value === true) {236 container.setAttribute(k, '')237 } else if (typeof value === 'string' || typeof value === 'number') {238 container.setAttribute(k, value as string)239 } else {240 container.setAttribute(k, value.toString())241 }242 } catch (e) {243 if (!isIgnorableAttributeError(e)) {244 throw e245 }246 }247 }248 }249 }
7 unmodified lines
257 container.removeEventListener(eventSpec[0], value, eventSpec[1])258 } else if (key === 'ref') {259 refCleanupMap.get(container)?.()260 } else {261 try {249 container.removeAttribute(toAttributeName(container, key))262 container.removeAttribute(toAttributeName(container, key))263 } catch (e) {264 if (!isIgnorableAttributeError(e)) {265 throw e266 }267 }268 }269 }270 }271 }
554 unmodified lines
modified:src/jsx/base.ts+4 added-1 removed
8 unmodified lines
9import type {10 JSX as HonoJSX,11 IntrinsicElements as IntrinsicElementsDefined,12} from './intrinsic-elements'13import { normalizeIntrinsicElementKey, styleObjectForEach } from './utils'13import { isValidAttributeName, normalizeIntrinsicElementKey, styleObjectForEach } from './utils'1415// eslint-disable-next-line @typescript-eslint/no-explicit-any16export type Props = Record<string, any>17export type FC<P = Props> = {
163 unmodified lines
181 ? (key) => toSVGAttributeName(normalizeIntrinsicElementKey(key))182 : (key) => normalizeIntrinsicElementKey(key)183 for (let [key, v] of Object.entries(props)) {184 key = normalizeKey(key)185 if (!isValidAttributeName(key)) {186 continue187 }188 if (key === 'children') {189 // skip children190 } else if (key === 'style' && typeof v === 'object') {191 // object to style strings
254 unmodified lines
modified:src/jsx/index.test.tsx+79 added
476 unmodified lines
477 expect(template.toString()).toBe('<span data-text="&lt;html-escaped-string&gt;">Hello</span>')478 })479 })480481 describe('XSS prevention for attribute keys', () => {482 it('Should skip attribute keys containing double quotes', () => {483 const props: Record<string, string> = { ['" onfocus="alert(1)']: 'x' }484 const template = <div {...props}>Hello</div>485 expect(template.toString()).toBe('<div>Hello</div>')486 })487488 it('Should skip attribute keys containing >', () => {489 const props: Record<string, string> = { ['"><script>alert(1)</script><x x="']: 'x' }490 const template = <div {...props}>Hello</div>491 expect(template.toString()).toBe('<div>Hello</div>')492 })493494 it('Should skip attribute keys containing <', () => {495 const props: Record<string, string> = { ['foo<bar']: 'x' }496 const template = <div {...props}>Hello</div>497 expect(template.toString()).toBe('<div>Hello</div>')498 })499500 it('Should skip attribute keys containing backslashes', () => {501 const props: Record<string, string> = { ['foo\\bar']: 'x' }502 const template = <div {...props}>Hello</div>503 expect(template.toString()).toBe('<div>Hello</div>')504 })505506 it('Should skip attribute keys containing backticks', () => {507 const props: Record<string, string> = { ['foo`bar']: 'x' }508 const template = <div {...props}>Hello</div>509 expect(template.toString()).toBe('<div>Hello</div>')510 })511512 it('Should skip attribute keys containing spaces', () => {513 const props: Record<string, string> = { ['foo bar']: 'x' }514 const template = <div {...props}>Hello</div>515 expect(template.toString()).toBe('<div>Hello</div>')516 })517518 it('Should still render valid attributes alongside invalid ones', () => {519 const props: Record<string, string> = {520 id: 'safe',521 ['" onfocus="alert(1)']: 'x',522 class: 'test',523 }524 const template = <div {...props}>Hello</div>525 expect(template.toString()).toBe('<div id="safe" class="test">Hello</div>')526 })527528 it('Should skip invalid attribute keys before style serialization', () => {529 const template = <div {...{ ['" onfocus="alert(1)']: { fontSize: 10 } }}>Hello</div>530 expect(template.toString()).toBe('<div>Hello</div>')531 })532533 it('Should skip invalid attribute keys before function prop validation', () => {534 const template = <div {...{ ['" onfocus="alert(1)']: () => 'x' }}>Hello</div>535 expect(template.toString()).toBe('<div>Hello</div>')536 })537538 it('Should skip invalid attribute keys before dangerouslySetInnerHTML handling', () => {539 const template = (540 <div {...{ ['" onfocus="alert(1)']: { __html: '<strong>Injected</strong>' } }}>Hello</div>541 )542 expect(template.toString()).toBe('<div>Hello</div>')543 })544545 it('Should skip invalid attribute keys with Promise values', async () => {546 const template = <div {...{ ['" onfocus="alert(1)']: Promise.resolve('x') }}>Hello</div>547 expect(await template.toString()).toBe('<div>Hello</div>')548 })549 })550551 describe('head', () => {552 it('Simple head elements should be rendered as is', () => {553 const template = (554 <head>
181 unmodified lines
736 '<head><title>Document Title</title></head><svg><title>SVG Title</title></svg>'737 )738 })739740 it('should skip invalid attribute keys in SVG while preserving valid ones', () => {741 const template = (742 <svg>743 <g {...{ ['" onload="alert(1)']: 'x', viewBox: '0 0 10 10' }} />744 </svg>745 )746 expect(template.toString()).toBe('<svg><g viewBox="0 0 10 10"></g></svg>')747 })748749 describe('attribute', () => {750 describe('camelCase', () => {751 test.each`752 key
437 unmodified lines
modified:src/jsx/jsx-runtime.test.tsx+24 added
modified:src/jsx/jsx-runtime.ts+4 added-1 removed
modified:src/jsx/utils.test.ts+46 added-1 removed
1import { normalizeIntrinsicElementKey, styleObjectForEach } from './utils'1import { isValidAttributeName, normalizeIntrinsicElementKey, styleObjectForEach } from './utils'23describe('normalizeIntrinsicElementKey', () => {4 test.each`5 key | expected
10 unmodified lines
16 expect(normalizeIntrinsicElementKey(key)).toBe(expected)17 })18})1920describe('isValidAttributeName', () => {21 test.each`22 name | expected23 ${'class'} | ${true}24 ${'id'} | ${true}25 ${'href'} | ${true}26 ${'data-foo'} | ${true}27 ${'aria-label'} | ${true}28 ${'onclick'} | ${true}29 ${'viewBox'} | ${true}30 ${'xml:lang'} | ${true}31 `('should return $expected for valid name "$name"', ({ name, expected }) => {32 expect(isValidAttributeName(name)).toBe(expected)33 })3435 test.each`36 name | description37 ${''} | ${'empty string'}38 ${'" onfocus="alert(1)'} | ${'double quote'}39 ${"' onfocus='alert(1)"} | ${'single quote'}40 ${'foo<bar'} | ${'less than'}41 ${'"><script>alert(1)</script>'} | ${'greater than'}42 ${'foo bar'} | ${'space'}43 ${'foo=bar'} | ${'equals sign'}44 ${'foo/bar'} | ${'slash'}45 ${'foo\\bar'} | ${'backslash'}46 ${'foo`bar'} | ${'backtick'}47 ${'a\x00b'} | ${'null byte'}48 ${'a\x1fb'} | ${'control character'}49 ${'a\x7fb'} | ${'DEL character'}50 `('should return false for "$description"', ({ name }) => {51 expect(isValidAttributeName(name)).toBe(false)52 })5354 test.each`55 name | description56 ${'xlink:href'} | ${'namespace separator'}57 ${'data.foo'} | ${'dot'}58 ${'data_foo'} | ${'underscore'}59 ${'é'} | ${'non-ascii'}60 `('should return true for valid "$description" names', ({ name }) => {61 expect(isValidAttributeName(name)).toBe(true)62 })63})6465describe('styleObjectForEach', () => {66 describe('Should output the number as it is, when a number type is passed', () => {67 test.each`68 property
85 unmodified lines
modified:src/jsx/utils.ts+27 added