Configurable CSP Headers

This commit is contained in:
PearlDragon 2025-04-15 13:01:15 -06:00
parent 89fc2a9859
commit f7dae4ce98
10 changed files with 4663 additions and 4 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
# Node.js
node_modules/

15
.prettierrc Normal file
View File

@ -0,0 +1,15 @@
{
"printWidth": 100,
"proseWrap": "always",
"semi": false,
"singleQuote": true,
"tabWidth": 2,
"plugins": [
],
"overrides": [
{
"files": "*.tpl",
"options": { "parser": "html" }
}
]
}

View File

@ -1,8 +1,7 @@
ISC License: ISC License:
Copyright (c) 2004-2010 by Internet Systems Consortium, Inc. ("ISC") Copyright (c) 2025 by William Ross ( the "AUTHOR")
Copyright (c) 1995-2003 by Internet Software Consortium
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DTHE AUTHORLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

View File

@ -1,3 +1,64 @@
# express-csp # express-csp
Rapid configurable Content Security Policy middleware **Rapid, configurable Content Security Policy middleware for Express**, powered by [Helmet](https://helmetjs.github.io/) and simple YAML configuration.
---
## Features
- Secure defaults with CSP via `helmet`
- Configuration in clean, readable YAML
- Easily swappable policies per environment
- Fully tested with Jest & Supertest
---
## Installation
```bash
npm install helmet yaml
npm install --save-dev jest supertest
```
## Usage
```
const express = require('express')
const csp = require('express-csp')
const app = express()
const policyPath = './csp-policy.yml'
app.use(csp(policyPath))
app.get('/', (req, res) => res.send('Secure by CSP!'))
app.listen(3000)
```
## Sample Policy
```
default-src: ["'self'"]
script-src:
- "'self'"
- example.com
style-src:
- "'self'"
- "https:"
- "'unsafe-inline'"
img-src:
- "'self'"
- "data:"
object-src: ["'none'"]
upgrade-insecure-requests: []
```
## License
ISC License
----
## Contributing
PRs welcome! For bugs or suggestions, open an issue.

28
csp-policy.yml Normal file
View File

@ -0,0 +1,28 @@
# Sets
#
# Should yield the follwoiung header:
# "Content-Security-Policy: default-src 'self';
# script-src 'self' example.com;object-src 'none';
# upgrade-insecure-requests"
# Note: embedded single quotes are required
default-src: [ "'self'" ]
base-uri: [ "'self'" ]
font-src:
- "'self'"
- "https:"
- "data:"
form-action: [ "'self'" ]
frame-ancestors: [ "'self'" ]
img-src:
- "'self'"
- "data:"
object-src: [ "'none'" ]
script-src:
- "'self'"
- example.com
script-src-attr: [ "'none'" ]
style-src:
- "'self'"
- "https:"
- "'unsafe-inline'"
upgrade-insecure-requests: []

17
index.cjs Normal file
View File

@ -0,0 +1,17 @@
const fs = require('fs')
const YAML = require('yaml')
const helmet = require('helmet')
module.exports = (path) => {
const csppolicy = fs.readFileSync(path, 'utf8')
const csp = YAML.parse(csppolicy)
return helmet({
contentSecurityPolicy: {
useDefaults: false,
directives: csp,
},
xFrameOptions: 'SAMEORIGIN',
})
}

3
index.mjs Normal file
View File

@ -0,0 +1,3 @@
import csp from './express-csp.cjs'
export { csp }
export default csp

4419
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

39
package.json Normal file
View File

@ -0,0 +1,39 @@
{
"name": "express-csp",
"version": "1.0.0",
"description": "Rapid configurable Content Security Policy middleware",
"main": "./index.js",
"exports": {
"require": "./index.cjs",
"import": "./index.mjs"
},
"module": "./index.mjs",
"scripts": {
"test": "jest"
},
"repository": {
"type": "git",
"url": "https://git.slabhub.co/wnross/express-csp"
},
"bugs": {
"url": "https://github.com/yourname/express-csp/issues"
},
"homepage": "https://github.com/yourname/express-csp#readme",
"keywords": [
"csp",
"security",
"middleware",
"express"
],
"author": "William Ross <wnross@gwhc.net>",
"license": "ISC",
"dependencies": {
"helmet": "^8.1.0",
"yaml": "^2.7.1"
},
"devDependencies": {
"express": "^5.1.0",
"jest": "^29.7.0",
"supertest": "^7.1.0"
}
}

76
test/index.test.js Normal file
View File

@ -0,0 +1,76 @@
const path = require('path')
const request = require('supertest')
const express = require('express')
const fs = require('fs')
// Import the middleware factory (don't name this `csp` to avoid shadowing!)
const createCspMiddleware = require('../index.cjs')
describe('Rapid configurable Content Security Policy middleware', () => {
const validPolicyPath = path.join(__dirname, '../csp-policy.yml')
const malformedPolicyPath = path.join(__dirname, 'bad-policy.yml')
const customPolicyPath = path.join(__dirname, 'custom-policy.yml')
beforeAll(() => {
// Write a malformed YAML file (missing colon, bad list syntax)
fs.writeFileSync(malformedPolicyPath, `default-src 'self'\nthis-is: [bad yaml]`)
// Write a simple custom policy
fs.writeFileSync(
customPolicyPath,
`
default-src: ["'self'"]
script-src: ["'self'", "https://cdn.example.com"]
`,
)
})
afterAll(() => {
fs.unlinkSync(malformedPolicyPath)
fs.unlinkSync(customPolicyPath)
})
it('should load and apply CSP directives from YAML', async () => {
const app = express()
const csp = createCspMiddleware(validPolicyPath)
app.use(csp)
app.get('/', (req, res) => res.send('Hello World'))
const res = await request(app).get('/')
expect(res.headers['content-security-policy']).toBeDefined()
expect(res.text).toBe('Hello World')
})
it('should include specific CSP directives in header', async () => {
const app = express()
const csp = createCspMiddleware(validPolicyPath)
app.use(csp)
app.get('/', (req, res) => res.send('Hello'))
const res = await request(app).get('/')
const cspHeader = res.headers['content-security-policy']
expect(cspHeader).toMatch(/default-src 'self'/)
expect(cspHeader).toMatch(/script-src 'self'[^;]*example\.com/)
expect(cspHeader).toMatch(/style-src 'self'[^;]*'unsafe-inline'/)
})
it('should throw an error for malformed YAML', () => {
expect(() => {
createCspMiddleware(malformedPolicyPath)
}).toThrow(/Implicit keys|bad indentation|unexpected token/i)
})
it('should apply a custom policy file correctly', async () => {
const app = express()
const csp = createCspMiddleware(customPolicyPath)
app.use(csp)
app.get('/', (req, res) => res.send('Test Custom'))
const res = await request(app).get('/')
const cspHeader = res.headers['content-security-policy']
expect(cspHeader).toMatch(/default-src 'self'/)
expect(cspHeader).toMatch(/script-src 'self' https:\/\/cdn\.example\.com/)
})
})