22
33A robust Content Security Policy (CSP) generator that works in both Node.js and browser environments. This tool analyzes HTML content and generates appropriate CSP headers to enhance your application's security.
44
5+ ---
6+
57## Requirements
68
79- [ Bun] ( https://bun.sh/ ) - A modern JavaScript runtime that is fast and easy to use.
@@ -40,6 +42,45 @@ CSP_REQUIRE_TRUSTED_TYPES=true \
4042csp-generator
4143```
4244
45+ ---
46+
47+ ## Importing in Node and Browser
48+
49+ - ** Node.js:**
50+ ``` js
51+ import {SecureCSPGenerator } from ' csp-generator'
52+ ```
53+ - ** Browser:**
54+ ``` js
55+ import {CSPGenerator } from ' csp-generator/browser'
56+ ```
57+
58+ ---
59+
60+ ## TypeScript Support
61+
62+ This package ships with full TypeScript type definitions. Types are automatically included when you import from ` csp-generator ` in a TypeScript project.
63+
64+ If you need to import specific types:
65+
66+ ``` ts
67+ import type {SecureCSPGeneratorOptions } from ' csp-generator/dist/types'
68+ ```
69+
70+ ---
71+
72+ ## Trusted Types
73+
74+ Trusted Types is a web platform security standard that helps prevent DOM-based XSS by locking down injection sinks. When you enable ` --require-trusted-types ` or set ` CSP_REQUIRE_TRUSTED_TYPES=true ` , the generated CSP will include:
75+
76+ ```
77+ require-trusted-types-for 'script'
78+ ```
79+
80+ This instructs browsers to only allow script-creating APIs to accept Trusted Types objects, mitigating XSS risks.
81+
82+ ---
83+
4384## CLI Parameters
4485
4586The CSP generator supports the following command-line parameters:
@@ -50,62 +91,70 @@ csp-generator <url> [options]
5091
5192### Options
5293
53- | Option | Type | Default | Description |
54- | --------| ------| --------- | -------------|
55- | ` --allow-http ` | boolean | false | Allow HTTP URLs in addition to HTTPS |
56- | ` --allow-private-origins ` | boolean | false | Permit private IP / localhost origins |
57- | ` --allow-unsafe-inline-script ` | boolean | false | Add 'unsafe-inline' to 'script-src' when inline scripts detected |
58- | ` --allow-unsafe-inline-style ` | boolean | false | Add 'unsafe-inline' to 'style-src' when inline styles detected |
59- | ` --allow-unsafe-eval ` | boolean | false | Add 'unsafe-eval' to 'script-src' |
60- | ` --require-trusted-types ` | boolean | false | Add "require-trusted-types-for 'script'" to the CSP |
61- | ` --use-strict-dynamic ` | boolean | false | Add 'strict-dynamic' to script-src |
62- | ` --use-nonce ` | boolean | true | Generate and use a random nonce for inline scripts (recommended) |
63- | ` --custom-nonce ` | string | | Use a custom nonce value instead of a random one |
64- | ` --use-hashes ` | boolean | false | Generate hashes for inline content |
65- | ` --upgrade-insecure-requests ` | boolean | true | Force HTTPS upgrades |
66- | ` --block-mixed-content ` | boolean | true | Block mixed content |
67- | ` --restrict-framing ` | boolean | true | Add frame-ancestors 'none' |
68- | ` --use-sandbox ` | boolean | false | Add sandbox directive with safe defaults |
69- | ` --max-body-size ` | number | 0 | Maximum allowed bytes for HTML download (0 = unlimited) |
70- | ` --timeout-ms ` | number | 8000 | Timeout for fetch requests in milliseconds |
71- | ` --format ` , ` -f ` | string | 'header' | Output format: header, raw, json, csp-only |
72- | ` --presets ` | string | - | User-provided source lists (format: "directive1: value1 ,value2;directive2: value3 ,value4") |
73- | ` --fetch-options ` | JSON | - | Custom fetch options as JSON string |
94+ | Option | Type | Default | Description |
95+ | ------------------------------ | ------- | -------- | ---------------------------------------------------------------------------------------- |
96+ | ` --allow-http ` | boolean | false | Allow HTTP URLs in addition to HTTPS |
97+ | ` --allow-private-origins ` | boolean | false | Permit private IP / localhost origins |
98+ | ` --allow-unsafe-inline-script ` | boolean | false | Add 'unsafe-inline' to 'script-src' when inline scripts detected |
99+ | ` --allow-unsafe-inline-style ` | boolean | false | Add 'unsafe-inline' to 'style-src' when inline styles detected |
100+ | ` --allow-unsafe-eval ` | boolean | false | Add 'unsafe-eval' to 'script-src' |
101+ | ` --require-trusted-types ` | boolean | false | Add "require-trusted-types-for 'script'" to the CSP |
102+ | ` --use-strict-dynamic ` | boolean | false | Add 'strict-dynamic' to script-src |
103+ | ` --use-nonce ` | boolean | true | Generate and use a random nonce for inline scripts (recommended) |
104+ | ` --custom-nonce ` | string | | Use a custom nonce value instead of a random one |
105+ | ` --use-hashes ` | boolean | false | Generate hashes for inline content |
106+ | ` --upgrade-insecure-requests ` | boolean | true | Force HTTPS upgrades |
107+ | ` --block-mixed-content ` | boolean | true | Block mixed content |
108+ | ` --restrict-framing ` | boolean | true | Add frame-ancestors 'none' |
109+ | ` --use-sandbox ` | boolean | false | Add sandbox directive with safe defaults |
110+ | ` --max-body-size ` | number | 0 | Maximum allowed bytes for HTML download (0 = unlimited) |
111+ | ` --timeout-ms ` | number | 8000 | Timeout for fetch requests in milliseconds |
112+ | ` --format ` , ` -f ` | string | 'header' | Output format: header, raw, json, csp-only |
113+ | ` --presets ` | string | - | User-provided source lists (format: "directive1: value1 ,value2;directive2: value3 ,value4") |
114+ | ` --fetch-options ` | JSON | - | Custom fetch options as JSON string |
74115
75116### Examples
76117
77118Generate CSP with default settings:
119+
78120``` bash
79121csp-generator https://example.com
80122```
81123
82124Use a custom nonce:
125+
83126``` bash
84127csp-generator https://example.com --custom-nonce my-custom-nonce
85128```
86129
87130Or with environment variable:
131+
88132``` bash
89133CSP_CUSTOM_NONCE=my-custom-nonce csp-generator https://example.com
90134```
91135
92136Enable unsafe inline styles and strict dynamic:
137+
93138``` bash
94139csp-generator https://example.com \
95140 --allow-unsafe-inline-style true \
96141 --use-strict-dynamic true
97142```
98143
99144Output as JSON with custom presets:
145+
100146``` bash
101147csp-generator https://example.com \
102148 --format json \
103149 --presets " script-src:https://cdn.example.com;connect-src:https://api.example.com"
104150```
105151
152+ ---
153+
106154## Environment Variables Configuration
107155
108156The CSP generator uses Bun's built-in support for environment variables. It automatically loads variables from:
157+
109158- ` .env `
110159- ` .env.local `
111160- ` .env.${NODE_ENV} ` (e.g., ` .env.development ` , ` .env.production ` )
@@ -114,11 +163,13 @@ The CSP generator uses Bun's built-in support for environment variables. It auto
114163To get started:
115164
1161651 . Copy the example environment file:
166+
117167``` bash
118168cp .env.example .env
119169```
120170
1211712 . Edit the ` .env ` file with your desired configuration:
172+
122173``` env
123174# Required (if not using command-line argument)
124175CSP_URL=https://your-site.com
@@ -129,44 +180,51 @@ CSP_USE_STRICT_DYNAMIC=true
129180```
130181
1311823 . Run the generator:
183+
132184``` bash
133185csp-generator
134186```
135187
136188All command-line options have equivalent environment variables. This is particularly useful for:
189+
137190- CI/CD pipelines
138191- Docker environments
139192- Development configurations
140193- Shared team settings
141194
142195> Note: No additional packages are needed for .env support as it's built into Bun.
143196
197+ ---
198+
144199## Browser Usage
145200
146201You can also use the CSP generator directly in your browser:
147202
148203``` html
149204<script type =" module" >
150- import { CSPGenerator } from ' csp-generator/browser' ;
205+ import {CSPGenerator } from ' csp-generator/browser'
151206
152207 // Create a new instance
153208 const generator = new CSPGenerator ({
154209 // Optional configuration
155210 allowUnsafeInlineStyle: true ,
156- useStrictDynamic: true
157- });
211+ useStrictDynamic: true ,
212+ })
158213
159214 // Generate CSP for a URL
160- const result = await generator .generate (' https://example.com' );
161- console .log (result);
215+ const result = await generator .generate (' https://example.com' )
216+ console .log (result)
162217 </script >
163218```
164219
165220The browser version provides the same functionality as the CLI but uses native browser APIs for better performance. It's particularly useful for:
221+
166222- Generating CSPs for single-page applications
167223- Testing CSPs against your current page
168224- Integrating CSP generation into your web development workflow
169225
226+ ---
227+
170228## Environment Variables
171229
172230### Required (if not provided as command-line argument)
@@ -217,34 +275,41 @@ The browser version provides the same functionality as the CLI but uses native b
217275 - ` json ` : Outputs JSON format: ` {"Content-Security-Policy":"[policy]"} `
218276 - ` csp-only ` : Outputs just the CSP directives
219277
278+ ---
279+
220280## Features
221281
222282The generator automatically detects and includes various resource types:
223283
2242841 . ** Scripts**
285+
225286 - External script sources
226287 - Inline scripts (with hash/nonce)
227288 - Worker scripts
228289 - Module scripts
229290
2302912 . ** Styles**
292+
231293 - External stylesheets
232294 - Inline styles
233295 - CSS @import rules
234296 - CSS url() functions
235297
2362983 . ** Fonts**
299+
237300 - Font files from @font-face rules
238301 - Preloaded fonts
239302 - Google Fonts and other CDNs
240303
2413044 . ** Network**
305+
242306 - Fetch API calls
243307 - WebSocket connections
244308 - EventSource connections
245309 - XMLHttpRequest (legacy)
246310
2473115 . ** Media**
312+
248313 - Images
249314 - Videos
250315 - Audio
@@ -255,6 +320,20 @@ The generator automatically detects and includes various resource types:
255320 - frame-ancestors
256321 - Sandbox controls
257322
323+ ---
324+
325+ ## Error Handling and Security
326+
327+ - The generator will throw errors for:
328+ - Non-OK HTTP responses
329+ - Content-Type mismatches
330+ - Exceeding the maximum body size
331+ - Insecure or private origins (unless explicitly allowed)
332+ - SSRF protection is enabled by default. Use ` --allow-private-origins ` to override.
333+ - Only HTTPS URLs are allowed unless ` --allow-http ` is set.
334+
335+ ---
336+
258337## Notes
259338
260339- The package requires Bun to be installed and available in your PATH
@@ -266,6 +345,8 @@ The generator automatically detects and includes various resource types:
266345- WebSocket URLs are detected in script content
267346- The browser version uses native APIs for better performance
268347
348+ ---
349+
269350## Development
270351
271352``` bash
@@ -286,8 +367,13 @@ bun run format
286367
287368# Try the CLI locally during development
288369bun src/cli.ts https://example.com
370+
371+ # Check type definitions
372+ bun run build:types
289373```
290374
375+ ---
376+
291377## License
292378
293379MIT
0 commit comments