Skip to content
Open
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
50 changes: 50 additions & 0 deletions src/lib/security-headers.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { describe, expect, it } from "vite-plus/test";

import { securityHeaders, withSecurityHeaders } from "./security-headers";

describe("securityHeaders", () => {
it("forbids framing and sniffing and sends HSTS on an https origin", () => {
expect(
Object.fromEntries(securityHeaders("https://auth.polinetwork.org", new Headers())),
).toEqual({
"X-Frame-Options": "DENY",
"Content-Security-Policy": "frame-ancestors 'none'; base-uri 'self'; object-src 'none'",
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "strict-origin-when-cross-origin",
"Strict-Transport-Security": "max-age=31536000; includeSubDomains",
});
});

it("leaves HSTS out on an http origin", () => {
const names = securityHeaders("http://localhost:3003", new Headers()).map(([name]) => name);
expect(names).not.toContain("Strict-Transport-Security");
expect(names).toContain("X-Frame-Options");
});

it("keeps a policy the response already has", () => {
const existing = new Headers({ "Content-Security-Policy": "default-src 'none'" });
const names = securityHeaders("https://auth.polinetwork.org", existing).map(([name]) => name);
expect(names).not.toContain("Content-Security-Policy");
expect(names).toContain("X-Frame-Options");
});
});

describe("withSecurityHeaders", () => {
it("adds the headers without touching the ones already there", () => {
const response = new Response("{}", {
headers: { "Cache-Control": "no-store", "Access-Control-Allow-Origin": "*" },
});
const result = withSecurityHeaders(response, "https://auth.polinetwork.org");
expect(result.headers.get("X-Frame-Options")).toBe("DENY");
expect(result.headers.get("Cache-Control")).toBe("no-store");
expect(result.headers.get("Access-Control-Allow-Origin")).toBe("*");
});

it("copies a response whose headers cannot change", async () => {
const response = Response.redirect("https://example.com/", 302);
const result = withSecurityHeaders(response, "https://auth.polinetwork.org");
expect(result.status).toBe(302);
expect(result.headers.get("Location")).toBe("https://example.com/");
expect(result.headers.get("X-Frame-Options")).toBe("DENY");
});
});
36 changes: 36 additions & 0 deletions src/lib/security-headers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/**
* Headers every response carries. No other site may frame these pages: the session cookie
* is SameSite=Lax, so a page on another polinetwork.org subdomain could otherwise frame the
* consent and sign-out pages with the person signed in and trick them into clicking.
*
* The policy stops at framing, base and plugins on purpose. `form-action` would block the
* sign-out form, which is redirected to the application's own address, and `script-src`
* would block the inline theme script and the hydration scripts.
*/
export function securityHeaders(publicOrigin: string, existing: Headers): [string, string][] {
const headers: [string, string][] = [
["X-Frame-Options", "DENY"],
["Content-Security-Policy", "frame-ancestors 'none'; base-uri 'self'; object-src 'none'"],
["X-Content-Type-Options", "nosniff"],
["Referrer-Policy", "strict-origin-when-cross-origin"],
];
// Only on https: local development runs on http://localhost.
if (new URL(publicOrigin).protocol === "https:") {
headers.push(["Strict-Transport-Security", "max-age=31536000; includeSubDomains"]);
}
// A header the handler already chose, such as a stricter policy, stays as it is.
return headers.filter(([name]) => !existing.has(name));
}

/** Adds the headers, copying the response when its headers cannot be changed. */
export function withSecurityHeaders(response: Response, publicOrigin: string): Response {
const headers = securityHeaders(publicOrigin, response.headers);
try {
for (const [name, value] of headers) response.headers.set(name, value);
return response;
} catch {
const copy = new Response(response.body, response);
for (const [name, value] of headers) copy.headers.set(name, value);
return copy;
}
}
21 changes: 21 additions & 0 deletions src/nitro/security-headers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { definePlugin } from "nitro";

import { env } from "../env";
import { securityHeaders } from "../lib/security-headers";

/**
* Files from `public/` and Nitro's own error pages never reach the request middleware in
* `src/start.ts`, so they get the same headers here. Responses from the app already have
* them, and a header that is already set is left alone.
*/
export default definePlugin((nitroApp) => {
nitroApp.hooks.hook("response", (response) => {
try {
for (const [name, value] of securityHeaders(env.BETTER_AUTH_URL, response.headers)) {
response.headers.set(name, value);
}
} catch {
// Headers that cannot change only come from the app, which set them already.
}
});
});
13 changes: 12 additions & 1 deletion src/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
} from "@tanstack/react-start";
import { getResponseStatus } from "@tanstack/react-start/server";
import { actionErrorAdapter } from "@/lib/action-error";
import { withSecurityHeaders } from "@/lib/security-headers";
import { env } from "@/env";

/** The public origin, not the one the request reached this process with behind the proxy. */
Expand Down Expand Up @@ -35,7 +36,17 @@ const refusalStatusMiddleware = createMiddleware().server(async ({ next, handler
return { ...result, response: new Response(body, { status, headers }) };
});

/**
* Pages, server functions and server routes all pass through here. It runs first so it sees
* the response the other middleware produced.
*/
const securityHeadersMiddleware = createMiddleware().server(async ({ next }) => {
const result = await next();
const response = withSecurityHeaders(result.response, trustedOrigin());
return response === result.response ? result : { ...result, response };
});

export const startInstance = createStart(() => ({
requestMiddleware: [csrfMiddleware, refusalStatusMiddleware],
requestMiddleware: [securityHeadersMiddleware, csrfMiddleware, refusalStatusMiddleware],
serializationAdapters: [actionErrorAdapter],
}));
1 change: 1 addition & 0 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ const config = defineConfig({
// BetterAuthError is initialized, and every auth route returns 500.
inlineDynamicImports: true,
rollupConfig: { external: [/^@sentry\//] },
plugins: ["./src/nitro/security-headers.ts"],
}),
tailwindcss(),
tanstackStart(),
Expand Down
Loading