Skip to content
Myr

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

7 files+121 added−13 removed

modified:runtime-tests/deno-jsx/jsx.test.tsx+23 added
modified:src/helper/css/common.case.test.tsx+15 added
486 unmodified lines
487 expect(await toString(template)).toBe(488 '<style id="hono-css">.css-478287868{padding:0}</style><h1 class="css-478287868">Hello!</h1>'489 )490 })491492 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 */2import { Hono } from '../../'3import { html } from '../../helper/html'4import { isValidElement } from '../../jsx'4import type { JSXNode } from '../../jsx'5import { isValidElement } from '../../jsx'6import { Suspense, renderToReadableStream } from '../../jsx/streaming'7import type { HtmlEscapedString } from '../../utils/html'8import { HtmlEscapedCallbackPhase, resolveCallback } from '../../utils/html'9import { renderTest } from './common.case.test'
47 unmodified lines
57 `<style id="hono-css">.css-2458908649{background-color:blue}</style>58 <h1 class="css-2458908649">Hello!</h1>`59 )60 })6162 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 })7475 describe('cx()', () => {76 it('Should render CSS with cx()', async () => {
161 unmodified lines
238 },239 })240 })241242 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 })258259 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 lines
278})(document)279</script>`280 )281 })282283 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) => {289c=d.currentScript.previousSibling290d=d.getElementById('H:1')291if(!d)return292do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')293d.replaceWith(c.content)294})(document)295</script>`296 )297 })298 })299})
modified:src/helper/css/index.ts+22 added-10 removed
48 unmodified lines
49 (): Promise<string>50}5152interface StyleType {53 (args?: { children?: Promise<string> }): HtmlEscapedString53 (args?: { children?: Promise<string>; nonce?: string }): HtmlEscapedString54}5556/**57 * @experimental
3 unmodified lines
61export const createCssContext = ({ id }: { id: Readonly<string> }): DefaultContextType => {62 const [cssJsxDomObject, StyleRenderToDom] = createCssJsxDomObjects({ id })6364 const contextMap: WeakMap<object, usedClassNameData> = new WeakMap()65 const nonceMap: WeakMap<object, string | undefined> = new WeakMap()6666 const replaceStyleRe = new RegExp(`(<style id="${id}">.*?)(</style>)`)67 const replaceStyleRe = new RegExp(`(<style id="${id}"(?: nonce="[^"]*")?>.*?)(</style>)`)6869 const newCssClassNameObject = (cssClassName: CssClassNameCommon): Promise<string> => {70 const appendStyle: HtmlEscapedCallback = ({ buffer, context }): Promise<string> | undefined => {71 const [toAdd, added] = contextMap.get(context) as usedClassNameData
16 unmodified lines
88 buffer[0] = buffer[0].replace(replaceStyleRe, (_, pre, post) => `${pre}${stylesStr}${post}`)89 return90 }9191 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>`9697 if (buffer) {98 buffer[0] = `${appendStyleScript}${buffer[0]}`99 return100 }
1 unmodified line
102 return Promise.resolve(appendStyleScript)103 }104105 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 = true
47 unmodified lines
158 // eslint-disable-next-line @typescript-eslint/no-explicit-any159 return newCssClassNameObject(viewTransitionCommon(strings as any, values))160 }) as ViewTransitionType161159 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 )174175 // eslint-disable-next-line @typescript-eslint/no-explicit-any176 ;(Style as any)[DOM_RENDERER] = StyleRenderToDom177178 return {
54 unmodified lines
modified:src/jsx/dom/css.test.tsx+12 added
50 unmodified lines
51 '.css-3142110215 {color: red;}'52 )53 })5455 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 })6667 it('<Style>{css`global`}</Style>', async () => {68 const App = () => {69 return (70 <div>
52 unmodified lines
modified:src/jsx/dom/css.ts+2 added-1 removed
118 unmodified lines
119 return this[CLASS_NAME]120 },121 }122123 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 lines
modified:src/utils/html.ts+1 added-1 removed
9 unmodified lines
10} as const11type 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}16export type HtmlEscapedCallback = (opts: HtmlEscapedCallbackOpts) => Promise<string> | undefined17export type HtmlEscaped = {18 isEscaped: true
164 unmodified lines