From 90a46d34c049452f44e7679013817a0d044df7c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Raffray?= Date: Fri, 10 May 2024 15:50:41 +0200 Subject: [PATCH] insert csp meta after charset meta --- src/runtime/nitro/plugins/60-recombineHtml.ts | 9 ++++++++- test/ssgHashes.test.ts | 11 +++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/runtime/nitro/plugins/60-recombineHtml.ts b/src/runtime/nitro/plugins/60-recombineHtml.ts index 625dd3ae..be158311 100644 --- a/src/runtime/nitro/plugins/60-recombineHtml.ts +++ b/src/runtime/nitro/plugins/60-recombineHtml.ts @@ -32,7 +32,14 @@ export default defineNitroPlugin((nitroApp) => { const csp = structuredClone(rules.headers.contentSecurityPolicy) csp['frame-ancestors'] = false const headerValue = headerStringFromObject('contentSecurityPolicy', csp) - html.head.unshift(``) + + // Let's insert the CSP meta tag just after the first tag which should be the charset meta + let insertIndex = 0 + const metaCharsetMatch = html.head[0].match(/^/mdi) + if (metaCharsetMatch && metaCharsetMatch.indices) { + insertIndex = metaCharsetMatch.indices[0][1] + } + html.head[0] = html.head[0].slice(0, insertIndex) + `` + html.head[0].slice(insertIndex) } }) }) \ No newline at end of file diff --git a/test/ssgHashes.test.ts b/test/ssgHashes.test.ts index 151c5ab1..f5d3e16e 100644 --- a/test/ssgHashes.test.ts +++ b/test/ssgHashes.test.ts @@ -217,4 +217,15 @@ describe('[nuxt-security] SSG support of CSP', async () => { const metaFrameAncestors = metaCsp!.split(';').find(policy => policy.trim().startsWith('frame-ancestors')) expect(metaFrameAncestors).toBeUndefined() }) + + it('sets CSP meta at top of head after charset meta', async () => { + const res = await fetch('/') + + const body = await res.text() + + expect(res).toBeDefined() + expect(res).toBeTruthy() + expect(body).toBeDefined() + expect(body).toMatch(/^