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>
This commit is contained in:
Emil Krebs
2025-09-15 12:20:22 +02:00
committed by GitHub
co-authored by Marvin Hagemeister
parent f9ba5417c4
commit b4bb004753
5 changed files with 158 additions and 0 deletions
+31
View File
@@ -0,0 +1,31 @@
---
description: "Set Content-Security-Policy (CSP) HTTP headers with the csp middleware"
---
The `csp()` middleware can be used to add
[Content-Security-Policy headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CSP)
to HTTP requests. These restrict which resources a document is allowed to load.
```ts main.ts
import { csp } from "fresh";
const app = new App()
.use(csp({
// If true, sets Content-Security-Policy-Report-Only header instead
// of Content-Security-Policy
reportOnly: true,
// If set, adds Reporting-Endpoints, report-to, and report-uri
// directive.
reportTo: "/api/csp-reports",
// Additional CSP directives to add or override the defaults
csp: [
"script-src 'self' 'unsafe-inline' 'https://example.com'",
],
}))
.get("/", () => new Response("hello"));
```
## Options
See the [API docs](https://jsr.io/@fresh/core/doc/~/csp) for a list of all
supported options.
+1
View File
@@ -82,6 +82,7 @@ const toc: RawTableOfContents = {
pages: [
["cors", "cors", "link:latest"],
["csrf", "csrf", "link:latest"],
["csp", "csp", "link:latest"],
["trailing-slashes", "trailingSlashes", "link:latest"],
],
},
+67
View File
@@ -0,0 +1,67 @@
import type { Middleware } from "./mod.ts";
/** Options for Content-Security-Policy middleware */
export interface CSPOptions {
/** If true, sets Content-Security-Policy-Report-Only header instead of Content-Security-Policy */
reportOnly?: boolean;
/** If set, adds Reporting-Endpoints, report-to, and report-uri directive */
reportTo?: string;
/** Additional CSP directives to add or override the defaults */
csp?: string[];
}
/** Middleware to set Content-Security-Policy headers
* @param options - CSP options
* @example
* app.use(csp({
* reportOnly: true,
* reportTo: '/api/csp-reports',
* csp: [
* "script-src 'self' 'unsafe-inline' 'https://example.com'",
* ],
* }));
*/
export function csp<State>(options: CSPOptions = {}): Middleware<State> {
const {
reportOnly = false,
reportTo,
csp = [],
} = options;
const defaultCsp = [
"default-src 'self'",
"script-src 'self' 'unsafe-inline'", // unsafe-inline needed for fresh
"style-src 'self' 'unsafe-inline'",
"font-src 'self'",
"img-src 'self' data:",
"media-src 'self' data: blob:",
"worker-src 'self' blob:",
"connect-src 'self'",
"object-src 'none'",
"base-uri 'self'",
"form-action 'self'",
"frame-ancestors 'none'",
"upgrade-insecure-requests",
];
const cspDirectives = [...defaultCsp, ...csp];
if (reportTo) {
cspDirectives.push(`report-to csp-endpoint`);
cspDirectives.push(`report-uri ${reportTo}`); // deprecated but some browsers still use it
}
const cspString = cspDirectives.join("; ");
return async (ctx) => {
const res = await ctx.next();
const headerName = reportOnly
? "Content-Security-Policy-Report-Only"
: "Content-Security-Policy";
res.headers.set(headerName, cspString);
if (reportTo) {
res.headers.set("Reporting-Endpoints", `csp-endpoint="${reportTo}"`);
}
return res;
};
}
@@ -0,0 +1,58 @@
import { expect } from "@std/expect/expect";
import { App } from "../app.ts";
import { csp } from "./csp.ts";
Deno.test("CSP - GET default", async () => {
const handler = new App()
.use(csp())
.get("/", () => new Response("ok"))
.handler();
const res = await handler(new Request("https://localhost/"));
expect(res.status).toBe(200);
expect(res.headers.get("Content-Security-Policy")).toBeDefined();
expect(res.headers.get("Content-Security-Policy")).toContain(
"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data:; media-src 'self' data: blob:; worker-src 'self' blob:; connect-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests",
);
});
Deno.test("CSP - GET with override options", async () => {
const handler = new App()
.use(csp({
reportTo: "/api/csp-reports",
csp: [
"font-src 'self' 'https://fonts.gstatic.com'",
"style-src 'self' 'https://fonts.googleapis.com'",
],
}))
.get("/", () => new Response("ok"))
.handler();
const res = await handler(new Request("https://localhost/"));
expect(res.status).toBe(200);
expect(res.headers.get("Content-Security-Policy")).toContain(
"font-src 'self' 'https://fonts.gstatic.com'; style-src 'self' 'https://fonts.googleapis.com'",
);
expect(res.headers.get("Content-Security-Policy")).toContain(
"report-uri /api/csp-reports",
);
expect(res.headers.get("Reporting-Endpoints")).toBe(
'csp-endpoint="/api/csp-reports"',
);
});
Deno.test("CSP - GET report only", async () => {
const handler = new App()
.use(csp({
reportOnly: true,
}))
.get("/", () => new Response("ok"))
.handler();
const res = await handler(new Request("https://localhost/"));
expect(res.status).toBe(200);
expect(res.headers.get("Content-Security-Policy-Report-Only")).toBeDefined();
expect(res.headers.get("Content-Security-Policy-Report-Only")).toContain(
"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data:; media-src 'self' data: blob:; worker-src 'self' blob:; connect-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests",
);
});
+1
View File
@@ -13,6 +13,7 @@ export type { Middleware, MiddlewareFn } from "./middlewares/mod.ts";
export { staticFiles } from "./middlewares/static_files.ts";
export { csrf, type CsrfOptions } from "./middlewares/csrf.ts";
export { cors, type CORSOptions } from "./middlewares/cors.ts";
export { csp, type CSPOptions } from "./middlewares/csp.ts";
export type { FreshConfig, ResolvedFreshConfig } from "./config.ts";
export type { Context, FreshContext, Island } from "./context.ts";
export { createDefine, type Define } from "./define.ts";