-
-
Notifications
You must be signed in to change notification settings - Fork 337
feat: add CSP and some security headers to HTML pages #2075
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
serhalp
wants to merge
7
commits into
main
Choose a base branch
from
serhalp/security-audit
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+170
−8
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
010723b
feat: add CSP and other security headers to HTML responses
serhalp a06d5fc
fix: allow more origins in CSP
serhalp 5ff3953
test: catch new CSP violations before they land
serhalp a22dff5
fix: also apply security headers to prerendered pages
serhalp 2160c06
fix: actually disable security headers on API routes
serhalp f17932f
fix: set CSP via <meta> for easier targeting of just HTML
serhalp 49438d8
fix: allow localhost connection in CSP
serhalp File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| import { defineNuxtModule } from 'nuxt/kit' | ||
| import { ALL_KNOWN_GIT_API_ORIGINS } from '#shared/utils/git-providers' | ||
| import { TRUSTED_IMAGE_DOMAINS } from '#server/utils/image-proxy' | ||
|
|
||
| /** | ||
| * Adds Content-Security-Policy and other security headers to all pages. | ||
| * | ||
| * CSP is delivered via a <meta http-equiv> tag in <head>, so it naturally | ||
| * only applies to HTML pages (not API routes). The remaining security | ||
| * headers are set via a catch-all route rule. | ||
| * | ||
| * Note: frame-ancestors is not supported in meta-tag CSP, but | ||
| * X-Frame-Options: DENY (set via route rule) provides equivalent protection. | ||
| * | ||
| * Current policy uses 'unsafe-inline' for scripts and styles because: | ||
| * - Nuxt injects inline scripts for hydration and payload transfer | ||
| * - Vue uses inline styles for :style bindings and scoped CSS | ||
| */ | ||
| export default defineNuxtModule({ | ||
| meta: { name: 'security-headers' }, | ||
| setup(_, nuxt) { | ||
| const imgSrc = [ | ||
| "'self'", | ||
| 'data:', | ||
| ...TRUSTED_IMAGE_DOMAINS.map(domain => `https://${domain}`), | ||
| ].join(' ') | ||
|
|
||
| const connectSrc = [ | ||
| "'self'", | ||
| 'https://*.algolia.net', | ||
| 'https://registry.npmjs.org', | ||
| 'https://api.npmjs.org', | ||
| 'https://npm.antfu.dev', | ||
| ...ALL_KNOWN_GIT_API_ORIGINS, | ||
| // Local CLI connector (npmx CLI communicates via localhost) | ||
| 'http://127.0.0.1:*', | ||
| ].join(' ') | ||
|
|
||
| const frameSrc = ['https://bsky.app', 'https://pdsmoover.com'].join(' ') | ||
|
|
||
| const csp = [ | ||
| `default-src 'none'`, | ||
| `script-src 'self' 'unsafe-inline'`, | ||
| `style-src 'self' 'unsafe-inline'`, | ||
| `img-src ${imgSrc}`, | ||
| `font-src 'self'`, | ||
| `connect-src ${connectSrc}`, | ||
| `frame-src ${frameSrc}`, | ||
| `base-uri 'self'`, | ||
| `form-action 'self'`, | ||
| `object-src 'none'`, | ||
| `manifest-src 'self'`, | ||
| 'upgrade-insecure-requests', | ||
| ].join('; ') | ||
|
|
||
| // CSP via <meta> tag — only present in HTML pages, not API responses. | ||
| nuxt.options.app.head ??= {} | ||
| const head = nuxt.options.app.head as { meta?: Array<Record<string, string>> } | ||
| head.meta ??= [] | ||
| head.meta.push({ | ||
| 'http-equiv': 'Content-Security-Policy', | ||
| 'content': csp, | ||
| }) | ||
|
|
||
| // Other security headers via route rules (fine on all responses). | ||
| nuxt.options.routeRules ??= {} | ||
| nuxt.options.routeRules['/**'] = { | ||
| ...nuxt.options.routeRules['/**'], | ||
| headers: { | ||
| 'X-Content-Type-Options': 'nosniff', | ||
| 'X-Frame-Options': 'DENY', | ||
| 'Referrer-Policy': 'strict-origin-when-cross-origin', | ||
| }, | ||
| } | ||
| }, | ||
| }) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| import { expect, test } from './test-utils' | ||
|
|
||
| test.describe('security headers', () => { | ||
| test('HTML pages include CSP meta tag and security headers', async ({ page, baseURL }) => { | ||
| const response = await page.goto(baseURL!) | ||
| const headers = response!.headers() | ||
|
|
||
| // CSP is delivered via <meta http-equiv> in <head> | ||
| const cspContent = await page | ||
| .locator('meta[http-equiv="Content-Security-Policy"]') | ||
| .getAttribute('content') | ||
| expect(cspContent).toContain("script-src 'self'") | ||
|
|
||
| // Other security headers via route rules | ||
| expect(headers['x-content-type-options']).toBe('nosniff') | ||
| expect(headers['x-frame-options']).toBe('DENY') | ||
| expect(headers['referrer-policy']).toBe('strict-origin-when-cross-origin') | ||
| }) | ||
|
|
||
| test('API routes do not include CSP', async ({ page, baseURL }) => { | ||
| const response = await page.request.get(`${baseURL}/api/registry/package-meta/vue`) | ||
|
|
||
| expect(response.headers()['content-security-policy']).toBeUndefined() | ||
| }) | ||
|
|
||
| // Navigate key pages and assert no CSP violations are logged. | ||
| // This catches new external resources that weren't added to the CSP. | ||
| const PAGES = ['/', '/package/nuxt', '/search?q=vue', '/compare'] as const | ||
|
|
||
| for (const path of PAGES) { | ||
| test(`no CSP violations on ${path}`, async ({ goto, cspViolations }) => { | ||
| await goto(path, { waitUntil: 'hydration' }) | ||
| expect(cspViolations).toEqual([]) | ||
| }) | ||
| } | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🏁 Script executed:
Repository: npmx-dev/npmx.dev
Length of output: 29908
Merge existing headers instead of clobbering them when setting catch-all route rules.
The current code spreads
...nuxt.options.routeRules['/**']at the object level but then immediately overwrites theheadersproperty, discarding any pre-existing headers. Use optional chaining to safely merge the new headers with any existing ones.Proposed merge-safe fix