import { describe, it, expect } from "vitest"; import { contentSecurityPolicy, newNonce } from "./contentSecurityPolicy"; // portal-script-nonce-csp (F30): page responses allow only scripts that carry the per-request nonce. function directives(policy: string): Map { return new Map( policy.split(";").map(d => d.trim()).filter(Boolean).map(d => { const [name, ...values] = d.split(/\s+/); return [name, values] as [string, string[]]; }), ); } describe("contentSecurityPolicy", () => { it("keeps the baseline directives", () => { const d = directives(contentSecurityPolicy("abc", false)); expect(d.get("frame-ancestors")).toEqual(["'self'"]); expect(d.get("object-src")).toEqual(["'none'"]); expect(d.get("base-uri")).toEqual(["'self'"]); }); it("allows only nonce-bearing scripts in production", () => { const d = directives(contentSecurityPolicy("abc", false)); expect(d.get("script-src")).toEqual(["'self'", "'nonce-abc'", "'strict-dynamic'"]); }); it("adds 'unsafe-eval' only for the dev server", () => { expect(directives(contentSecurityPolicy("abc", true)).get("script-src")).toContain("'unsafe-eval'"); expect(directives(contentSecurityPolicy("abc", false)).get("script-src")).not.toContain("'unsafe-eval'"); }); it("never allows inline scripts", () => { for (const dev of [true, false]) { expect(directives(contentSecurityPolicy("abc", dev)).get("script-src")).not.toContain("'unsafe-inline'"); } }); }); describe("newNonce", () => { it("is base64 of at least 16 random bytes", () => { const n = newNonce(); expect(n).toMatch(/^[A-Za-z0-9+/]+={0,2}$/); expect(atob(n).length).toBeGreaterThanOrEqual(16); }); it("differs per call", () => { const seen = new Set(Array.from({ length: 50 }, () => newNonce())); expect(seen.size).toBe(50); }); });