Commit Graph
2 Commits
Author SHA1 Message Date
Emil KrebsandMarvin Hagemeister b4bb004753 feat: add CSP and header middleware (#3421)
Added a CSP and header middleware to simplify the HTTP Security Response
Header creation.

Fixes:
- https://github.com/denoland/fresh/issues/1705

Example:

```ts
// main.ts

export const app = new App<State>()
    .use(csp({
        reportTo: '/api/csp-reports',
    }))
    .use(headers({
        'Cross-Origin-Resource-Policy': 'same-site',
        'Cross-Origin-Embedder-Policy': 'require-corp',
        'Cross-Origin-Opener-Policy': 'same-origin',
        'Permissions-Policy':
            'geolocation=(), camera=(), microphone=(), payment=(), usb=(), bluetooth=(), magnetometer=(), gyroscope=(), accelerometer=()',
        'Referrer-Policy': 'strict-origin-when-cross-origin',
        'X-Content-Type-Options': 'nosniff',
        'X-Frame-Options': 'DENY',
        'Strict-Transport-Security': 'max-age=63072000; includeSubDomains; preload',
    }))
```

Endpoint example:
```ts
// routes/api/csp-handler.ts

import { Context } from 'fresh';
import { State } from '../../main.ts';

export const handler = {
    async POST(ctx: Context<State>) {
        try {
            const text = await ctx.req.text();
            const body = JSON.parse(text);

            const logEntry = {
                timestamp: new Date().toISOString(),
                report: body,
                userAgent: ctx.req.headers.get('user-agent') || 'unknown',
            };
            await Deno.writeFile('csp-reports.log', new TextEncoder().encode(JSON.stringify(logEntry) + '\n'), { append: true });

            return new Response(JSON.stringify({ status: "ok" }), { status: 200 });
        } catch (error) {
            console.error("Error handling CSP report:", error);
            return new Response(JSON.stringify({ status: "error", error: String(error) }), { status: 500 });
        }
    },
};

```

Implementing these headers improved the security report at [Security
Headers](securityheaders.com) from F to A and helps to prevent security
vulnerabilities like Cross-Site Scripting and Clickjacking.

**Before**
<img width="1200" height="308" alt="image"
src="https://github.com/user-attachments/assets/01adfff4-5bb4-4cc6-bd8f-5e74b471301b"
/>
**After**
<img width="1200" height="335" alt="image"
src="https://github.com/user-attachments/assets/c5a9b07e-babf-4797-b47d-4368de70cbc3"
/>

---------

Co-authored-by: Marvin Hagemeister <marvin@deno.com>
2025-09-15 12:20:22 +02:00
Marvin Hagemeister 79d8cfc3ed docs: make 2.x the default version (#3369) 2025-09-09 14:36:51 +02:00