|
| 1 | +import { WebView } from 'bun' |
| 2 | +import { expect, test } from 'bun:test' |
| 3 | +import { createHash } from 'node:crypto' |
| 4 | +import { rm } from 'node:fs/promises' |
| 5 | +import { join, relative, sep } from 'node:path' |
| 6 | +import { buildComponentLibrary } from '../../src/component-library' |
| 7 | +import { createTempDir } from '../../src/temp-dir' |
| 8 | +import { createBrowserFixture } from '../../test-utils/browser-fixture' |
| 9 | + |
| 10 | +test('build-result style hashes authorize exact client and SSR styles under a browser hash-only CSP', async () => { |
| 11 | + const root = createTempDir('stx-library-style-csp-') |
| 12 | + let fixture: ReturnType<typeof createBrowserFixture> | undefined |
| 13 | + try { |
| 14 | + const input = join(root, 'source'), output = join(root, 'dist') |
| 15 | + await Bun.write(join(input, 'browser-leaf.ts'), 'export const title = document.documentElement.tagName') |
| 16 | + await Bun.write(join(input, 'browser.ts'), "export { title } from './browser-leaf'") |
| 17 | + const modes = [false, 'open', 'closed'] as const |
| 18 | + for (const [index, mode] of modes.entries()) { |
| 19 | + const source = `<script component type="application/json">${JSON.stringify({ tag: `csp-card-${index}`, shadowDOM: mode, properties: { count: { type: 'number', default: 0 } } })}</script> |
| 20 | +<script>import { title as browserTitle } from './browser' |
| 21 | +const title = browserTitle</script> |
| 22 | +<template><p>{{ title }} {{ count }}</p></template> |
| 23 | +<style>/* Preserve café, spacing and \`quotes\` ${index} */ |
| 24 | +:host { color: rgb(23, 45, 67); } |
| 25 | +p { color: rgb(12, 34, 56); }\r/* lone carriage return; NUL \u0000 */</style>` |
| 26 | + await Bun.write(join(input, `Card${index}.stx`), source.replaceAll('\n', '\r\n')) |
| 27 | + } |
| 28 | + const result = await buildComponentLibrary({ inputDir: input, outputDir: output, css: false, minify: true }) |
| 29 | + const { renderComponent } = await import(join(output, 'ssr.js')) |
| 30 | + const hashes = result.components.filter(component => component.styles).map(component => `'sha256-${createHash('sha256').update(component.styles, 'utf8').digest('base64')}'`) |
| 31 | + const csp = `default-src 'none'; script-src 'self'; img-src 'self'; style-src ${hashes.join(' ')}; base-uri 'none'` |
| 32 | + const emitted = new Map(result.files.filter(file => file.endsWith('.js')).map(file => [`/${relative(output, file).split(sep).join('/')}`, file])) |
| 33 | + fixture = createBrowserFixture({ |
| 34 | + createServer: () => Bun.serve({ |
| 35 | + hostname: '127.0.0.1', |
| 36 | + port: 0, |
| 37 | + fetch(request) { |
| 38 | + const pathname = new URL(request.url).pathname |
| 39 | + if (pathname === '/' || pathname === '/ssr') { |
| 40 | + const elements = result.components.map(component => pathname === '/ssr' ? renderComponent(component.tag) : `<${component.tag}></${component.tag}>`).join('') |
| 41 | + return new Response(`<!doctype html><link rel="icon" href="/favicon.ico"><script src="/probe.js"></script>${elements}<script src="/ssr-probe.js"></script><script type="module" src="/bundle.js"></script>`, { headers: { 'Content-Type': 'text/html; charset=utf-8', 'Content-Security-Policy': csp } }) |
| 42 | + } |
| 43 | + if (pathname === '/favicon.ico') return new Response(null, { status: 204 }) |
| 44 | + if (pathname === '/probe.js') return new Response("globalThis.violations=[];globalThis.errors=[];addEventListener('error',event=>errors.push(event.message));addEventListener('unhandledrejection',event=>errors.push(String(event.reason)));addEventListener('securitypolicyviolation',event=>violations.push(event.effectiveDirective))", { headers: { 'Content-Type': 'text/javascript' } }) |
| 45 | + // A classic parser-blocking script inspects actual Declarative Shadow DOM |
| 46 | + // before the deferred custom-element bundle can upgrade either root mode. |
| 47 | + if (pathname === '/ssr-probe.js') return new Response(`globalThis.beforeUpgrade=${JSON.stringify(result.components.map(component => component.tag))}.map(tag=>{const element=document.querySelector(tag);return {registered:!!customElements.get(tag),color:getComputedStyle(element).color,styles:element.shadowRoot?.querySelector('style')?.textContent??null,unparsedTemplate:!!element.querySelector('template[shadowrootmode]')}})`, { headers: { 'Content-Type': 'text/javascript' } }) |
| 48 | + const file = emitted.get(pathname) |
| 49 | + return file ? new Response(Bun.file(file), { headers: { 'Content-Type': 'text/javascript' } }) : new Response('Not found', { status: 404 }) |
| 50 | + }, |
| 51 | + }), |
| 52 | + createView: () => new WebView({ headless: true, backend: { type: 'chrome', url: false } }), |
| 53 | + }) |
| 54 | + for (const pathname of ['/', '/ssr']) { |
| 55 | + await fixture.view.navigate(new URL(pathname, fixture.url).href) |
| 56 | + if (pathname === '/ssr') { |
| 57 | + expect(JSON.parse(await fixture.view.evaluate<string>('JSON.stringify(beforeUpgrade)'))).toEqual(result.components.map(component => ({ |
| 58 | + registered: false, |
| 59 | + color: component.shadowMode ? 'rgb(23, 45, 67)' : 'rgb(0, 0, 0)', |
| 60 | + styles: component.shadowMode === 'open' ? component.styles : null, |
| 61 | + unparsedTemplate: false, |
| 62 | + }))) |
| 63 | + } |
| 64 | + const hydrated = await fixture.waitFor(`Array.from(document.querySelectorAll('csp-card-0,csp-card-1,csp-card-2')).every(element=>element.hasAttribute('hydrated'))`, value => value === true) |
| 65 | + expect(await fixture.view.evaluate('JSON.stringify(errors)')).toBe('[]') |
| 66 | + expect(await fixture.view.evaluate('JSON.stringify(violations)')).toBe('[]') |
| 67 | + expect(hydrated).toBe(true) |
| 68 | + const inspect = `(async()=>{ |
| 69 | + const results=[]; |
| 70 | + for(const tag of ${JSON.stringify(result.components.map(component => component.tag))}){ |
| 71 | + const element=document.querySelector(tag); |
| 72 | + element.count=1;await element.updateComplete; |
| 73 | + results.push({styles:element.renderRoot.querySelector('style')?.textContent??null,color:getComputedStyle(element.renderRoot.querySelector('p')).color,text:element.renderRoot.querySelector('p').textContent}); |
| 74 | + } |
| 75 | + return JSON.stringify(results); |
| 76 | + })()` |
| 77 | + const observed = JSON.parse(await fixture.view.evaluate<string>(inspect)) |
| 78 | + expect(observed).toEqual(result.components.map(component => ({ styles: component.shadowMode ? component.styles : null, color: component.shadowMode ? 'rgb(12, 34, 56)' : 'rgb(0, 0, 0)', text: 'HTML 1' }))) |
| 79 | + for (const [index, component] of result.components.entries()) { |
| 80 | + expect(component.styles).toBe(`/* Preserve café, spacing and \`quotes\` ${index} */\n:host { color: rgb(23, 45, 67); }\np { color: rgb(12, 34, 56); }\n/* lone carriage return; NUL � */`) |
| 81 | + } |
| 82 | + expect(await fixture.view.evaluate('JSON.stringify(violations)')).toBe('[]') |
| 83 | + // A different inline style proves the response really enforces the hashes. |
| 84 | + await fixture.view.evaluate("(()=>{const blocked=document.createElement('style');blocked.textContent='p { color: rgb(200, 0, 0); }';document.querySelector('csp-card-1').renderRoot.appendChild(blocked);return true})()") |
| 85 | + expect(await fixture.waitFor('violations.includes("style-src-elem")', value => value === true)).toBe(true) |
| 86 | + expect(await fixture.view.evaluate("getComputedStyle(document.querySelector('csp-card-1').renderRoot.querySelector('p')).color")).toBe('rgb(12, 34, 56)') |
| 87 | + } |
| 88 | + } |
| 89 | + finally { |
| 90 | + fixture?.close() |
| 91 | + await rm(root, { recursive: true, force: true }) |
| 92 | + } |
| 93 | +}, 30_000) |
0 commit comments