feat(css): add CSP nonce to hono/css related style and script tags (#3685)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat(css): add CSP nonce to hono/css related style and script tags * test(helper/css): fix expected result * test(helper/css): add test for stream with nonce * fix(helper/css): Update regex to match nonce attribute * refactor(helper/css): `context` is read-only and must not be modified. * refactor(utils/html): declare context as readonly explicitly * perf(helper/css): use `has` instead of `get` ---------
authored by Moritz Eck · committed by GitHub · parent 3059741 · Browse files · 7 files·+121 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
7 files+121 added−13 removed
- tests:+96 added−1 removed
- other:+25 added−12 removed
Provenance
- Commit
bfc190f- Tree
3d0d83c- Author
Moritz Eck <moritz.eck@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
3059741
7 files changed+121 added−13 removed
modified:runtime-tests/deno-jsx/jsx.test.tsx+23 added
109 unmodified linesExpand all11011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914049 unmodified lines109 unmodified linesExpand all '<html><head><style id="hono-css">.css-3142110215{color:red}</style></head><body><div class="css-3142110215"></div></body></html>' )})
Deno.test('JSX: css with CSP nonce', async () => { const className = css` color: red; ` const html = ( <html> <head> <Style nonce='1234' /> </head> <body> <div class={className}></div> </body> </html> )
const awaitedHtml = await html const htmlEscapedString = 'callbacks' in awaitedHtml ? awaitedHtml : await awaitedHtml.toString() assertEquals( await resolveCallback(htmlEscapedString, HtmlEscapedCallbackPhase.Stringify, false, {}), '<html><head><style id="hono-css" nonce="1234">.css-3142110215{color:red}</style></head><body><div class="css-3142110215"></div></body></html>' )})
Deno.test('JSX: normalize key', async () => { const className = <div className='foo'></div> const htmlFor = <div htmlFor='foo'></div> const crossOrigin = <div crossOrigin='foo'></div>49 unmodified linesmodified:src/helper/css/common.case.test.tsx+15 added
486 unmodified lines487 expect(await toString(template)).toBe(488 '<style id="hono-css">.css-478287868{padding:0}</style><h1 class="css-478287868">Hello!</h1>'489 )490 })491+492+ it('Should render CSS styles with CSP nonce', async () => {493+ const headerClass = css`494+ background-color: blue;495+ `496+ const template = (497+ <>498+ <Style nonce='1234' />499+ <h1 class={headerClass}>Hello!</h1>500+ </>501+ )502+ expect(await toString(template)).toBe(503+ '<style id="hono-css" nonce="1234">.css-2458908649{background-color:blue}</style><h1 class="css-2458908649">Hello!</h1>'504+ )505+ })506 })507 })508 }modified:src/helper/css/index.test.tsx+46 added-1 removed
1 /** @jsxImportSource ../../jsx */2 import { Hono } from '../../'3 import { html } from '../../helper/html'4-import { isValidElement } from '../../jsx'4 import type { JSXNode } from '../../jsx'5+import { isValidElement } from '../../jsx'6 import { Suspense, renderToReadableStream } from '../../jsx/streaming'7 import type { HtmlEscapedString } from '../../utils/html'8 import { HtmlEscapedCallbackPhase, resolveCallback } from '../../utils/html'9 import { renderTest } from './common.case.test'47 unmodified lines57 `<style id="hono-css">.css-2458908649{background-color:blue}</style>58 <h1 class="css-2458908649">Hello!</h1>`59 )60 })61+62+ it('Should render CSS styles with `html` tag function and CSP nonce', async () => {63+ const headerClass = css`64+ background-color: blue;65+ `66+ const template = html`${Style({ nonce: '1234' })}67+ <h1 class="${headerClass}">Hello!</h1>`68+ expect(await toString(template)).toBe(69+ `<style id="hono-css" nonce="1234">.css-2458908649{background-color:blue}</style>70+ <h1 class="css-2458908649">Hello!</h1>`71+ )72+ })73 })74 75 describe('cx()', () => {76 it('Should render CSS with cx()', async () => {161 unmodified lines238 },239 })240 })241 242+ app.get('/stream-with-nonce', (c) => {243+ const stream = renderToReadableStream(244+ <>245+ <Style nonce='1234' />246+ <Suspense fallback={<p>Loading...</p>}>247+ <h1 class={headerClass}>Hello!</h1>248+ </Suspense>249+ </>250+ )251+ return c.body(stream, {252+ headers: {253+ 'Content-Type': 'text/html; charset=UTF-8',254+ 'Transfer-Encoding': 'chunked',255+ },256+ })257+ })258+259 it('/sync', async () => {260 const res = await app.request('http://localhost/sync')261 expect(res).not.toBeNull()262 expect(await res.text()).toBe(15 unmodified lines278 })(document)279 </script>`280 )281 })282+283+ it('/stream-with-nonce', async () => {284+ const res = await app.request('http://localhost/stream-with-nonce')285+ expect(res).not.toBeNull()286+ expect(await res.text()).toBe(287+ `<style id="hono-css" nonce="1234"></style><template id="H:1"></template><p>Loading...</p><!--/$--><script nonce="1234">document.querySelector('#hono-css').textContent+=".css-2458908649{background-color:blue}"</script><template data-hono-target="H:1"><h1 class="css-2458908649">Hello!</h1></template><script>288+((d,c,n) => {289+c=d.currentScript.previousSibling290+d=d.getElementById('H:1')291+if(!d)return292+do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')293+d.replaceWith(c.content)294+})(document)295+</script>`296+ )297+ })298 })299 })modified:src/helper/css/index.ts+22 added-10 removed
48 unmodified lines49 (): Promise<string>50 }51 52 interface StyleType {53- (args?: { children?: Promise<string> }): HtmlEscapedString53+ (args?: { children?: Promise<string>; nonce?: string }): HtmlEscapedString54 }55 56 /**57 * @experimental3 unmodified lines61 export const createCssContext = ({ id }: { id: Readonly<string> }): DefaultContextType => {62 const [cssJsxDomObject, StyleRenderToDom] = createCssJsxDomObjects({ id })63 64 const contextMap: WeakMap<object, usedClassNameData> = new WeakMap()65+ const nonceMap: WeakMap<object, string | undefined> = new WeakMap()66 66- const replaceStyleRe = new RegExp(`(<style id="${id}">.*?)(</style>)`)67+ const replaceStyleRe = new RegExp(`(<style id="${id}"(?: nonce="[^"]*")?>.*?)(</style>)`)68 69 const newCssClassNameObject = (cssClassName: CssClassNameCommon): Promise<string> => {70 const appendStyle: HtmlEscapedCallback = ({ buffer, context }): Promise<string> | undefined => {71 const [toAdd, added] = contextMap.get(context) as usedClassNameData16 unmodified lines88 buffer[0] = buffer[0].replace(replaceStyleRe, (_, pre, post) => `${pre}${stylesStr}${post}`)89 return90 }91 91- const appendStyleScript = `<script>document.querySelector('#${id}').textContent+=${JSON.stringify(92- stylesStr93- )}</script>`92+ const nonce = nonceMap.get(context)93+ const appendStyleScript = `<script${94+ nonce ? ` nonce="${nonce}"` : ''95+ }>document.querySelector('#${id}').textContent+=${JSON.stringify(stylesStr)}</script>`96+97 if (buffer) {98 buffer[0] = `${appendStyleScript}${buffer[0]}`99 return100 }1 unmodified line102 return Promise.resolve(appendStyleScript)103 }104 105 const addClassNameToContext: HtmlEscapedCallback = ({ context }) => {103- if (!contextMap.get(context)) {106+ if (!contextMap.has(context)) {107 contextMap.set(context, [{}, {}])108 }109 const [toAdd, added] = contextMap.get(context) as usedClassNameData110 let allAdded = true47 unmodified lines158 // eslint-disable-next-line @typescript-eslint/no-explicit-any159 return newCssClassNameObject(viewTransitionCommon(strings as any, values))160 }) as ViewTransitionType161 159- const Style: StyleType = ({ children } = {}) =>160- children161- ? raw(`<style id="${id}">${(children as unknown as CssClassName)[STYLE_STRING]}</style>`)162- : raw(`<style id="${id}"></style>`)162+ const Style: StyleType = ({ children, nonce } = {}) =>163+ raw(164+ `<style id="${id}"${nonce ? ` nonce="${nonce}"` : ''}>${165+ children ? (children as unknown as CssClassName)[STYLE_STRING] : ''166+ }</style>`,167+ [168+ ({ context }) => {169+ nonceMap.set(context, nonce)170+ return undefined171+ },172+ ]173+ )174+175 // eslint-disable-next-line @typescript-eslint/no-explicit-any176 ;(Style as any)[DOM_RENDERER] = StyleRenderToDom177 178 return {54 unmodified linesmodified:src/jsx/dom/css.test.tsx+12 added
50 unmodified lines51 '.css-3142110215 {color: red;}'52 )53 })54 55+ it('<Style nonce="1234" />', async () => {56+ const App = () => {57+ return (58+ <div>59+ <Style nonce='1234' />60+ </div>61+ )62+ }63+ render(<App />, root)64+ expect(root.innerHTML).toBe('<div><style id="hono-css" nonce="1234"></style></div>')65+ })66+67 it('<Style>{css`global`}</Style>', async () => {68 const App = () => {69 return (70 <div>52 unmodified linesmodified:src/jsx/dom/css.ts+2 added-1 removed
118 unmodified lines119 return this[CLASS_NAME]120 },121 }122 123- const Style: FC<PropsWithChildren<void>> = ({ children }) =>123+ const Style: FC<PropsWithChildren<{ nonce?: string }>> = ({ children, nonce }) =>124 ({125 tag: 'style',126 props: {127 id,128+ nonce,129 children:130 children &&131 (Array.isArray(children) ? children : [children]).map(132 (c) => (c as unknown as CssClassName)[STYLE_STRING]113 unmodified linesmodified:src/utils/html.ts+1 added-1 removed
9 unmodified lines10 } as const11 type HtmlEscapedCallbackOpts = {12 buffer?: [string]13 phase: (typeof HtmlEscapedCallbackPhase)[keyof typeof HtmlEscapedCallbackPhase]14- context: object // An object unique to each JSX tree. This object is used as the WeakMap key.14+ context: Readonly<object> // An object unique to each JSX tree. This object is used as the WeakMap key.15 }16 export type HtmlEscapedCallback = (opts: HtmlEscapedCallbackOpts) => Promise<string> | undefined17 export type HtmlEscaped = {18 isEscaped: true164 unmodified lines