feat(auth): proactive session expiry redirect across all delivery paths

- Split auth config into auth.config.ts (edge-safe, no argon2) and auth-edge.ts
  for middleware use; auth.ts now spreads the shared config
- Middleware wraps with auth() to redirect unauthenticated requests to /auth/signin
  before any page render; passes through /auth/, /api/, /invite/ paths
- SessionGuard client component watches useSession() and redirects on
  status=unauthenticated, closing the SPA navigation gap
- QueryCache + MutationCache in TRPCProvider redirect on UNAUTHORIZED tRPC errors
  without retrying; SessionProvider polls session state every 5 minutes
- Middleware tests updated for async auth wrapper and auth-edge mock

Co-Authored-By: claude-flow <ruv@ruv.net>
This commit is contained in:
2026-04-03 10:42:10 +02:00
parent ed4d4e4640
commit bf8577dbaf
8 changed files with 151 additions and 57 deletions
+19 -12
View File
@@ -1,13 +1,20 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { describe, it, expect, vi, afterEach } from "vitest";
import { NextRequest } from "next/server";
// Web Crypto is available in the test environment (Node 20+)
// Simulate an authenticated session so the middleware does not redirect
// and CSP headers are set on every response.
vi.mock("./server/auth-edge.js", () => ({
auth: (handler: (req: NextRequest & { auth: object | null }) => unknown) =>
(req: NextRequest) =>
handler(Object.assign(req, { auth: { user: { id: "test-user", email: "test@test.com" } } })),
}));
async function importMiddleware(nodeEnv: string) {
vi.stubEnv("NODE_ENV", nodeEnv);
vi.resetModules();
const mod = await import("./middleware.js");
return mod.middleware;
// middleware is the default export (wrapped by auth())
return mod.default as (req: NextRequest) => Promise<Response>;
}
describe("middleware — Content-Security-Policy", () => {
@@ -19,16 +26,16 @@ describe("middleware — Content-Security-Policy", () => {
it("sets a Content-Security-Policy header on every response", async () => {
const middleware = await importMiddleware("production");
const req = new NextRequest("http://localhost:3100/");
const res = middleware(req);
const res = await middleware(req);
expect(res.headers.get("Content-Security-Policy")).toBeTruthy();
});
it("production: script-src contains a nonce and does NOT contain unsafe-inline or unsafe-eval", async () => {
const middleware = await importMiddleware("production");
const req = new NextRequest("http://localhost:3100/dashboard");
const res = middleware(req);
const res = await middleware(req);
const csp = res.headers.get("Content-Security-Policy") ?? "";
const scriptSrc = csp.split(";").find((d) => d.trim().startsWith("script-src")) ?? "";
const scriptSrc = csp.split(";").find((d: string) => d.trim().startsWith("script-src")) ?? "";
expect(scriptSrc).toMatch(/'nonce-[A-Za-z0-9+/=]+'/);
expect(scriptSrc).not.toContain("'unsafe-inline'");
expect(scriptSrc).not.toContain("'unsafe-eval'");
@@ -36,8 +43,8 @@ describe("middleware — Content-Security-Policy", () => {
it("production: each request gets a unique nonce", async () => {
const middleware = await importMiddleware("production");
const res1 = middleware(new NextRequest("http://localhost:3100/a"));
const res2 = middleware(new NextRequest("http://localhost:3100/b"));
const res1 = await middleware(new NextRequest("http://localhost:3100/a"));
const res2 = await middleware(new NextRequest("http://localhost:3100/b"));
const nonce1 = res1.headers.get("Content-Security-Policy")?.match(/'nonce-([^']+)'/)?.[1];
const nonce2 = res2.headers.get("Content-Security-Policy")?.match(/'nonce-([^']+)'/)?.[1];
expect(nonce1).toBeTruthy();
@@ -48,7 +55,7 @@ describe("middleware — Content-Security-Policy", () => {
it("production: x-nonce request header matches the nonce in the CSP response header", async () => {
const middleware = await importMiddleware("production");
const req = new NextRequest("http://localhost:3100/settings");
const res = middleware(req);
const res = await middleware(req);
const cspNonce = res.headers.get("Content-Security-Policy")?.match(/'nonce-([^']+)'/)?.[1];
// The nonce is forwarded on the request (for server components) — not readable from
// the response directly, but verifiable via the CSP header consistency.
@@ -59,9 +66,9 @@ describe("middleware — Content-Security-Policy", () => {
it("development: script-src includes unsafe-eval and unsafe-inline for HMR", async () => {
const middleware = await importMiddleware("development");
const req = new NextRequest("http://localhost:3100/");
const res = middleware(req);
const res = await middleware(req);
const csp = res.headers.get("Content-Security-Policy") ?? "";
const scriptSrc = csp.split(";").find((d) => d.trim().startsWith("script-src")) ?? "";
const scriptSrc = csp.split(";").find((d: string) => d.trim().startsWith("script-src")) ?? "";
expect(scriptSrc).toContain("'unsafe-eval'");
expect(scriptSrc).toContain("'unsafe-inline'");
});
@@ -69,7 +76,7 @@ describe("middleware — Content-Security-Policy", () => {
it("frame-ancestors is always 'none' regardless of environment", async () => {
for (const env of ["production", "development"] as const) {
const middleware = await importMiddleware(env);
const res = middleware(new NextRequest("http://localhost:3100/"));
const res = await middleware(new NextRequest("http://localhost:3100/"));
const csp = res.headers.get("Content-Security-Policy") ?? "";
expect(csp).toContain("frame-ancestors 'none'");
}