Skip to content

Commit e608283

Browse files
author
MPCoreDeveloper
committed
pre nuget lib vrsion
1 parent 095f6bd commit e608283

File tree

13 files changed

+1739
-60
lines changed

13 files changed

+1739
-60
lines changed

README.md

Lines changed: 202 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,70 +1,241 @@
1-
# SafeWebCore
1+
# 🛡️ SafeWebCore
22

3-
A .NET 10 library for building secure web applications with sensible defaults.
3+
[![.NET 10](https://img.shields.io/badge/.NET-10-512BD4?logo=dotnet)](https://dotnet.microsoft.com)
4+
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
5+
[![securityheaders.com](https://img.shields.io/badge/securityheaders.com-A%2B-brightgreen)](https://securityheaders.com)
46

5-
## Features
7+
**SafeWebCore** is a lightweight, high-performance .NET 10 middleware library that adds security headers to your ASP.NET Core applications. It targets an **A+ rating** on [securityheaders.com](https://securityheaders.com) out of the box — zero configuration required.
68

7-
- Content Security Policy (CSP) middleware
8-
- Security header management
9-
- Zero-configuration secure defaults
9+
---
1010

11-
## Getting Started
11+
## ✨ Features
1212

13-
### Prerequisites
13+
- 🔒 **A+ in one line**`AddNetSecureHeadersStrictAPlus()` configures the strictest security headers instantly
14+
- 🧩 **Nonce-based CSP** — per-request cryptographic nonces for `script-src` and `style-src`
15+
- 📋 **CSP Level 3** — Trusted Types, `strict-dynamic`, `script-src-elem/attr`, `style-src-elem/attr`, `worker-src`, `fenced-frame-src`
16+
- 🎯 **Fluent CSP Builder** — type-safe, chainable API for building Content Security Policy
17+
-**Zero-allocation nonce generation**`stackalloc` + `RandomNumberGenerator` on the hot path
18+
- 🛑 **Server header removal** — hides server technology from attackers
19+
- 🔌 **Extensible** — add custom `IHeaderPolicy` implementations for any header
20+
- 📊 **CSP violation reporting** — built-in middleware for `/csp-report` endpoint
1421

15-
- [.NET 10 SDK](https://dotnet.microsoft.com/download)
22+
---
1623

17-
### Installation
24+
## 🚀 Quick Start
25+
26+
### 1. Install
1827

1928
```bash
2029
dotnet add package SafeWebCore
2130
```
2231

23-
### Usage
32+
### 2. One-line A+ setup (recommended)
2433

2534
```csharp
35+
using SafeWebCore.Extensions;
36+
2637
var builder = WebApplication.CreateBuilder(args);
38+
39+
// Adds ALL security headers with the strictest A+ configuration
40+
builder.Services.AddNetSecureHeadersStrictAPlus();
41+
2742
var app = builder.Build();
2843

29-
app.UseSafeWebCore();
44+
app.UseNetSecureHeaders();
45+
app.MapGet("/", () => "Hello, secure world!");
3046

3147
app.Run();
3248
```
3349

34-
## Building
50+
That's it! Your application now returns these headers on every response:
3551

36-
```bash
37-
dotnet build
52+
| Header | Value |
53+
|--------|-------|
54+
| `Strict-Transport-Security` | `max-age=63072000; includeSubDomains; preload` |
55+
| `X-Frame-Options` | `DENY` |
56+
| `X-Content-Type-Options` | `nosniff` |
57+
| `Referrer-Policy` | `no-referrer` |
58+
| `Permissions-Policy` | All features denied |
59+
| `Cross-Origin-Embedder-Policy` | `require-corp` |
60+
| `Cross-Origin-Opener-Policy` | `same-origin` |
61+
| `Cross-Origin-Resource-Policy` | `same-origin` |
62+
| `X-DNS-Prefetch-Control` | `off` |
63+
| `X-Permitted-Cross-Domain-Policies` | `none` |
64+
| `Content-Security-Policy` | Nonce-based, strict-dynamic, Trusted Types |
65+
| `Server` | _(removed)_ |
66+
67+
### 3. Strict A+ with customization
68+
69+
The preset is intentionally strict. Relax only what your app needs:
70+
71+
```csharp
72+
builder.Services.AddNetSecureHeadersStrictAPlus(opts =>
73+
{
74+
// Allow images from your CDN
75+
opts.Csp = opts.Csp with { ImgSrc = "'self' https://cdn.example.com" };
76+
77+
// Allow API calls to your backend
78+
opts.Csp = opts.Csp with { ConnectSrc = "'self' https://api.example.com" };
79+
80+
// Use strict-origin-when-cross-origin instead of no-referrer
81+
opts.ReferrerPolicyValue = "strict-origin-when-cross-origin";
82+
});
3883
```
3984

40-
## Testing
85+
### 4. Full manual configuration
4186

42-
```bash
43-
dotnet test
87+
For complete control, use `AddNetSecureHeaders` with the fluent CSP builder:
88+
89+
```csharp
90+
using SafeWebCore.Builder;
91+
using SafeWebCore.Extensions;
92+
93+
builder.Services.AddNetSecureHeaders(opts =>
94+
{
95+
opts.EnableHsts = true;
96+
opts.HstsValue = "max-age=31536000; includeSubDomains";
97+
98+
opts.EnableXFrameOptions = true;
99+
opts.XFrameOptionsValue = "SAMEORIGIN";
100+
101+
opts.ReferrerPolicyValue = "strict-origin-when-cross-origin";
102+
103+
// Use the fluent CSP builder
104+
opts.Csp = new CspBuilder()
105+
.DefaultSrc("'none'")
106+
.ScriptSrc("'nonce-{nonce}' 'strict-dynamic' https:")
107+
.StyleSrc("'nonce-{nonce}'")
108+
.ImgSrc("'self' https: data:")
109+
.FontSrc("'self' https://fonts.gstatic.com")
110+
.ConnectSrc("'self' wss://realtime.example.com")
111+
.FrameAncestors("'none'")
112+
.BaseUri("'none'")
113+
.FormAction("'self'")
114+
.UpgradeInsecureRequests()
115+
.Build();
116+
});
117+
```
118+
119+
---
120+
121+
## 🔑 Using CSP Nonces in Razor Views
122+
123+
SafeWebCore generates a unique cryptographic nonce per request. Use it in your scripts and styles:
124+
125+
### With the `[CspNonce]` attribute
126+
127+
```csharp
128+
using SafeWebCore.Attributes;
129+
130+
[CspNonce]
131+
public class HomeController : Controller
132+
{
133+
public IActionResult Index() => View();
134+
}
135+
```
136+
137+
```html
138+
<!-- In your Razor view -->
139+
<script nonce="@ViewData["CspNonce"]">
140+
console.log("This script is allowed by CSP");
141+
</script>
142+
143+
<style nonce="@ViewData["CspNonce"]">
144+
body { font-family: sans-serif; }
145+
</style>
146+
```
147+
148+
### Direct access via `HttpContext.Items`
149+
150+
```csharp
151+
var nonce = HttpContext.Items[NetSecureHeaders.CspNonceKey] as string;
152+
```
153+
154+
---
155+
156+
## 📊 CSP Violation Reporting
157+
158+
Enable the built-in CSP report endpoint to catch policy violations:
159+
160+
```csharp
161+
var app = builder.Build();
162+
163+
app.UseCspReport(); // Handles POST /csp-report
164+
app.UseNetSecureHeaders();
165+
166+
app.Run();
167+
```
168+
169+
Configure the CSP to send reports:
170+
171+
```csharp
172+
builder.Services.AddNetSecureHeadersStrictAPlus(opts =>
173+
{
174+
opts.Csp = opts.Csp with { ReportTo = "default" };
175+
});
44176
```
45177

46-
## Project Structure
178+
Violations are logged at `Warning` level via `ILogger`.
179+
180+
---
181+
182+
## 📁 Project Structure
47183

48184
```
49-
src/
50-
SafeWebCore/ # Main library
51-
tests/
52-
SafeWebCore.Tests/ # Unit tests (xUnit)
53-
docs/ # Documentation
54-
.github/ # GitHub templates and workflows
55-
.editorconfig # Code style settings
56-
Directory.Build.props # Shared MSBuild properties
57-
SafeWebCore.slnx # Solution file
185+
SafeWebCore/
186+
├── src/SafeWebCore/
187+
│ ├── Abstractions/ # IHeaderPolicy interface
188+
│ ├── Attributes/ # [CspNonce] action filter
189+
│ ├── Builder/ # Fluent CspBuilder
190+
│ ├── Constants/ # Header name constants
191+
│ ├── Extensions/ # DI and middleware extensions
192+
│ ├── Infrastructure/ # NonceService, CspReportMiddleware
193+
│ ├── Middleware/ # NetSecureHeadersMiddleware
194+
│ ├── Options/ # NetSecureHeadersOptions, CspOptions
195+
│ └── Presets/ # SecurePresets (Strict A+)
196+
├── tests/SafeWebCore.Tests/ # xUnit v3 tests
197+
├── docs/ # Documentation
198+
└── .github/ # CI, issue templates
58199
```
59200

60-
## Contributing
201+
---
202+
203+
## 📚 Documentation
204+
205+
| Document | Description |
206+
|----------|-------------|
207+
| [Getting Started](docs/getting-started.md) | Installation, first setup, verification |
208+
| [Security Headers](docs/security-headers.md) | Every header explained with rationale |
209+
| [CSP Configuration](docs/csp-configuration.md) | CSP builder, nonces, directives guide |
210+
| [Presets](docs/presets.md) | Strict A+ preset details and customization |
211+
| [Advanced Configuration](docs/advanced-configuration.md) | Custom policies, reporting, per-route config |
212+
213+
---
214+
215+
## 🏗️ Building & Testing
216+
217+
```bash
218+
# Build
219+
dotnet build
220+
221+
# Run tests
222+
dotnet test
223+
224+
# Run tests with coverage
225+
dotnet tool install -g dotnet-coverage
226+
dotnet-coverage collect -f cobertura -o coverage.cobertura.xml dotnet test
227+
```
228+
229+
---
230+
231+
## 🤝 Contributing
61232

62233
See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
63234

64-
## License
235+
## 📄 License
65236

66237
This project is licensed under the MIT License. See [LICENSE](LICENSE) for details.
67238

68-
## Changelog
239+
## 📝 Changelog
69240

70241
See [CHANGELOG.md](CHANGELOG.md) for release history.

SafeWebCore.slnx

Lines changed: 0 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -5,24 +5,4 @@
55
<Folder Name="/tests/">
66
<Project Path="tests/SafeWebCore.Tests/SafeWebCore.Tests.csproj" />
77
</Folder>
8-
<Folder Name="/docs/">
9-
<File Path="docs/README.md" />
10-
</Folder>
11-
<Folder Name="/.github/">
12-
<Folder Name="/.github/ISSUE_TEMPLATE/">
13-
<File Path=".github/ISSUE_TEMPLATE/bug_report.yml" />
14-
<File Path=".github/ISSUE_TEMPLATE/feature_request.yml" />
15-
<File Path=".github/ISSUE_TEMPLATE/config.yml" />
16-
</Folder>
17-
<Folder Name="/.github/PULL_REQUEST_TEMPLATE/">
18-
<File Path=".github/PULL_REQUEST_TEMPLATE/pull_request_template.md" />
19-
</Folder>
20-
</Folder>
21-
<File Path="README.md" />
22-
<File Path="LICENSE" />
23-
<File Path="CONTRIBUTING.md" />
24-
<File Path="CHANGELOG.md" />
25-
<File Path=".gitignore" />
26-
<File Path=".editorconfig" />
27-
<File Path="Directory.Build.props" />
288
</Solution>

docs/README.md

Lines changed: 37 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,47 @@
11
# SafeWebCore Documentation
22

3-
## Overview
3+
Welcome to the SafeWebCore documentation. SafeWebCore is a .NET 10 middleware library that adds security headers to ASP.NET Core applications, targeting an **A+ rating** on [securityheaders.com](https://securityheaders.com) out of the box.
44

5-
SafeWebCore provides middleware and utilities for building secure ASP.NET Core web applications.
5+
---
66

7-
## Modules
7+
## 📖 Table of Contents
88

9-
### CSP Middleware
9+
### Getting Started
1010

11-
Content Security Policy middleware for controlling resource loading policies.
11+
- **[Getting Started](getting-started.md)** — Installation, minimal setup, and verifying your headers
1212

13-
### Security Headers
13+
### Guides
1414

15-
Automatic injection of recommended security response headers.
15+
- **[Security Headers](security-headers.md)** — Every security header explained with values, rationale, and configuration
16+
- **[CSP Configuration](csp-configuration.md)** — Content Security Policy builder, nonces, directives, and common scenarios
17+
- **[Presets](presets.md)** — Strict A+ preset details, customization examples, and when-not-to-use guidance
18+
- **[Advanced Configuration](advanced-configuration.md)** — Custom policies, CSP reporting, middleware ordering, troubleshooting
1619

17-
## API Reference
20+
### Quick Reference
1821

19-
_API documentation will be generated from XML comments._
22+
| I want to... | Go to |
23+
|---------------|-------|
24+
| Get A+ in one line | [Getting Started](getting-started.md) |
25+
| Understand what each header does | [Security Headers](security-headers.md) |
26+
| Configure CSP with nonces | [CSP Configuration](csp-configuration.md) |
27+
| Customize the strict preset | [Presets](presets.md) |
28+
| Add custom headers | [Advanced Configuration](advanced-configuration.md) |
29+
| Set up CSP violation reporting | [Advanced Configuration](advanced-configuration.md#csp-violation-reporting) |
30+
| Fix blocked resources | [Advanced Configuration](advanced-configuration.md#troubleshooting) |
31+
32+
### API Reference
33+
34+
API documentation is generated from XML comments on all public types. Key classes:
35+
36+
| Class | Purpose |
37+
|-------|---------|
38+
| `SecurePresets` | Pre-configured A+ security options |
39+
| `NetSecureHeadersOptions` | All header configuration options |
40+
| `CspOptions` | CSP directive configuration (record) |
41+
| `CspBuilder` | Fluent CSP builder |
42+
| `INonceService` | Nonce generation interface |
43+
| `IHeaderPolicy` | Custom header policy interface |
44+
| `NetSecureHeaders` | Constants (`CspNonceKey`) |
45+
| `ServiceCollectionExtensions` | `AddNetSecureHeaders`, `AddNetSecureHeadersStrictAPlus` |
46+
| `ApplicationBuilderExtensions` | `UseNetSecureHeaders`, `UseCspReport` |
47+
| `CspNonceAttribute` | MVC action filter for nonce injection |

0 commit comments

Comments
 (0)