diff --git a/.github/scripts/pages-marketing-preview.mjs b/.github/scripts/pages-marketing-preview.mjs new file mode 100644 index 000000000..539b5ff39 --- /dev/null +++ b/.github/scripts/pages-marketing-preview.mjs @@ -0,0 +1,50 @@ +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { fileURLToPath } from 'node:url'; + +export function previewURL(deployments, project, branch, sha) { + const matches = deployments.filter(deployment => deployment.environment === 'preview' + && deployment.deployment_trigger?.metadata?.branch === branch + && deployment.deployment_trigger?.metadata?.commit_hash === sha + && deployment.latest_stage?.name === 'deploy' + && deployment.latest_stage?.status === 'success'); + assert.equal(matches.length, 1, 'Require one successful preview for this run and commit'); + const url = new URL(matches[0].url); + assert.equal(url.protocol, 'https:'); + assert.ok(url.hostname.endsWith(`.${project}.pages.dev`), 'Require the configured Pages project'); + assert.ok(!url.username && !url.password && url.pathname === '/' && !url.search && !url.hash); + return url; +} + +export async function verifyPreview(url, policy, request = fetch, directory = new URL('../../site/dist/', import.meta.url)) { + for (const [path, status, type] of [ + ['/', 200, 'text/html'], ['/terms/', 200, 'text/html'], ['/privacy/', 200, 'text/html'], + ['/marketing-csp-missing-page', 404, 'text/html'], + ['/install.sh', 200, null], ['/cli.sh', 200, null], + ]) { + const response = await request(new URL(path, url), { redirect: 'error', signal: AbortSignal.timeout(30000) }); + assert.equal(response.status, status, `Unexpected preview status for ${path}`); + assert.equal(response.headers.get('content-security-policy'), policy, `Unexpected preview CSP for ${path}`); + assert.equal(response.headers.get('x-content-type-options'), 'nosniff'); + if (type) assert.ok(response.headers.get('content-type')?.startsWith(type)); + else assert.equal(await response.text(), await readFile(new URL(path.slice(1), directory), 'utf8')); + } +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + const { CLOUDFLARE_ACCOUNT_ID: account, CLOUDFLARE_PAGES_PROJECT_NAME: project, + CLOUDFLARE_API_TOKEN: token, PREVIEW_BRANCH: branch, GITHUB_SHA: sha } = process.env; + assert.ok(account && project && token && branch && sha, 'Require preview deployment configuration'); + const response = await fetch(`https://api.cloudflare.com/client/v4/accounts/${account}/pages/projects/${project}/deployments?env=preview&per_page=100`, { + headers: { Authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(30000), + }); + assert.ok(response.ok, `Pages deployment lookup returned ${response.status}`); + const data = await response.json(); + assert.equal(data.success, true, 'Pages deployment lookup must succeed'); + const url = previewURL(data.result, project, branch, sha); + const headers = await readFile(new URL('../../site/dist/_headers', import.meta.url), 'utf8'); + const policies = [...headers.matchAll(/^\s+Content-Security-Policy: (.+)$/gm)]; + assert.equal(policies.length, 1, 'Require one built policy'); + await verifyPreview(url, policies[0][1]); + console.log('Marketing preview headers, routes and published installers verified'); +} diff --git a/.github/scripts/pages-marketing-preview.test.mjs b/.github/scripts/pages-marketing-preview.test.mjs new file mode 100644 index 000000000..067dd9e10 --- /dev/null +++ b/.github/scripts/pages-marketing-preview.test.mjs @@ -0,0 +1,57 @@ +import assert from 'node:assert/strict'; +import { mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { test } from 'node:test'; +import { previewURL, verifyPreview } from './pages-marketing-preview.mjs'; + +test('accepts only this run successful preview on the reviewed commit and project', () => { + const deployment = { environment: 'preview', url: 'https://abc.marketing.pages.dev', + deployment_trigger: { metadata: { branch: 'check-123', commit_hash: 'sha' } }, + latest_stage: { name: 'deploy', status: 'success' } }; + const select = value => previewURL([value], 'marketing', 'check-123', 'sha'); + assert.equal(select(deployment).origin, 'https://abc.marketing.pages.dev'); + for (const override of [ + { environment: 'production' }, { url: 'https://abc.other.pages.dev' }, + { latest_stage: { name: 'deploy', status: 'failure' } }, + { deployment_trigger: { metadata: { branch: 'other', commit_hash: 'sha' } } }, + { deployment_trigger: { metadata: { branch: 'check-123', commit_hash: 'old' } } }, + ]) assert.throws(() => select({ ...deployment, ...override })); + assert.throws(() => previewURL([deployment, deployment], 'marketing', 'check-123', 'sha')); +}); + +test('verifies page, error and byte-identical installer responses with the built policy', async () => { + const root = await mkdtemp(join(tmpdir(), 'marketing-preview-')); + try { + for (const file of ['install.sh', 'cli.sh']) await writeFile(join(root, file), `# ${file}\n`); + const paths = []; + const request = async url => { + paths.push(url.pathname); + const script = url.pathname.endsWith('.sh'); + return new Response(script ? `# ${url.pathname.slice(1)}\n` : 'Page', { + status: url.pathname.includes('missing-page') ? 404 : 200, + headers: { 'content-security-policy': 'policy', 'x-content-type-options': 'nosniff', + 'content-type': script ? 'text/plain' : 'text/html; charset=utf-8' }, + }); + }; + await verifyPreview('https://abc.marketing.pages.dev', 'policy', request, pathToFileURL(`${root}/`)); + assert.deepEqual(paths, ['/', '/terms/', '/privacy/', '/marketing-csp-missing-page', '/install.sh', '/cli.sh']); + await writeFile(join(root, 'cli.sh'), 'different bytes'); + await assert.rejects(verifyPreview('https://abc.marketing.pages.dev', 'policy', request, pathToFileURL(`${root}/`))); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test('blocks promotion for absent or different policy, redirects and unexpected responses', async () => { + for (const response of [ + new Response('', { status: 200 }), + new Response('', { status: 200, headers: { 'content-security-policy': 'other' } }), + new Response('', { status: 503 }), + ]) await assert.rejects(verifyPreview('https://abc.marketing.pages.dev', 'policy', async () => response)); + await assert.rejects(verifyPreview('https://abc.marketing.pages.dev', 'policy', async (url, options) => { + assert.equal(options.redirect, 'error'); + throw new Error('redirect refused'); + }), /redirect refused/); +}); diff --git a/.github/workflows/marketing-pages.yml b/.github/workflows/marketing-pages.yml new file mode 100644 index 000000000..3d3b66a92 --- /dev/null +++ b/.github/workflows/marketing-pages.yml @@ -0,0 +1,116 @@ +name: Deploy marketing Pages + +on: + pull_request: + paths: + - '.github/workflows/marketing-pages.yml' + - '.github/scripts/pages-*' + workflow_dispatch: + inputs: + expected_sha: + description: Reviewed main commit to deploy (full SHA) + required: true + type: string + +permissions: + contents: read + +concurrency: + group: ${{ github.event_name == 'workflow_dispatch' && 'release' || format('marketing-pages-check-{0}', github.ref) }} + cancel-in-progress: false + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: "22" + - run: node --test .github/scripts/pages-*.test.mjs + + deploy: + needs: check + if: github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && vars.CLOUDFLARE_PAGES_DEPLOY_ENABLED == 'true' + runs-on: ubuntu-latest + timeout-minutes: 30 + environment: site-production + env: + CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }} + PAGES_APP: site + WRANGLER_SEND_METRICS: "false" + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.sha }} + - name: Require the reviewed main commit + env: + EXPECTED_SHA: ${{ inputs.expected_sha }} + run: test "$EXPECTED_SHA" = "$GITHUB_SHA" + - uses: actions/setup-node@v4 + with: + node-version: "22" + - name: Select only the configured marketing project + env: + CLOUDFLARE_PAGES_PROJECTS: ${{ vars.CLOUDFLARE_PAGES_PROJECTS }} + run: | + node --input-type=module <<'JS' + import { appendFileSync } from 'node:fs'; + import { deploymentMatrix } from './.github/scripts/pages-projects.mjs'; + const sites = deploymentMatrix(process.env.CLOUDFLARE_PAGES_PROJECTS).include.filter(target => target.app === 'site'); + if (sites.length !== 1) throw new Error('Configure exactly one marketing Pages project'); + appendFileSync(process.env.GITHUB_ENV, `CLOUDFLARE_PAGES_PROJECT_NAME=${sites[0].project}\n`); + JS + - name: Load existing marketing production configuration + id: config + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + run: | + for name in CLOUDFLARE_API_TOKEN CLOUDFLARE_ACCOUNT_ID CLOUDFLARE_PAGES_PROJECT_NAME; do + test -n "${!name}" + done + curl --fail --silent --show-error \ + --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \ + "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/pages/projects/$CLOUDFLARE_PAGES_PROJECT_NAME" \ + | node .github/scripts/pages-production-config.mjs + - uses: pnpm/action-setup@v4 + with: + version: "11.9.0" + - uses: actions/setup-node@v4 + with: + node-version: "22" + cache: pnpm + cache-dependency-path: site/pnpm-lock.yaml + - name: Install marketing dependencies + working-directory: site + run: pnpm install --frozen-lockfile + - name: Check marketing behavior and CSP + working-directory: site + run: pnpm test + - name: Build marketing with production configuration + working-directory: site + run: pnpm build + - name: Deploy an isolated preview + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + PREVIEW_BRANCH: marketing-check-${{ github.run_id }}-${{ github.run_attempt }} + PRODUCTION_BRANCH: ${{ steps.config.outputs.production_branch }} + run: | + test "$PREVIEW_BRANCH" != "$PRODUCTION_BRANCH" + pnpm dlx wrangler@4.45.0 pages deploy site/dist \ + --project-name "$CLOUDFLARE_PAGES_PROJECT_NAME" \ + --branch "$PREVIEW_BRANCH" --commit-hash "$GITHUB_SHA" + - name: Verify preview responses before production + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + PREVIEW_BRANCH: marketing-check-${{ github.run_id }}-${{ github.run_attempt }} + run: node .github/scripts/pages-marketing-preview.mjs + - name: Publish the verified marketing artifact + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + PRODUCTION_BRANCH: ${{ steps.config.outputs.production_branch }} + run: | + pnpm dlx wrangler@4.45.0 pages deploy site/dist \ + --project-name "$CLOUDFLARE_PAGES_PROJECT_NAME" \ + --branch "$PRODUCTION_BRANCH" --commit-hash "$GITHUB_SHA" \ + --commit-message "Marketing $GITHUB_SHA" diff --git a/docs/content/docs/development/split-deployment.mdx b/docs/content/docs/development/split-deployment.mdx index 83407e03f..86be11bd4 100644 --- a/docs/content/docs/development/split-deployment.mdx +++ b/docs/content/docs/development/split-deployment.mdx @@ -262,6 +262,27 @@ A Pages deploy hook would reuse Cloudflare's build configuration too, but it bui Projects deploy independently, not atomically: one failed build or upload leaves that project's previous deployment live and does not cancel the other projects. After fixing the configuration, use **Re-run failed jobs** on that release run to retry the same release commit without creating another tag or rebuilding successful jobs. Do not retry an older release after a newer one has deployed unless you intend a rollback. To pause release uploads, set `CLOUDFLARE_PAGES_DEPLOY_ENABLED` to `false`; this leaves current deployments live and does not re-enable Cloudflare's automatic deployments. This workflow deploys only the listed static frontends; it does not deploy backend services. +The marketing build generates a Content Security Policy in `site/dist/_headers` +from the inline scripts in every rendered page, including the error page. Serve +that header with the generated files when hosting outside Pages. Scripts require +a build-generated hash or an allowed origin; inline event handlers and dynamic +code evaluation are refused. Inline styles remain allowed for page presentation. +The configured PostHog HTTPS origin and its regional asset host are allowed when +analytics is enabled. Cloudflare's analytics beacon has its own explicit origin. +Changes to scripts or analytics configuration require a fresh build. A policy +that exceeds Pages' 2,000-character header limit fails the build. + +For a marketing-only update without a release tag, run **Deploy marketing Pages** +on `main`, passing its reviewed full commit SHA as `expected_sha`. The manual +workflow uses `site-production` and the existing Pages production variables. It +requires exactly one `site` project in `CLOUDFLARE_PAGES_PROJECTS`, runs the site +checks, and builds once. An isolated preview must serve the built CSP on the +home, legal and error pages and preserve the published installer bytes before +the same artifact is uploaded to the production branch. A failed preview leaves +production unchanged. The workflow shares the release concurrency lock and +deploys only the marketing site. The existing Pages deployment enable flag +applies to this workflow too. + ## Anything the control plane cannot know `warmbly join` writes `/etc/warmbly/node.env` from the control plane's answer and rewrites it on every join. Next to it, `/etc/warmbly/node.local.env` is created once and never written again, and the container reads it second, so a name repeated there wins. diff --git a/site/astro.config.mjs b/site/astro.config.mjs index 6d1c486eb..ef0168f08 100644 --- a/site/astro.config.mjs +++ b/site/astro.config.mjs @@ -3,11 +3,13 @@ import { defineConfig } from 'astro/config'; import tailwindcss from '@tailwindcss/vite'; import sitemap from '@astrojs/sitemap'; import mdx from '@astrojs/mdx'; +import contentSecurityPolicyHeaders from './scripts/content-security-policy.mjs'; // https://astro.build/config export default defineConfig({ site: 'https://warmbly.com', integrations: [ + contentSecurityPolicyHeaders(), mdx(), sitemap({ // The 404 page is noindex and should never appear in the sitemap. diff --git a/site/package.json b/site/package.json index 533bdd006..b042f6046 100644 --- a/site/package.json +++ b/site/package.json @@ -4,7 +4,7 @@ "version": "1.0.0", "private": true, "scripts": { - "test": "node scripts/check-observability.mjs && node scripts/check-acquisition.mjs", + "test": "node scripts/check-observability.mjs && node scripts/check-acquisition.mjs && node --test scripts/content-security-policy.test.mjs", "dev": "astro dev", "build": "astro build", "preview": "astro preview", @@ -21,5 +21,9 @@ "reading-time": "^1.5.0", "sharp": "0.35.5", "tailwindcss": "^4.1.10" + }, + "devDependencies": { + "parse5": "^8.0.1", + "vite": "^8.3.5" } } diff --git a/site/pnpm-lock.yaml b/site/pnpm-lock.yaml index edba6ca50..7cc864a7c 100644 --- a/site/pnpm-lock.yaml +++ b/site/pnpm-lock.yaml @@ -47,6 +47,13 @@ importers: tailwindcss: specifier: ^4.1.10 version: 4.3.0 + devDependencies: + parse5: + specifier: ^8.0.1 + version: 8.0.1 + vite: + specifier: ^8.3.5 + version: 8.3.5(@types/node@24.13.5)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1) packages: @@ -1114,6 +1121,10 @@ packages: resolution: {integrity: sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==} engines: {node: '>=0.12'} + entities@8.1.0: + resolution: {integrity: sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==} + engines: {node: '>=20.19.0'} + es-module-lexer@2.3.2: resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==} @@ -1741,6 +1752,9 @@ packages: parse5@7.3.0: resolution: {integrity: sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==} + parse5@8.0.1: + resolution: {integrity: sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==} + path-expression-matcher@1.6.2: resolution: {integrity: sha512-enSlaiat05iasnzmgNxRj8reFdj3puY2QpNgP1aPIaVfT6nn9ICuPoFlKHk8EN22HcwewshO+mN2DGbkCEOtqQ==} engines: {node: '>=14.0.0'} @@ -3148,6 +3162,8 @@ snapshots: entities@6.0.1: {} + entities@8.1.0: {} + es-module-lexer@2.3.2: {} es-module-lexer@3.0.4: {} @@ -4109,6 +4125,10 @@ snapshots: dependencies: entities: 6.0.1 + parse5@8.0.1: + dependencies: + entities: 8.1.0 + path-expression-matcher@1.6.2: {} piccolore@0.1.3: {} diff --git a/site/public/_headers b/site/public/_headers index 42e3ffbfa..b43847c48 100644 --- a/site/public/_headers +++ b/site/public/_headers @@ -1,6 +1,7 @@ # Security response headers for the marketing site. Static pages, no # credentials, but the site serves install.sh and cli.sh, so framing and # content-type sniffing are both switched off. +# The build adds a CSP with hashes of the generated inline scripts. /* X-Content-Type-Options: nosniff X-Frame-Options: DENY diff --git a/site/scripts/content-security-policy.mjs b/site/scripts/content-security-policy.mjs new file mode 100644 index 000000000..a0deec5fc --- /dev/null +++ b/site/scripts/content-security-policy.mjs @@ -0,0 +1,83 @@ +import { createHash } from 'node:crypto'; +import { readFile, readdir, writeFile } from 'node:fs/promises'; +import { parse } from 'parse5'; +import { loadEnv } from 'vite'; +import { fileURLToPath } from 'node:url'; + +export function inlineHashes(html) { + const scripts = new Set(); + function visit(node) { + const attributes = Object.fromEntries((node.attrs ?? []).map(({ name, value }) => [name, value])); + if (Object.keys(attributes).some((name) => name.startsWith('on'))) { + throw new Error('Marketing CSP requires event listeners instead of inline handlers'); + } + if (node.tagName === 'script' && !attributes.src && !['application/ld+json', 'application/json'].includes(attributes.type)) { + const text = (node.childNodes ?? []).map((child) => child.value ?? '').join(''); + if (text) { + const hash = `'sha256-${createHash('sha256').update(text).digest('base64')}'`; + scripts.add(hash); + } + } + for (const child of node.childNodes ?? []) visit(child); + } + visit(parse(html)); + return scripts; +} + +export function contentSecurityPolicy(scripts, analyticsHost) { + const analytics = []; + if (analyticsHost) { + const url = new URL(analyticsHost); + if (url.protocol !== 'https:' || url.username || url.password) throw new Error('Analytics CSP requires an HTTPS host'); + analytics.push(url.origin); + if (/^(us|eu)\.i\.posthog\.com$/.test(url.hostname)) { + analytics.push(`https://${url.hostname.replace('.i.', '-assets.i.')}`); + } + } + return [ + "default-src 'none'", + "base-uri 'none'", + "object-src 'none'", + "frame-ancestors 'none'", + "form-action 'self'", + `script-src 'self' https://static.cloudflareinsights.com ${[...analytics, ...scripts].join(' ')}`, + "script-src-attr 'none'", + "style-src 'self' 'unsafe-inline'", + `img-src 'self' data: ${analytics.join(' ')}`, + "font-src 'self'", + `connect-src 'self' https://cloudflareinsights.com ${analytics.join(' ')}`, + "worker-src 'self' blob:", + ].join('; '); +} + +export default function contentSecurityPolicyHeaders() { + let analyticsHost; + return { + name: 'marketing-content-security-policy', + hooks: { + 'astro:config:setup': ({ config, mode }) => { + const env = loadEnv(mode, fileURLToPath(config.root), 'PUBLIC_POSTHOG_'); + analyticsHost = env.PUBLIC_POSTHOG_KEY ? env.PUBLIC_POSTHOG_HOST || 'https://us.i.posthog.com' : undefined; + }, + 'astro:build:done': async ({ dir, logger }) => { + const hashes = new Set(); + for (const entry of await readdir(dir, { recursive: true })) { + if (!entry.endsWith('.html')) continue; + const page = inlineHashes(await readFile(new URL(entry, dir), 'utf8')); + for (const hash of page) hashes.add(hash); + } + if (!hashes.size) throw new Error('No marketing page scripts found for CSP'); + const policy = contentSecurityPolicy(hashes, analyticsHost); + const header = ` Content-Security-Policy: ${policy}`; + // Pages rejects header lines longer than 2,000 characters. + if (header.length > 2000) throw new Error(`Marketing CSP exceeds the Pages header limit (${header.length})`); + const file = new URL('_headers', dir); + const headers = await readFile(file, 'utf8'); + if (/Content-Security-Policy:/i.test(headers)) throw new Error('Marketing CSP header already configured'); + if (!headers.includes('/*\n')) throw new Error('Marketing headers require a catch-all rule'); + await writeFile(file, headers.replace('/*\n', `/*\n${header}\n`)); + logger.info(`Generated CSP for all marketing routes (${hashes.size} script hashes)`); + }, + }, + }; +} diff --git a/site/scripts/content-security-policy.test.mjs b/site/scripts/content-security-policy.test.mjs new file mode 100644 index 000000000..e14f258d1 --- /dev/null +++ b/site/scripts/content-security-policy.test.mjs @@ -0,0 +1,63 @@ +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { test } from 'node:test'; +import integration, { contentSecurityPolicy, inlineHashes } from './content-security-policy.mjs'; + +test('hashes browser-normalized script text without treating JSON data or remote scripts as code', () => { + const hashes = inlineHashes(''); + const digest = createHash('sha256').update('window.ready = true;\n').digest('base64'); + assert.deepEqual([...hashes], [`'sha256-${digest}'`]); + assert.throws(() => inlineHashes(''), /inline handlers/); +}); + +test('restricts executable sources while preserving configured analytics and inline presentation', () => { + const directives = new Map(contentSecurityPolicy(new Set(["'sha256-known'"]), 'https://eu.i.posthog.com') + .split('; ').map((value) => { const [name, ...sources] = value.split(' '); return [name, sources]; })); + assert.deepEqual(directives.get('default-src'), ["'none'"]); + assert.deepEqual(directives.get('script-src-attr'), ["'none'"]); + assert.deepEqual(directives.get('frame-ancestors'), ["'none'"]); + const scripts = directives.get('script-src'); + assert.ok(scripts.includes("'sha256-known'")); + assert.ok(scripts.includes('https://eu-assets.i.posthog.com')); + assert.ok(!scripts.includes("'unsafe-inline'") && !scripts.includes("'unsafe-eval'")); + assert.ok(directives.get('style-src').includes("'unsafe-inline'")); + assert.ok(!contentSecurityPolicy(new Set()).includes('posthog')); + assert.throws(() => contentSecurityPolicy(new Set(), 'http://analytics.example.com'), /HTTPS/); + assert.throws(() => contentSecurityPolicy(new Set(), 'https://user:password@example.com'), /HTTPS/); +}); + +test('emits one catch-all header from every generated page and refuses oversized or duplicate policies', async () => { + const root = await mkdtemp(join(tmpdir(), 'marketing-csp-')); + const dir = pathToFileURL(`${root}/`); + try { + await writeFile(join(root, '.env.production'), 'PUBLIC_POSTHOG_KEY=test\nPUBLIC_POSTHOG_HOST=https://analytics.example.com/ingest\n'); + await mkdir(join(root, 'terms')); + await writeFile(join(root, 'index.html'), ''); + await writeFile(join(root, 'terms/index.html'), ''); + const baseline = '/*\n X-Frame-Options: DENY\n/_astro/*\n Cache-Control: public\n'; + await writeFile(join(root, '_headers'), baseline); + const { hooks } = integration(); + hooks['astro:config:setup']({ config: { root: dir }, mode: 'production' }); + const build = () => hooks['astro:build:done']({ dir, logger: { info() {} } }); + await build(); + const headers = await readFile(join(root, '_headers'), 'utf8'); + assert.ok(headers.startsWith('/*\n Content-Security-Policy:')); + for (const code of ['window.home=true', 'window.legal=true']) { + assert.ok(headers.includes(createHash('sha256').update(code).digest('base64'))); + } + assert.ok(headers.includes('https://analytics.example.com')); + assert.ok(headers.includes('X-Frame-Options: DENY')); + assert.ok(headers.includes('/_astro/*\n Cache-Control: public')); + await assert.rejects(build(), /already configured/); + await writeFile(join(root, '_headers'), baseline); + await writeFile(join(root, 'index.html'), Array.from({ length: 40 }, (_, i) => ``).join('')); + await assert.rejects(build(), /header limit/); + assert.equal(await readFile(join(root, '_headers'), 'utf8'), baseline); + } finally { + await rm(root, { recursive: true, force: true }); + } +});