website/routes/_middleware.ts

40 lines
2 KiB
TypeScript
Raw Normal View History

import { FreshContext } from '$fresh/server.ts'
2024-07-09 11:00:35 +02:00
import { useCsp } from ':src/csp/middleware.ts'
import { SessionStore } from ':src/session/mod.ts'
import { useSession } from ':src/session/middleware.ts'
export async function handler(request: Request, ctx: FreshContext) {
// Update fresh context state with session
ctx.state = { ...ctx.state, session: SessionStore.getFromRequest(request) }
// Get response
const response = await ctx.next()
//Add security headers
// See https://developer.mozilla.org/en-US/docs/Web/Security/Practical_implementation_guides/TLS#http_strict_transport_security
response.headers.set('Strict-Transport-Security', 'max-age=63072000; includeSubDomains; preload')
response.headers.set('Content-Security-Policy', "frame-ancestors 'none'; upgrade-insecure-requests")
//See https://developer.mozilla.org/en-US/docs/Web/Security/Practical_implementation_guides/Referrer_policy
response.headers.set('Referrer-Policy', 'no-referrer, strict-origin-when-cross-origin')
//See https://developer.mozilla.org/en-US/docs/Web/Security/Practical_implementation_guides/MIME_types
response.headers.set('X-Content-Type-Options', 'nosniff')
//See https://developer.mozilla.org/en-US/docs/Web/Security/Practical_implementation_guides/Clickjacking
response.headers.set('X-Frame-Options', 'DENY')
//See https://developer.mozilla.org/en-US/docs/Web/Security/Practical_implementation_guides/CORP
response.headers.set('Cross-Origin-Resource-Policy', 'same-origin')
//See https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity
//? SRI plugin for non local resources only ?
//See https://developer.mozilla.org/en-US/docs/Web/Security/Practical_implementation_guides/CSP
//? fresh useCSP https://fresh.deno.dev/docs/examples/using-csp
2024-07-09 11:00:35 +02:00
await useCsp(request, response, ctx)
useSession(request, response, ctx)
2024-07-09 11:00:35 +02:00
// Allow service worker to serve root scope
if (ctx.url.pathname.endsWith('island-startserviceworker.js')) {
response.headers.set('Service-Worker-Allowed', '/')
}
2024-06-13 12:20:47 +02:00
return response
}