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
Provenance
- Commit
66daa2e- Tree
ce65977- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
fa2c74f
8 files changed+287 added−12 removed
modified:src/jsx/dom/index.test.tsx+76 added
94 unmodified lines95 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 })102 103 it('simple App', () => {90 unmodified lines194 render(<App />, root)195 expect(root.innerHTML).toBe('<div x-value="value"></div>')196 })197 198+ it('ignores invalid attribute keys without interrupting updates', async () => {199+ const invalidKey = '" onfocus="alert(1)'200+201+ 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+ }211+212+ render(<App />, root)213+ expect(root.innerHTML).toBe('<div id="safe">Hello</div>')214+215+ root.querySelector('div')?.click()216+ await Promise.resolve()217+218+ expect(root.innerHTML).toBe('<div class="updated">Hello</div>')219+ })220+221+ 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+ })232+233+ try {234+ expect(() => render(<div data-boom='x'>Hello</div>, root)).toThrow(error)235+ } finally {236+ setAttributeSpy.mockRestore()237+ }238+ })239+240+ it('rethrows unexpected errors while removing attributes', () => {241+ render(<div data-boom='x'>Hello</div>, root)242+243+ 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+ })253+254+ try {255+ expect(() => render(<div data-boom={undefined}>Hello</div>, root)).toThrow(error)256+ } finally {257+ removeAttributeSpy.mockRestore()258+ }259+ })260+261 it('ref', () => {262 const App = () => {263 const ref = useRef<HTMLDivElement>(null)264 return <div ref={ref} />2380 unmodified lines2645 expect(document.querySelector('title')).toBeInstanceOf(dom.window.HTMLTitleElement)2646 expect(document.querySelector('svg title')).toBeInstanceOf(dom.window.SVGTitleElement)2647 })2648 2649+ 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+ })2660+2661 describe('attribute', () => {2662 describe('camelCase', () => {2663 test.each`2664 key235 unmodified linesmodified:src/jsx/dom/render.ts+27 added-9 removed
153 unmodified lines154 select.selectedIndex = 0155 }156 }157 158+// 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.161+const isIgnorableAttributeError = (error: unknown): boolean =>162+ error instanceof DOMException && error.name === 'InvalidCharacterError'163+164 const applyProps = (165 container: SupportedElement,166 attributes: Props,167 oldAttributes?: Props60 unmodified lines228 }229 230 const k = toAttributeName(container, key)231 232+ 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 lines257 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 linesmodified:src/jsx/base.ts+4 added-1 removed
8 unmodified lines9 import type {10 JSX as HonoJSX,11 IntrinsicElements as IntrinsicElementsDefined,12 } from './intrinsic-elements'13-import { normalizeIntrinsicElementKey, styleObjectForEach } from './utils'13+import { isValidAttributeName, normalizeIntrinsicElementKey, styleObjectForEach } from './utils'14 15 // eslint-disable-next-line @typescript-eslint/no-explicit-any16 export type Props = Record<string, any>17 export type FC<P = Props> = {163 unmodified lines181 ? (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 strings254 unmodified linesmodified:src/jsx/index.test.tsx+79 added
476 unmodified lines477 expect(template.toString()).toBe('<span data-text="<html-escaped-string>">Hello</span>')478 })479 })480 481+ 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+ })487+488+ 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+ })493+494+ 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+ })499+500+ 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+ })505+506+ 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+ })511+512+ 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+ })517+518+ 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+ })527+528+ 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+ })532+533+ 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+ })537+538+ 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+ })544+545+ 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+ })550+551 describe('head', () => {552 it('Simple head elements should be rendered as is', () => {553 const template = (554 <head>181 unmodified lines736 '<head><title>Document Title</title></head><svg><title>SVG Title</title></svg>'737 )738 })739 740+ 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+ })748+749 describe('attribute', () => {750 describe('camelCase', () => {751 test.each`752 key437 unmodified linesmodified:src/jsx/jsx-runtime.test.tsx+24 added
1234567810 unmodified lines192021222324252627282930313233343536373839404142434445464748498 unmodified lines/** @jsxRuntime automatic **//** @jsxImportSource . **/import { Hono } from '../hono'import { jsxAttr } from './jsx-runtime'
describe('jsx-runtime', () => { let app: Hono
10 unmodified lines expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8') expect(await res.text()).toBe('<h1>Hello</h1>') })
it('Should skip invalid attribute keys in jsxAttr()', () => { expect(String(jsxAttr('" onfocus="alert(1)', 'x'))).toBe('') expect(String(jsxAttr('foo<bar', 'x'))).toBe('') expect(String(jsxAttr('foo\\bar', 'x'))).toBe('') expect(String(jsxAttr('foo`bar', 'x'))).toBe('') })
it('Should skip invalid non-string attribute values in jsxAttr()', async () => { const invalidKey = '" onfocus="alert(1)'
expect(String(jsxAttr(invalidKey, { fontSize: 10 }))).toBe('') expect(String(await jsxAttr(invalidKey, Promise.resolve('/docs?q=1&lang=en')))).toBe('') })
it('Should render valid attribute values in jsxAttr()', async () => { expect(String(jsxAttr('style', { fontSize: 10, color: 'red' }))).toBe( 'style="font-size:10px;color:red"' ) expect(String(await jsxAttr('href', Promise.resolve('/docs?q=1&lang=en')))).toBe( 'href="/docs?q=1&lang=en"' ) })
// https://en.reactjs.org/docs/jsx-in-depth.html#booleans-null-and-undefined-are-ignored describe('Booleans, Null, and Undefined Are Ignored', () => { it.each([true, false, undefined, null])('%s', (item) => { expect((<span>{item}</span>).toString()).toBe('<span></span>')8 unmodified linesmodified:src/jsx/jsx-runtime.ts+4 added-1 removed
7 unmodified lines8910111212131415161718192021222324252625 unmodified lines7 unmodified linesexport type { JSX } from './jsx-dev-runtime'import { html, raw } from '../helper/html'import type { HtmlEscapedString, StringBuffer, HtmlEscaped } from '../utils/html'import { escapeToBuffer, stringBufferToString } from '../utils/html'import { styleObjectForEach } from './utils'import { isValidAttributeName, styleObjectForEach } from './utils'
export { html as jsxTemplate }
export const jsxAttr = ( key: string, v: string | Promise<string> | Record<string, string | number | null | undefined | boolean>): HtmlEscapedString | Promise<HtmlEscapedString> => { if (!isValidAttributeName(key)) { return raw('') } const buffer: StringBuffer = [`${key}="`] as StringBuffer if (key === 'style' && typeof v === 'object') { // object to style strings let styleStr = ''25 unmodified linesmodified:src/jsx/utils.test.ts+46 added-1 removed
1-import { normalizeIntrinsicElementKey, styleObjectForEach } from './utils'1+import { isValidAttributeName, normalizeIntrinsicElementKey, styleObjectForEach } from './utils'2 3 describe('normalizeIntrinsicElementKey', () => {4 test.each`5 key | expected10 unmodified lines16 expect(normalizeIntrinsicElementKey(key)).toBe(expected)17 })18 })19 20+describe('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+ })34+35+ 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+ })53+54+ 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+})64+65 describe('styleObjectForEach', () => {66 describe('Should output the number as it is, when a number type is passed', () => {67 test.each`68 property85 unmodified linesmodified:src/jsx/utils.ts+27 added
9 unmodified lines101112131415161718192021222324252627282930313233343536373839404142434419 unmodified lines9 unmodified lines])export const normalizeIntrinsicElementKey = (key: string): string => normalizeElementKeyMap.get(key) || key
// eslint-disable-next-line no-control-regexconst invalidAttributeNameCharRe = /[\s"'<>/=`\\\x00-\x1f\x7f-\x9f]/export const isValidAttributeName = (name: string): boolean => { const len = name.length if (len === 0) { return false } for (let i = 0; i < len; i++) { const c = name.charCodeAt(i) if ( !( (c >= 0x61 && c <= 0x7a) || // a-z (c >= 0x41 && c <= 0x5a) || // A-Z (c >= 0x30 && c <= 0x39) || // 0-9 c === 0x2d || // - c === 0x5f || // _ c === 0x2e || // . c === 0x3a // : ) ) { // non-fast-path character found — fall back to regex for the full name return !invalidAttributeNameCharRe.test(name) } } return true}
export const styleObjectForEach = ( style: Record<string, string | number>, fn: (key: string, value: string | null) => void): void => {19 unmodified lines