Merge commit from fork
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* fix: jsx tag name validation * perf: cache valid names to improve performance * fix: reject parser-control tag name prefixes Reject tag names starting with `!` or `?` (e.g. `!--`, `!DOCTYPE`, `?xml`) so programmatic JSX input can't emit HTML comment / doctype / processing-instruction openers that break parser context downstream.
authored by Taku Amano · committed by GitHub · parent 027e3df · Browse files · 4 files·+180 added−15 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+180 added−15 removed
- tests:+128 added−13 removed
- other:+52 added−2 removed
Provenance
- Commit
614b834- Tree
8b5ab54- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
027e3df
4 files changed+180 added−15 removed
modified:src/jsx/base.ts+9 added-1 removed
8 unmodified lines9 import type {10 JSX as HonoJSX,11 IntrinsicElements as IntrinsicElementsDefined,12 } from './intrinsic-elements'13-import { isValidAttributeName, normalizeIntrinsicElementKey, styleObjectForEach } from './utils'13+import {14+ isValidAttributeName,15+ isValidTagName,16+ normalizeIntrinsicElementKey,17+ styleObjectForEach,18+} from './utils'19 20 // eslint-disable-next-line @typescript-eslint/no-explicit-any21 export type Props = Record<string, any>22 export type FC<P = Props> = {116 unmodified lines139 children: Child[]140 isEscaped: true = true as const141 localContexts?: LocalContexts142 constructor(tag: string | Function, props: Props, children: Child[]) {143+ if (typeof tag !== 'function' && !isValidTagName(tag)) {144+ throw new Error(`Invalid JSX tag name: ${tag}`)145+ }146 this.tag = tag147 this.props = props148 this.children = children149 }304 unmodified linesmodified:src/jsx/index.test.tsx+52 added-1 removed
1 unmodified line2 /* eslint-disable @typescript-eslint/no-explicit-any */3 import { html } from '../helper/html'4 import { Hono } from '../hono'5 import { Suspense, renderToReadableStream } from './streaming'6-import DefaultExport, { Fragment, StrictMode, createContext, memo, useContext, version } from '.'6+import DefaultExport, {7+ Fragment,8+ StrictMode,9+ createContext,10+ createElement,11+ jsx,12+ memo,13+ useContext,14+ version,15+} from '.'16 import type { Context, FC, PropsWithChildren } from '.'17 18 interface SiteData {19 title: string158 unmodified lines178 const template = <link>https://example.com</link>179 expect(template.toString()).toBe('<link>https://example.com</link>')180 })181 182+ describe('programmatic tag names', () => {183+ it('Should throw when jsx() receives a tag name that can break out of the HTML context', () => {184+ const payloads = [185+ '><script>alert(1)</script><x',186+ 'div onmouseover="alert(1)" x=',187+ 'div></div><img src=x onerror=alert(1)><div',188+ '!--',189+ '!DOCTYPE',190+ '?xml',191+ ]192+193+ for (const tag of payloads) {194+ expect(() => jsx(tag, {}, 'hello')).toThrow(`Invalid JSX tag name: ${tag}`)195+ }196+ })197+198+ it('Should throw when createElement() receives a tag name that can break out of the HTML context', () => {199+ expect(() => createElement('div onmouseover="alert(1)" x=', {}, 'hello')).toThrow(200+ 'Invalid JSX tag name: div onmouseover="alert(1)" x='201+ )202+ })203+204+ it('Should throw when jsx() receives an invalid non-primitive tag name', () => {205+ expect(() => jsx(new String('div') as never, {}, 'hello')).toThrow(206+ 'Invalid JSX tag name: div'207+ )208+ expect(() =>209+ jsx({ toString: () => 'div onmouseover="alert(1)" x=' } as never, {}, 'hello')210+ ).toThrow('Invalid JSX tag name: div onmouseover="alert(1)" x=')211+ })212+213+ it('Should allow compatible custom and namespaced tag names', () => {214+ expect(jsx('custom-element', {}, 'hello').toString()).toBe(215+ '<custom-element>hello</custom-element>'216+ )217+ expect(jsx('foo:bar', {}, 'hello').toString()).toBe('<foo:bar>hello</foo:bar>')218+ expect(jsx('x.foo', {}, 'hello').toString()).toBe('<x.foo>hello</x.foo>')219+ expect(jsx('x_bar', {}, 'hello').toString()).toBe('<x_bar>hello</x_bar>')220+ expect(jsx('é', {}, 'hello').toString()).toBe('<é>hello</é>')221+ })222+ })223+224 it('Props value is null', () => {225 const template = <span data-hello={null}>Hello</span>226 expect(template.toString()).toBe('<span>Hello</span>')227 })1013 unmodified linesmodified:src/jsx/utils.test.ts+76 added-12 removed
11234567891012 unmodified lines23242526222324252627282930313227282930313233343536373839404122 unmodified lines64656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113285 unmodified linesimport { isValidAttributeName, normalizeIntrinsicElementKey, styleObjectForEach } from './utils'import { isValidAttributeName, isValidTagName, normalizeIntrinsicElementKey, styleObjectForEach,} from './utils'
describe('normalizeIntrinsicElementKey', () => { test.each` key | expected12 unmodified lines})
describe('isValidAttributeName', () => { test.each` name | expected ${'class'} | ${true} ${'id'} | ${true} ${'href'} | ${true} ${'data-foo'} | ${true} ${'aria-label'} | ${true} ${'onclick'} | ${true} ${'viewBox'} | ${true} ${'xml:lang'} | ${true} `('should return $expected for valid name "$name"', ({ name, expected }) => { expect(isValidAttributeName(name)).toBe(expected) name ${'class'} ${'id'} ${'href'} ${'data-foo'} ${'aria-label'} ${'onclick'} ${'viewBox'} ${'xml:lang'} `('should return true for valid name "$name"', ({ name }) => { expect(isValidAttributeName(name)).toBe(true) })
test.each` name | description22 unmodified lines ${'é'} | ${'non-ascii'} `('should return true for valid "$description" names', ({ name }) => { expect(isValidAttributeName(name)).toBe(true) })
it('should keep validating names after the valid attribute name cache is reset', () => { for (let i = 0; i < 1025; i++) { expect(isValidAttributeName(`data-k${i}`)).toBe(true) }
expect(isValidAttributeName('class')).toBe(true) expect(isValidAttributeName('" onfocus="alert(1)')).toBe(false) })})
describe('isValidTagName', () => { test.each` name ${''} ${'div'} ${'h1'} ${'custom-element'} ${'clipPath'} ${'foo:bar'} ${'x.foo'} ${'x_bar'} ${'é'} `('should return true for valid tag name "$name"', ({ name }) => { expect(isValidTagName(name)).toBe(true) })
test.each` name | description ${'foo bar'} | ${'space'} ${'foo\nbar'} | ${'newline'} ${'" onfocus="alert(1)'} | ${'double quote'} ${"' onfocus='alert(1)"} | ${'single quote'} ${'foo<bar'} | ${'less than'} ${'"><script>alert(1)</script>'} | ${'greater than'} ${'foo=bar'} | ${'equals sign'} ${'foo/bar'} | ${'slash'} ${'foo\\bar'} | ${'backslash'} ${'foo`bar'} | ${'backtick'} ${'a\x00b'} | ${'null byte'} ${'a\x1fb'} | ${'control character'} ${'a\x7fb'} | ${'DEL character'} ${'!'} | ${'single bang'} ${'!--'} | ${'parser-control bang prefix'} ${'!DOCTYPE'} | ${'doctype-like name'} ${'?'} | ${'single question mark'} ${'?xml'} | ${'processing instruction'} `('should return false for "$description"', ({ name }) => { expect(isValidTagName(name)).toBe(false) })
it('should keep validating names after the valid tag name cache is reset', () => { for (let i = 0; i < 257; i++) { expect(isValidTagName(`custom-${i}`)).toBe(true) }
expect(isValidTagName('div')).toBe(true) expect(isValidTagName('div onmouseover="alert(1)"')).toBe(false) })})
describe('styleObjectForEach', () => { describe('Should output the number as it is, when a number type is passed', () => { test.each` property85 unmodified linesmodified:src/jsx/utils.ts+43 added-1 removed
11 unmodified lines12 normalizeElementKeyMap.get(key) || key13 14 // eslint-disable-next-line no-control-regex15 const invalidAttributeNameCharRe = /[\s"'<>/=`\\\x00-\x1f\x7f-\x9f]/16+const validAttributeNameCache = new Set<string>()17+const validAttributeNameCacheMax = 102418+// reject HTML parser-control tag starters ('!' for comments/doctype, '?' for19+// processing instructions) in addition to the shared invalid-char set20+// eslint-disable-next-line no-control-regex21+const invalidTagNameCharRe = /^[!?]|[\s"'<>/=`\\\x00-\x1f\x7f-\x9f]/22+const validTagNameCache = new Set<unknown>()23+const validTagNameCacheMax = 25624+25+const cacheValidName = (cache: Set<unknown>, max: number, name: string): void => {26+ if (cache.size >= max) {27+ cache.clear()28+ }29+ cache.add(name)30+}31+32+export const isValidTagName = (name: unknown): name is string => {33+ if (validTagNameCache.has(name)) {34+ return true35+ }36+ if (typeof name !== 'string') {37+ return false38+ }39+ if (name.length === 0) {40+ return true41+ }42+ if (invalidTagNameCharRe.test(name)) {43+ return false44+ }45+ cacheValidName(validTagNameCache, validTagNameCacheMax, name)46+ return true47+}48+49 export const isValidAttributeName = (name: string): boolean => {50+ if (validAttributeNameCache.has(name)) {51+ return true52+ }53 const len = name.length54 if (len === 0) {55 return false56 }10 unmodified lines67 c === 0x3a // :68 )69 ) {70 // non-fast-path character found — fall back to regex for the full name35- return !invalidAttributeNameCharRe.test(name)71+ if (!invalidAttributeNameCharRe.test(name)) {72+ cacheValidName(validAttributeNameCache, validAttributeNameCacheMax, name)73+ return true74+ } else {75+ return false76+ }77 }78 }79+ cacheValidName(validAttributeNameCache, validAttributeNameCacheMax, name)80 return true81 }82 83 export const styleObjectForEach = (22 unmodified lines