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>
Fresh
Fresh is a small, fast and extensible full stack web framework built on Web Standards. It’s designed for building high-quality, performant, and personalized web applications.