Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: harden headers security #592

Merged
merged 10 commits into from
Sep 22, 2023
36 changes: 36 additions & 0 deletions middleware/headers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Copyright 2023 the Deno authors. All rights reserved. MIT license.
import type { MiddlewareHandlerContext } from "$fresh/server.ts";

export async function hardenHeaders(
Jabolol marked this conversation as resolved.
Show resolved Hide resolved
req: Request,
ctx: MiddlewareHandlerContext,
) {
const response = await ctx.next();
const path = new URL(req.url).pathname.split("/")[1] || "/";
const blacklist = [/api/];

if (blacklist.some((regex) => regex.test(path))) {
return response;
}
Jabolol marked this conversation as resolved.
Show resolved Hide resolved

const contentSecurityPolicy = [
"default-src 'self'",
"img-src 'self' https://avatars.githubusercontent.com",
"frame-ancestors 'self'",
"script-src 'self' 'unsafe-inline';",
"style-src 'self' 'unsafe-inline'",
"object-src 'none'",
];

response.headers.set(
"Content-Security-Policy",
contentSecurityPolicy.join("; "),
);
response.headers.set("Strict-Transport-Security", "max-age=63072000;");
response.headers.set("Referrer-Policy", "strict-origin-when-cross-origin");
response.headers.set("X-Content-Type-Options", "nosniff");
response.headers.set("X-Frame-Options", "SAMEORIGIN");
response.headers.set("X-XSS-Protection", "1; mode=block");

return response;
}
2 changes: 2 additions & 0 deletions routes/_middleware.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Copyright 2023 the Deno authors. All rights reserved. MIT license.
import { setSessionState } from "@/middleware/session.ts";
import { hardenHeaders } from "@/middleware/headers.ts";

export const handler = [
setSessionState,
hardenHeaders,
];
Loading