Skip to content

Commit

Permalink
Merge pull request #449 from Baroshem/fix/csp-meta-charset-v2
Browse files Browse the repository at this point in the history
fix(csp): ensure charset meta at top of head
  • Loading branch information
vejja authored May 17, 2024
2 parents 60ddf61 + 90a46d3 commit 6c8d01f
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 @@ -21,7 +21,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 6c8d01f

Please sign in to comment.