Skip to content

Commit d94d63f

Browse files
committed
docs: update README with new sections on importing, TypeScript support, and error handling; improve CLI parameters table formatting
build: modify package.json to include type declaration generation in build process fix: adjust TypeScript configuration to emit declaration files and set output directory refactor: update SecureCSPGenerator options type and ensure fetch headers are correctly merged
1 parent f09752f commit d94d63f

File tree

4 files changed

+125
-35
lines changed

4 files changed

+125
-35
lines changed

README.md

Lines changed: 112 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
A 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 \
4042
csp-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

4586
The 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

77118
Generate CSP with default settings:
119+
78120
```bash
79121
csp-generator https://example.com
80122
```
81123

82124
Use a custom nonce:
125+
83126
```bash
84127
csp-generator https://example.com --custom-nonce my-custom-nonce
85128
```
86129

87130
Or with environment variable:
131+
88132
```bash
89133
CSP_CUSTOM_NONCE=my-custom-nonce csp-generator https://example.com
90134
```
91135

92136
Enable unsafe inline styles and strict dynamic:
137+
93138
```bash
94139
csp-generator https://example.com \
95140
--allow-unsafe-inline-style true \
96141
--use-strict-dynamic true
97142
```
98143

99144
Output as JSON with custom presets:
145+
100146
```bash
101147
csp-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

108156
The 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
114163
To get started:
115164

116165
1. Copy the example environment file:
166+
117167
```bash
118168
cp .env.example .env
119169
```
120170

121171
2. Edit the `.env` file with your desired configuration:
172+
122173
```env
123174
# Required (if not using command-line argument)
124175
CSP_URL=https://your-site.com
@@ -129,44 +180,51 @@ CSP_USE_STRICT_DYNAMIC=true
129180
```
130181

131182
3. Run the generator:
183+
132184
```bash
133185
csp-generator
134186
```
135187

136188
All 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

146201
You 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

165220
The 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

222282
The generator automatically detects and includes various resource types:
223283

224284
1. **Scripts**
285+
225286
- External script sources
226287
- Inline scripts (with hash/nonce)
227288
- Worker scripts
228289
- Module scripts
229290

230291
2. **Styles**
292+
231293
- External stylesheets
232294
- Inline styles
233295
- CSS @import rules
234296
- CSS url() functions
235297

236298
3. **Fonts**
299+
237300
- Font files from @font-face rules
238301
- Preloaded fonts
239302
- Google Fonts and other CDNs
240303

241304
4. **Network**
305+
242306
- Fetch API calls
243307
- WebSocket connections
244308
- EventSource connections
245309
- XMLHttpRequest (legacy)
246310

247311
5. **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
288369
bun src/cli.ts https://example.com
370+
371+
# Check type definitions
372+
bun run build:types
289373
```
290374

375+
---
376+
291377
## License
292378

293379
MIT

package.json

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,14 @@
2020
"csp-generator": "./dist/cli.js"
2121
},
2222
"files": [
23-
"dist/cli.js",
24-
"dist/csp-generator.js",
25-
"dist/csp-generator.browser.js"
23+
"dist/"
2624
],
2725
"scripts": {
28-
"build": "bun run build:cli && bun run build:core && bun run build:browser",
26+
"build": "bun run build:cli && bun run build:core && bun run build:browser && bun run build:types",
2927
"build:cli": "bun build ./src/cli.ts --outdir ./dist --target node --minify --outfile cli.js",
3028
"build:core": "bun build ./src/csp-generator.ts --outdir ./dist --target node --minify --outfile csp-generator.js",
3129
"build:browser": "bun build ./src/csp-generator.browser.ts --outdir ./dist --target browser --minify --outfile csp-generator.browser.js --format esm",
30+
"build:types": "tsc --emitDeclarationOnly --declaration --project tsconfig.json",
3231
"prepublishOnly": "bun run build",
3332
"test": "bun test",
3433
"lint": "npx prettier --check **/*.ts",

src/csp-generator.browser.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ export class SecureCSPGenerator {
1616
/** The target URL to analyze. */
1717
readonly url: URL
1818

19-
private readonly opts: Required<SecureCSPGeneratorOptions>
19+
private readonly opts: SecureCSPGeneratorOptions
2020
private readonly logger: Logger
2121
private html: string = ''
2222
private readonly sources = new Map<DirectiveName, Set<string>>()
@@ -141,7 +141,7 @@ export class SecureCSPGenerator {
141141
const response = await fetch(this.url, {
142142
...fetchOptions,
143143
signal: ac.signal,
144-
headers: {accept: 'text/html', ...fetchOptions.headers},
144+
headers: {accept: 'text/html', ...fetchOptions!.headers},
145145
}).finally(() => clearTimeout(timer))
146146

147147
if (!response.ok) {

tsconfig.json

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,12 @@
1010

1111
// Bundler mode
1212
"moduleResolution": "bundler",
13-
"allowImportingTsExtensions": true,
13+
"allowImportingTsExtensions": false,
1414
"verbatimModuleSyntax": true,
15-
"noEmit": true,
15+
"noEmit": false, // <-- Change to false to allow emitting files
16+
"declaration": true, // <-- Emit .d.ts files
17+
"declarationDir": "./dist", // <-- Output types to dist
18+
"declarationMap": false, // (optional) Enable declaration maps
1619

1720
// Best practices
1821
"strict": true,
@@ -24,5 +27,7 @@
2427
"noUnusedLocals": false,
2528
"noUnusedParameters": false,
2629
"noPropertyAccessFromIndexSignature": false
27-
}
30+
},
31+
"include": ["src/**/*.ts"],
32+
"exclude": ["test", "demos", "**/*.test.ts"]
2833
}

0 commit comments

Comments
 (0)