feat(core-shared): add TanStack Start security header adapter

Exports withSecurityHeaders() and getNonce() from the
./security/tanstack subpath. withSecurityHeaders() returns all six
security headers plus x-nonce for use inside a TanStack/Nitro H3
server middleware; getNonce() reads x-nonce from the node request
headers forwarded by that middleware.

Mirrors the ./security/next adapter pattern while staying free of
any @tanstack/start dependency — the adapter works with plain H3
IncomingMessage types that TanStack Start exposes at wiring time
(Story 09).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-05-20 09:56:03 +00:00
parent 6903c59cc7
commit a48af7e91c
7 changed files with 143 additions and 21 deletions

View File

@@ -0,0 +1,52 @@
import { describe, it, expect, vi } from "vitest";
import { withSecurityHeaders } from "@/security/tanstack/middleware";
const ALL_SIX_HEADERS = [
"Strict-Transport-Security",
"X-Frame-Options",
"X-Content-Type-Options",
"Referrer-Policy",
"Permissions-Policy",
"Content-Security-Policy",
] as const;
describe("withSecurityHeaders", () => {
it("returns all six security headers", () => {
const { headers } = withSecurityHeaders();
for (const header of ALL_SIX_HEADERS) {
expect(headers).toHaveProperty(header);
}
});
it("returns x-nonce in headers equal to the returned nonce", () => {
const { headers, nonce } = withSecurityHeaders();
expect(headers["x-nonce"]).toBe(nonce);
expect(typeof nonce).toBe("string");
expect(nonce.length).toBeGreaterThan(0);
});
it("nonce in x-nonce matches nonce threaded into CSP in production mode", () => {
vi.stubEnv("NODE_ENV", "production");
const { headers, nonce } = withSecurityHeaders();
expect(headers["Content-Security-Policy"]).toContain(`'nonce-${nonce}'`);
});
it("uses dev-mode CSP when NODE_ENV is not production", () => {
vi.stubEnv("NODE_ENV", "test");
const { headers } = withSecurityHeaders();
expect(headers["Content-Security-Policy"]).toContain("'unsafe-inline'");
});
it("each call produces a unique nonce", () => {
const a = withSecurityHeaders();
const b = withSecurityHeaders();
expect(a.nonce).not.toBe(b.nonce);
});
});