Files
sweet/docs/toc.ts
T
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

181 lines
5.7 KiB
TypeScript

import FRESH_VERSIONS_1x from "../versions.json" with { type: "json" };
import LATEST_VERSION_2 from "../packages/fresh/deno.json" with {
type: "json",
};
type RawTableOfContents = Record<
string,
{
label: string;
content: Record<string, RawTableOfContentsEntry>;
}
>;
interface RawTableOfContentsEntry {
title: string;
link?: string;
pages?: [string, string, string?][];
}
const toc: RawTableOfContents = {
latest: {
label: LATEST_VERSION_2.version,
content: {
introduction: {
title: "Introduction",
link: "latest",
},
"getting-started": {
title: "Getting Started",
link: "latest",
},
concepts: {
title: "Concepts",
link: "latest",
pages: [
["app", "App", "link:latest"],
["middleware", "Middlewares", "link:latest"],
["context", "Context", "link:latest"],
["routing", "Routing", "link:latest"],
["islands", "Islands", "link:latest"],
["static-files", "Static files", "link:latest"],
["file-routing", "File routing", "link:latest"],
],
},
advanced: {
title: "Advanced",
link: "latest",
pages: [
["app-wrapper", "App wrapper", "link:latest"],
["layouts", "Layouts", "link:latest"],
["error-handling", "Error handling", "link:latest"],
["partials", "Partials", "link:latest"],
["forms", "Forms", "link:latest"],
["define", "Define Helpers", "link:latest"],
["environment-variables", "Environment Variables", "link:latest"],
["head", "Modifying <head>", "link:latest"],
["vite", "Vite Plugin Options", "link:latest"],
["troubleshooting", "Troubleshooting", "link:latest"],
["builder", "Builder (Legacy)", "link:latest"],
],
},
deployment: {
title: "Deployment",
link: "latest",
pages: [
["deno-deploy", "Deno Deploy", "link:latest"],
["deno-compile", "deno compile", "link:latest"],
["docker", "Docker", "link:latest"],
["cloudflare-workers", "Cloudflare Workers", "link:latest"],
],
},
testing: {
title: "Testing",
link: "latest",
},
plugins: {
title: "Plugins",
link: "latest",
pages: [
["cors", "cors", "link:latest"],
["csrf", "csrf", "link:latest"],
["csp", "csp", "link:latest"],
["trailing-slashes", "trailingSlashes", "link:latest"],
],
},
examples: {
title: "Examples",
link: "latest",
pages: [
["migration-guide", "Migration Guide", "link:latest"],
["daisyui", "daisyUI", "link:latest"],
["markdown", "Rendering Markdown", "link:latest"],
["rendering-raw-html", "Rendering raw HTML", "link:latest"],
[
"sharing-state-between-islands",
"Sharing state between islands",
"link:latest",
],
["active-links", "Active links", "link:latest"],
],
},
},
},
"1.x": {
label: FRESH_VERSIONS_1x[0],
content: {
introduction: {
title: "Introduction",
},
"getting-started": {
title: "Getting Started",
pages: [
["create-a-project", "Create a project"],
["running-locally", "Running locally"],
["create-a-route", "Create a route"],
["dynamic-routes", "Dynamic routes"],
["custom-handlers", "Custom handlers"],
["form-submissions", "Form submissions"],
["adding-interactivity", "Adding interactivity"],
["deploy-to-production", "Deploy to production"],
],
},
concepts: {
title: "Concepts",
pages: [
["architecture", "Architecture"],
["server-components", "Server Components"],
["routing", "Routing"],
["routes", "Routes"],
["app-wrapper", "App wrapper"],
["layouts", "Layouts"],
["forms", "Forms"],
["islands", "Interactive islands"],
["static-files", "Static files"],
["middleware", "Middlewares"],
["error-pages", "Error pages"],
["partials", "Partials"],
["data-fetching", "Data fetching"],
["ahead-of-time-builds", "Ahead-of-time Builds"],
["deployment", "Deployment"],
["plugins", "Plugins"],
["updating", "Updating Fresh"],
["server-configuration", "Server configuration"],
],
},
integrations: {
title: "Integrations",
},
examples: {
title: "Examples",
pages: [
["migrating-to-tailwind", "Migrating to Tailwind"],
["modifying-the-head", "Modifying the <head>"],
["writing-tests", "Writing tests"],
["changing-the-src-dir", "Changing the source directory"],
["using-twind-v1", "Using Twind v1"],
["init-the-server", "Initializing the server"],
["using-fresh-canary-version", "Using Fresh canary version"],
["dealing-with-cors", "Dealing with CORS"],
["creating-a-crud-api", "Creating a CRUD API"],
["handling-complex-routes", "Handling complex routes"],
["rendering-markdown", "Rendering markdown"],
["rendering-raw-html", "Rendering raw HTML"],
["sharing-state-between-islands", "Sharing state between islands"],
["using-csp", "Using CSP"],
["active-links", "Styling active links"],
[
"client-side-components-and-libraries",
"Client only side components",
],
],
},
},
},
};
export default toc;