AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
feat(ui): a nonce Content-Security-Policy on every page (#623)
ladislav-urban85b5945c3c91
diff --git a/docs/auth.md b/docs/auth.mdindex d52c3f39..c98a53d9 100644--- a/docs/auth.md+++ b/docs/auth.md@@ -61,6 +61,23 @@ Browser ──► exec.example.com (UI) ──► (middleware: session check)route handler```+### Pages' security headers++The UI's middleware also sets a Content-Security-Policy on every page, so it now runs on+`/signin` and Auth.js's routes too; they still skip the session check+([`middlewarePaths.ts`](../packages/ui/src/lib/middlewarePaths.ts)):++- **Scripts** run only with the response's nonce (`script-src 'self' 'nonce-…' 'strict-dynamic'`),+ plus `'unsafe-eval'` on the dev server for React's dev build. A script injected into a page+ (text from an outside source rendered as HTML, a dependency gone wrong) doesn't run.+- **No plugins and no foreign `<base>`** (`object-src 'none'`, `base-uri 'self'`).+- **No framing by other sites** (`frame-ancestors 'self'`), so no other page can show the app's+ Approve and Send buttons under its own. Auth.js's own pages get this header alone.++Every page renders per request (the root layout awaits `connection()`), because a page built+ahead of time would carry no nonce and the policy would stop its scripts. See+[`lib/csp.ts`](../packages/ui/src/lib/csp.ts).+### Exempt paths (API)These bypass the shared-secret check because they're hit by external services that authenticate themselves:diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex fb3a753d..dea8ed07 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -7801,6 +7801,15 @@ auth:local-login change: removed users kept working until theirJWT expired. /signin bounces a visitor onward only when`sessionStillAllowed` agrees, or a refused session would loop.+ Pages' security headers (packages/ui/src/middleware.ts, lib/csp.ts):+ every request but Next's static files and the favicon runs the+ middleware, /signin and Auth.js's routes included (they skip only the+ session check, SESSION_FREE_PATH in lib/middlewarePaths.ts). Every page+ gets Content-Security-Policy script-src 'self' 'nonce-…'+ 'strict-dynamic' (+ 'unsafe-eval' on the dev server only), object-src+ 'none', base-uri 'self', frame-ancestors 'self'; Auth.js's own HTML+ pages get frame-ancestors 'self' alone. The root layout awaits+ connection() so every page renders per request and carries its nonce.Local login (packages/ui/src/lib/localLogin.ts): `make dev` withneither Google nor SSO sign-in set up starts the UI with `-H 127.0.0.1` andOE_LOCAL_LOGIN=1 in one recipe line (the flag alone would handdiff --git a/packages/ui/scripts/csp.test.mjs b/packages/ui/scripts/csp.test.mjsnew file mode 100644index 00000000..7c6d5024--- /dev/null+++ b/packages/ui/scripts/csp.test.mjs@@ -0,0 +1,48 @@+// The pages' Content-Security-Policy (lib/csp.ts, set by src/middleware.ts).+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import { contentSecurityPolicy, makeNonce } from "../src/lib/csp.ts";++const directives = (policy) =>+ Object.fromEntries(policy.split(";").map((d) => d.trim().split(/\s+/)).map(([name, ...values]) => [name, values]));++test("scripts need this response's nonce; nothing inline or eval'd", () => {+ const nonce = makeNonce();+ const policy = directives(contentSecurityPolicy({ nonce, devServer: false }));+ assert.deepEqual(policy["script-src"], ["'self'", `'nonce-${nonce}'`, "'strict-dynamic'"]);+ assert.deepEqual(policy["object-src"], ["'none'"]);+ assert.deepEqual(policy["base-uri"], ["'self'"]);+ const all = Object.values(policy).flat();+ assert.ok(!all.includes("'unsafe-inline'") && !all.includes("'unsafe-eval'"));+});++test("only the dev server allows eval, for React's dev build", () => {+ const policy = directives(contentSecurityPolicy({ nonce: makeNonce(), devServer: true }));+ assert.ok(policy["script-src"].includes("'unsafe-eval'"));+ assert.ok(!policy["script-src"].includes("'unsafe-inline'"));+});++test("no other site may frame the pages", () => {+ const policy = directives(contentSecurityPolicy({ nonce: makeNonce(), devServer: false }));+ assert.deepEqual(policy["frame-ancestors"], ["'self'"]);+});++test("every nonce is fresh and well formed", () => {+ const a = makeNonce();+ assert.notEqual(a, makeNonce());+ assert.equal(Buffer.from(a, "base64").length, 16);+ assert.throws(() => contentSecurityPolicy({ nonce: "x'; script-src *", devServer: false }));+});++test("every page renders on request, so each gets its own nonce", () => {+ // A page built ahead of time would carry no nonce, and the policy would+ // stop its scripts: the root layout waits for the request.+ const layout = readFileSync(new URL("../src/app/layout.tsx", import.meta.url), "utf8");+ assert.match(layout, /await connection\(\)/);+ // What the middleware does with the policy is tested with a stub session+ // check in pageGate.test.mjs; here, only that it is wired to lib/pageGate.ts.+ const middleware = readFileSync(new URL("../src/middleware.ts", import.meta.url), "utf8");+ assert.match(middleware, /return gatePage\(/);+ assert.match(middleware, /csp: \(\) => contentSecurityPolicy\(\{ nonce: makeNonce\(\), devServer: DEV_SERVER \}\)/);+});diff --git a/packages/ui/scripts/middleware-matcher.test.mjs b/packages/ui/scripts/middleware-matcher.test.mjsindex 63b4a2c6..ba34d3e7 100644--- a/packages/ui/scripts/middleware-matcher.test.mjs+++ b/packages/ui/scripts/middleware-matcher.test.mjs@@ -1,7 +1,9 @@-// Which paths the auth middleware skips.+// Which paths the middleware skips, and which it lets through without a+// session.//// `config.matcher` in src/middleware.ts is a negative lookahead: every entry-// in it is a path the session check never sees. An entry with no terminator+// in it is a path the middleware never sees (and so gets neither the session+// check nor the pages' security headers). An entry with no terminator// excludes every path that merely *starts with* it — `api/auth` used to skip// `/api/authorizations`, and `favicon.ico` skipped `/favicon.icoX` and (the dot// being unescaped) `/faviconXico` — so a future route with such a prefix would@@ -18,6 +20,7 @@ import assert from "node:assert/strict";import { readFileSync } from "node:fs";import { createRequire } from "node:module";import test from "node:test";+import { SESSION_FREE_PATH } from "../src/lib/middlewarePaths.ts";const require = createRequire(import.meta.url);const { getMiddlewareMatchers } = require("next/dist/build/analysis/get-page-static-info.js");@@ -31,18 +34,26 @@ assert.ok(literal, "could not find a single string literal in middleware.ts confconst matcher = getMiddlewareRouteMatcher(getMiddlewareMatchers([JSON.parse(literal[1])], {}));const runsMiddleware = (pathname) => matcher(pathname, { headers: {}, cookies: {} }, {});-test("Auth.js routes, static assets and the sign-in page skip the middleware", () => {+const gated = (pathname) => runsMiddleware(pathname) && !SESSION_FREE_PATH.test(pathname);++test("static assets skip the middleware", () => {+ for (const path of ["/favicon.ico", "/_next/static/chunks/main.js", "/_next/image"]) {+ assert.equal(runsMiddleware(path), false, path);+ }+});++test("Auth.js routes and the sign-in page need no session but still get the middleware", () => {for (const path of ["/api/auth","/api/auth/","/api/auth/session","/api/auth/providers","/api/auth/callback/google",- "/favicon.ico",- "/_next/static/chunks/main.js","/signin",+ "/signin/",]) {- assert.equal(runsMiddleware(path), false, path);+ assert.equal(runsMiddleware(path), true, path);+ assert.equal(gated(path), false, path);}});@@ -55,13 +66,14 @@ test("a path that only starts with an excluded entry is still gated", () => {"/faviconXico","/favicon.ico/x","/signin-help",+ "/signin/done",]) {- assert.equal(runsMiddleware(path), true, path);+ assert.equal(gated(path), true, path);}});test("ordinary pages and API routes are gated", () => {for (const path of ["/", "/settings", "/api/backend/health"]) {- assert.equal(runsMiddleware(path), true, path);+ assert.equal(gated(path), true, path);}});diff --git a/packages/ui/scripts/pageGate.test.mjs b/packages/ui/scripts/pageGate.test.mjsnew file mode 100644index 00000000..9738dcb5--- /dev/null+++ b/packages/ui/scripts/pageGate.test.mjs@@ -0,0 +1,113 @@+// What the middleware does with a request (lib/pageGate.ts, wired in by+// src/middleware.ts), with the session check stubbed: who is let through,+// what a refusal looks like, and that every page and refusal of one carries+// the Content-Security-Policy.+import assert from "node:assert/strict";+import test from "node:test";+import { PASSED_ON_HEADER, gatePage } from "../src/lib/pageGate.ts";++const POLICY = "script-src 'self' 'nonce-abc'; frame-ancestors 'self'";+const AUTH_PAGES = "frame-ancestors 'self'";++// NextResponse.next(): a response marked as passed on, and the request+// headers it hands to the page, recorded for the test.+function harness(gateResult) {+ const seen = { gateCalls: 0, requestHeaders: undefined };+ const deps = {+ sessionGate: async () => {+ seen.gateCalls += 1;+ if (gateResult instanceof Error) throw gateResult;+ return typeof gateResult === "function" ? gateResult() : gateResult;+ },+ passOn: (requestHeaders) => {+ seen.requestHeaders = requestHeaders;+ return new Response(null, { headers: { [PASSED_ON_HEADER]: "1" } });+ },+ csp: () => POLICY,+ authPagesPolicy: AUTH_PAGES,+ };+ return { deps, seen };+}++const request = (pathname, sessionFree = false) => ({+ pathname,+ headers: new Headers({ cookie: "session=old", accept: "text/html" }),+ sessionFree,+});++test("allowed: the page goes on with the policy on both sides and the refreshed cookie", async () => {+ const allowed = new Response(null, { headers: { [PASSED_ON_HEADER]: "1" } });+ allowed.headers.append("set-cookie", "session=new; Path=/; HttpOnly");+ const { deps, seen } = harness(allowed);+ const response = await gatePage(request("/today"), deps);+ assert.equal(seen.gateCalls, 1);+ assert.equal(response.headers.get("content-security-policy"), POLICY);+ assert.equal(seen.requestHeaders.get("content-security-policy"), POLICY);+ // The page still gets the browser's own headers.+ assert.equal(seen.requestHeaders.get("cookie"), "session=old");+ assert.deepEqual(response.headers.getSetCookie(), ["session=new; Path=/; HttpOnly"]);+});++test("refused page: the sign-in redirect itself carries the policy", async () => {+ // Response.redirect() answers with headers that can't be changed.+ const { deps, seen } = harness(() => Response.redirect("https://oe.example.com/signin?callbackUrl=%2Ftoday"));+ const response = await gatePage(request("/today"), deps);+ assert.equal(response.status, 302);+ assert.equal(response.headers.get("location"), "https://oe.example.com/signin?callbackUrl=%2Ftoday");+ assert.equal(response.headers.get("content-security-policy"), POLICY);+ // Not passed on: the page never rendered.+ assert.equal(seen.requestHeaders, undefined);+});++test("refused API call: the check's own 401, untouched", async () => {+ const { deps } = harness(() => Response.json({ error: "unauthorized" }, { status: 401 }));+ const response = await gatePage(request("/api/backend/today"), deps);+ assert.equal(response.status, 401);+ assert.deepEqual(await response.json(), { error: "unauthorized" });+});++test("session-free: the sign-in page gets the policy without a session check", async () => {+ const { deps, seen } = harness(new Response(null));+ const response = await gatePage(request("/signin", true), deps);+ assert.equal(seen.gateCalls, 0);+ assert.equal(response.headers.get("content-security-policy"), POLICY);+ assert.equal(seen.requestHeaders.get("content-security-policy"), POLICY);+});++test("session-free API (Auth.js's own pages): framing only, no session check", async () => {+ const { deps, seen } = harness(new Response(null));+ const response = await gatePage(request("/api/auth/signout", true), deps);+ assert.equal(seen.gateCalls, 0);+ assert.equal(response.headers.get("content-security-policy"), AUTH_PAGES);+});++for (const [name, result] of [+ ["nothing", undefined],+ ["null", null],+ ["a plain object", { ok: true }],+ ["an object with headers but no status", { headers: new Headers({ [PASSED_ON_HEADER]: "1" }) }],+]) {+ test(`a check that answers ${name} lets no page through`, async () => {+ const { deps, seen } = harness(result);+ const page = await gatePage(request("/today"), deps);+ assert.equal(page.status, 500);+ assert.equal(page.headers.get("content-security-policy"), POLICY);+ assert.equal(seen.requestHeaders, undefined);+ const api = await gatePage(request("/api/backend/today"), deps);+ assert.equal(api.status, 500);+ assert.equal(seen.requestHeaders, undefined);+ });+}++test("a refusal without the passed-on mark is never treated as allowed", async () => {+ const { deps, seen } = harness(() => new Response("no", { status: 403, headers: { [PASSED_ON_HEADER]: "0" } }));+ const response = await gatePage(request("/today"), deps);+ assert.equal(response.status, 403);+ assert.equal(seen.requestHeaders, undefined);+ assert.equal(response.headers.get("content-security-policy"), POLICY);+});++test("a check that throws lets nothing through", async () => {+ const { deps } = harness(new Error("session store down"));+ await assert.rejects(gatePage(request("/today"), deps), /session store down/);+});diff --git a/packages/ui/src/app/layout.tsx b/packages/ui/src/app/layout.tsxindex a387b5bb..ce551df1 100644--- a/packages/ui/src/app/layout.tsx+++ b/packages/ui/src/app/layout.tsx@@ -1,5 +1,6 @@import type { Metadata, Viewport } from "next";import { Bricolage_Grotesque, Geist } from "next/font/google";+import { connection } from "next/server";import AuthProvider from "@/components/AuthProvider";import { ExecutiveStatusProvider } from "@/components/executive/ExecutiveStatusContext";import { SessionsProvider } from "@/components/sessions/SessionsContext";@@ -32,11 +33,15 @@ export const viewport: Viewport = {viewportFit: "cover",};-export default function RootLayout({+export default async function RootLayout({children,}: {children: React.ReactNode;}) {+ // Every page renders on request, never ahead of time: each response's+ // scripts carry that response's nonce (lib/csp.ts, src/middleware.ts), and+ // a page built at build time would have none, so the policy would stop it.+ await connection();return (<html lang="en" className={`h-full ${geist.variable} ${bricolage.variable}`}><body className="h-full antialiased bg-surface text-fg">diff --git a/packages/ui/src/lib/csp.ts b/packages/ui/src/lib/csp.tsnew file mode 100644index 00000000..17d7749b--- /dev/null+++ b/packages/ui/src/lib/csp.ts@@ -0,0 +1,38 @@+// The Content-Security-Policy every page gets (src/middleware.ts).+//+// - Scripts: only those carrying this response's nonce, and what they load+// ('strict-dynamic'). No 'unsafe-inline', and no 'unsafe-eval' outside the+// dev server (React's dev build needs eval for its error overlays). So a+// script injected into a page (an outsider's text rendered as HTML, a+// dependency gone wrong) doesn't run.+// - No plugins, and no <base> pointing anywhere else.+// - Framing: this app alone ('self'), so no other site can show its Approve+// and Send buttons under something else.+//+// Styles, images and connections are left as they are: React, next/font and+// Mermaid set inline styles, and the rule above is what stops scripts.+//+// No imports, so `npm test` can exercise this under+// `node --experimental-strip-types` (see scripts/csp.test.mjs).++const NONCE_RE = /^[A-Za-z0-9+/_-]{16,}={0,2}$/;++/** Who may frame the pages: this app alone. */+export const FRAME_ANCESTORS = "frame-ancestors 'self'";++/** A fresh nonce: 16 random bytes, base64. */+export function makeNonce(): string {+ const bytes = new Uint8Array(16);+ crypto.getRandomValues(bytes);+ return btoa(String.fromCharCode(...bytes));+}++export function contentSecurityPolicy({ nonce, devServer }: { nonce: string; devServer: boolean }): string {+ if (!NONCE_RE.test(nonce)) throw new Error("a nonce is base64 of at least 12 random bytes");+ return [+ `script-src 'self' 'nonce-${nonce}' 'strict-dynamic'${devServer ? " 'unsafe-eval'" : ""}`,+ "object-src 'none'",+ "base-uri 'self'",+ FRAME_ANCESTORS,+ ].join("; ");+}diff --git a/packages/ui/src/lib/middlewarePaths.ts b/packages/ui/src/lib/middlewarePaths.tsnew file mode 100644index 00000000..7d656fcd--- /dev/null+++ b/packages/ui/src/lib/middlewarePaths.ts@@ -0,0 +1,8 @@+// The paths src/middleware.ts lets through without a session: Auth.js's own+// routes and exactly `/signin` (with optional trailing slash). Auth.js's+// routes end at a segment boundary and the sign-in page is an exact match, so+// a future `/api/authorizations` or `/signin-help` stays gated+// (scripts/middleware-matcher.test.mjs).+//+// No imports, so `npm test` can exercise it.+export const SESSION_FREE_PATH = /^\/(?:api\/auth(?:\/|$)|signin\/?$)/;diff --git a/packages/ui/src/lib/pageGate.ts b/packages/ui/src/lib/pageGate.tsnew file mode 100644index 00000000..f39e3da6--- /dev/null+++ b/packages/ui/src/lib/pageGate.ts@@ -0,0 +1,102 @@+// What src/middleware.ts does with a request, apart from Next.js and Auth.js+// themselves, so it can be tested with a stub session check+// (scripts/pageGate.test.mjs):+//+// 1. The session check, except for Auth.js's own routes and exactly `/signin`+// (lib/middlewarePaths.ts). It answers with the request passed on, or with+// the refusal auth.ts builds (JSON 401 for /api/*, a redirect to /signin+// for pages). Anything else from it refuses: a check that breaks never+// lets a page through.+// 2. Pages, the sign-in page and every refusal of one get the+// Content-Security-Policy. A page passed on carries it on the request+// too, where Next.js reads the nonce for its own scripts, and keeps any+// session cookie the check refreshed.+//+// No imports, so `npm test` can exercise it.++// What NextResponse.next() sets on a response that lets the request through.+// The check says "allowed" only this way.+export const PASSED_ON_HEADER = "x-middleware-next";++export type PageGateDeps = {+ // Auth.js's middleware: the request passed on, or its refusal.+ sessionGate: () => Promise<unknown>;+ // NextResponse.next(), with the request's headers when given.+ passOn: (requestHeaders?: Headers) => Response;+ // A fresh policy for this response (lib/csp.ts).+ csp: () => string;+ // Auth.js's own HTML pages: framing only, since its inline scripts get no nonce.+ authPagesPolicy: string;+};++function refusal(status: number, json: boolean): Response {+ return json+ ? new Response(JSON.stringify({ error: "the session check failed" }), {+ status,+ headers: { "content-type": "application/json" },+ })+ : new Response("The session check failed.", { status, headers: { "content-type": "text/plain" } });+}++// By shape rather than instanceof: Next.js runs the middleware in a runtime+// of its own, where a Response may come from another realm.+function isResponse(value: unknown): value is Response {+ return (+ typeof value === "object" &&+ value !== null &&+ typeof (value as Response).status === "number" &&+ typeof (value as Response).headers?.get === "function"+ );+}++// Response.redirect() and others answer with headers that can't be changed;+// a copy can.+function withHeader(response: Response, name: string, value: string): Response {+ try {+ response.headers.set(name, value);+ return response;+ } catch {+ const copy = new Response(response.body, {+ status: response.status,+ statusText: response.statusText,+ headers: new Headers(response.headers),+ });+ copy.headers.set(name, value);+ return copy;+ }+}++export async function gatePage(+ req: { pathname: string; headers: Headers; sessionFree: boolean },+ deps: PageGateDeps,+): Promise<Response> {+ if (req.pathname.startsWith("/api/")) {+ if (!req.sessionFree) {+ const gated = await deps.sessionGate();+ return isResponse(gated) ? gated : refusal(500, true);+ }+ return withHeader(deps.passOn(), "Content-Security-Policy", deps.authPagesPolicy);+ }++ const csp = deps.csp();+ const requestHeaders = new Headers(req.headers);+ requestHeaders.set("content-security-policy", csp);++ let response: Response;+ if (req.sessionFree) {+ response = deps.passOn(requestHeaders);+ } else {+ const gated = await deps.sessionGate();+ if (!isResponse(gated)) {+ response = refusal(500, false);+ } else if (gated.headers.get(PASSED_ON_HEADER) === "1") {+ // Allowed: pass the page on with the nonce, keeping any cookie the+ // session check refreshed.+ response = deps.passOn(requestHeaders);+ for (const cookie of gated.headers.getSetCookie()) response.headers.append("set-cookie", cookie);+ } else {+ response = gated;+ }+ }+ return withHeader(response, "Content-Security-Policy", csp);+}diff --git a/packages/ui/src/middleware.ts b/packages/ui/src/middleware.tsindex ace88f50..1394a7bf 100644--- a/packages/ui/src/middleware.ts+++ b/packages/ui/src/middleware.ts@@ -1,21 +1,43 @@-// Gate every page + non-auth API route. The decision, and the response a-// refused request gets (JSON 401 for /api/*, a redirect to /signin for-// pages), live in the `authorized` callback in auth.ts.+import { NextResponse, type NextFetchEvent, type NextRequest } from "next/server";+import { auth } from "@/auth";+import { contentSecurityPolicy, FRAME_ANCESTORS, makeNonce } from "@/lib/csp";+import { SESSION_FREE_PATH } from "@/lib/middlewarePaths";+import { gatePage } from "@/lib/pageGate";++// Every request but static assets comes through here. What it does with one+// (the session check, then the Content-Security-Policy on every page and+// every refusal of one) is lib/pageGate.ts; this wires in Next.js and+// Auth.js.//-// `auth` is exported as-is, not wrapped as `auth((req) => …)`: when a wrapper+// `auth` is called as-is, never wrapped as `auth((req) => …)`: when a wrapper// is passed, next-auth runs it even after `authorized` returns false, so the// per-request re-check never actually refused anyone — a user removed from// the roster kept working until their 24h JWT expired.-export { auth as middleware } from "@/auth";+const sessionGate = auth as unknown as (req: NextRequest, ev: NextFetchEvent) => Promise<unknown>;++// Written out literally: Next.js folds it at build time, so a production+// build never allows eval.+const DEV_SERVER = process.env.NODE_ENV !== "production";++export function middleware(req: NextRequest, ev: NextFetchEvent): Promise<Response> {+ const { pathname } = req.nextUrl;+ return gatePage(+ { pathname, headers: req.headers, sessionFree: SESSION_FREE_PATH.test(pathname) },+ {+ sessionGate: () => sessionGate(req, ev),+ passOn: (requestHeaders) =>+ requestHeaders ? NextResponse.next({ request: { headers: requestHeaders } }) : NextResponse.next(),+ csp: () => contentSecurityPolicy({ nonce: makeNonce(), devServer: DEV_SERVER }),+ authPagesPolicy: FRAME_ANCESTORS,+ },+ );+}-// Exclude Auth.js's own routes, Next internals, static assets, and exactly-// `/signin` (with optional trailing slash). Using `signin/?` rather than the-// looser `signin` keeps unrelated paths like `/signin-help` gated.-// An entry with no terminator would exclude every path that merely starts-// with it, so Auth.js's routes end at a segment boundary and the favicon is an-// exact match: a future `/api/authorizations` or `/favicon.icoX` stays gated.+// Everything but Next's static files and the favicon. An entry with no+// terminator would exclude every path that merely starts with it, so the+// favicon is an exact match: a future `/favicon.icoX` still runs here.// Checked against Next's own matcher compiler in// scripts/middleware-matcher.test.mjs.export const config = {- matcher: ["/((?!api/auth(?:/|$)|_next/static|_next/image|favicon\\.ico$|signin/?$).*)"],+ matcher: ["/((?!_next/static|_next/image|favicon\\.ico$).*)"],};