Skip to content

Commit

Permalink
insert csp meta after charset meta
Browse files Browse the repository at this point in the history
  • Loading branch information
vejja committed May 10, 2024
1 parent 47ed844 commit 90a46d3
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/runtime/nitro/plugins/60-recombineHtml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(`<meta http-equiv="Content-Security-Policy" content="${headerValue}">`)

// 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(/^<meta charset="(.*?)">/mdi)
if (metaCharsetMatch && metaCharsetMatch.indices) {
insertIndex = metaCharsetMatch.indices[0][1]
}
html.head[0] = html.head[0].slice(0, insertIndex) + `<meta http-equiv="Content-Security-Policy" content="${headerValue}">` + html.head[0].slice(insertIndex)
}
})
})
11 changes: 11 additions & 0 deletions test/ssgHashes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(/^<!DOCTYPE html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy"/)
})
})

0 comments on commit 90a46d3

Please sign in to comment.