Skip to content

Commit

Permalink
fix(error): strict security headers (#2907)
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 authored Nov 27, 2024
1 parent 6c3d16e commit 65c444b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
19 changes: 18 additions & 1 deletion src/runtime/internal/error.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
// import ansiHTML from 'ansi-html'
import { send, setResponseHeader, setResponseStatus } from "h3";
import {
send,
setResponseHeader,
setResponseHeaders,
setResponseStatus,
} from "h3";
import type { NitroErrorHandler } from "nitropack/types";
import { isJsonRequest, normalizeError } from "./utils";

Expand Down Expand Up @@ -56,6 +61,18 @@ export default defineNitroErrorHandler(
setResponseHeader(event, "Cache-Control", "no-cache");
}

// Security headers
setResponseHeaders(event, {
// Disable the execution of any js
"Content-Security-Policy": "script-src 'none'; frame-ancestors 'none';",
// Prevent browser from guessing the MIME types of resources.
"X-Content-Type-Options": "nosniff",
// Prevent error page from being embedded in an iframe
"X-Frame-Options": "DENY",
// Prevent browsers from sending the Referer header
"Referrer-Policy": "no-referrer",
});

setResponseStatus(event, statusCode, statusMessage);

if (isJsonRequest(event)) {
Expand Down
9 changes: 8 additions & 1 deletion test/tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -378,13 +378,20 @@ export function testNitro(
});

it("handles errors", async () => {
const { status } = await callHandler({
const { status, headers } = await callHandler({
url: "/api/error",
headers: {
Accept: "application/json",
},
});
expect(status).toBe(503);
expect(headers).toMatchObject({
"content-type": "application/json",
"content-security-policy": "script-src 'none'; frame-ancestors 'none';",
"referrer-policy": "no-referrer",
"x-content-type-options": "nosniff",
"x-frame-options": "DENY",
});
});

it.skipIf(isWindows && ctx.preset === "nitro-dev")(
Expand Down

0 comments on commit 65c444b

Please sign in to comment.