Files
sweet/packages/fresh/src/middlewares/csp.ts
T
Christian Svensson ffa845ab0d docs(core): correct example code block formatting (#3601)
The example for the CSP middleware looks a bit broken currently on JSR,
due to the `@example` markdown is not wrapped in a code block.

<img width="1136" height="247" alt="image"
src="https://github.com/user-attachments/assets/57888033-aa9e-4701-87dc-4f4810365177"
/>

## Changes

- Improves formatting a bit, to be less compact
- Wraps the example in a code block ` ```ts `
- Adds a title to the `@example` - "Basic usage" - To avoid the example
being labeled as "Example1" on JSR
2025-11-04 16:03:51 +01:00

73 lines
1.9 KiB
TypeScript

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 Basic usage
* ```ts
* 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;
};
}