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

fix(error): strict security headers #2907

Merged
merged 3 commits into from
Nov 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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