11 KiB
Session Expiry and Error Recovery Implementation Plan
For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (
- [ ]) syntax for tracking.
Goal: Redirect expired protected-page sessions to /anmelden and provide a branded retry/sign-in recovery page for genuine unexpected rendering failures.
Architecture: A server-only page-access wrapper classifies the existing PrincipalAuthorizationError before protected layouts render. Only AUTHENTICATION_REQUIRED becomes a Next.js redirect; every other error propagates to a root route error boundary implemented as a small client component.
Tech Stack: Next.js 16 App Router, React 19, TypeScript, Tailwind CSS 4, Vitest, Testing Library, jsdom.
Global Constraints
- Expired sessions redirect exactly to
/anmelden. - Only
PrincipalAuthorizationError("AUTHENTICATION_REQUIRED")is redirected. - Other authorization, database, Immich and programming errors are rethrown unchanged.
- Existing API response behavior, account-status rules and session duration remain unchanged.
- The unexpected-error UI exposes no stack, raw message or digest.
- Recovery controls are labelled exactly
Erneut versuchenandZur Anmeldung. - No database migration or new dependency is allowed.
Task 1: Protected-page authentication boundary
Files:
- Create:
src/modules/auth/page-access.ts - Create:
src/modules/auth/page-access.test.ts - Modify:
src/app/admin/layout.tsx - Modify:
src/app/redaktion/layout.tsx
Interfaces:
-
Consumes:
PrincipalAuthorizationError, Next.jsredirect, existingrequireAdminandrequireEditorialpage guards. -
Produces:
requirePageAccess<T>(loadPrincipal: () => Promise<T>): Promise<T>. -
Step 1: Write the failing page-access tests
Create src/modules/auth/page-access.test.ts:
import { afterEach, expect, test, vi } from "vitest";
const { redirect } = vi.hoisted(() => ({
redirect: vi.fn((destination: string): never => {
throw new Error(`NEXT_REDIRECT:${destination}`);
}),
}));
vi.mock("next/navigation", () => ({ redirect }));
import { PrincipalAuthorizationError } from "./principal";
import { requirePageAccess } from "./page-access";
afterEach(() => vi.clearAllMocks());
test("redirects an expired protected-page session to sign-in", async () => {
const expired = new PrincipalAuthorizationError("AUTHENTICATION_REQUIRED");
await expect(
requirePageAccess(async () => {
throw expired;
}),
).rejects.toThrow("NEXT_REDIRECT:/anmelden");
});
test("rethrows non-session failures unchanged", async () => {
const unavailable = new Error("database unavailable");
await expect(
requirePageAccess(async () => {
throw unavailable;
}),
).rejects.toBe(unavailable);
expect(redirect).not.toHaveBeenCalled();
});
test("returns the principal when the page guard succeeds", async () => {
const principal = { userId: "admin-1" };
await expect(requirePageAccess(async () => principal)).resolves.toBe(principal);
expect(redirect).not.toHaveBeenCalled();
});
- Step 2: Run the focused test and verify RED
./node_modules/.bin/vitest run src/modules/auth/page-access.test.ts
Expected: FAIL because ./page-access does not exist.
- Step 3: Implement the minimal server-only boundary
Create src/modules/auth/page-access.ts:
import "server-only";
import { redirect } from "next/navigation";
import { PrincipalAuthorizationError } from "@/modules/auth/principal";
export async function requirePageAccess<T>(
loadPrincipal: () => Promise<T>,
): Promise<T> {
try {
return await loadPrincipal();
} catch (error) {
if (
error instanceof PrincipalAuthorizationError &&
error.code === "AUTHENTICATION_REQUIRED"
) {
redirect("/anmelden");
}
throw error;
}
}
- Step 4: Run the focused test and verify GREEN
./node_modules/.bin/vitest run src/modules/auth/page-access.test.ts
Expected: 1 file and 3 tests PASS.
- Step 5: Integrate both protected layouts
In src/app/admin/layout.tsx, import requirePageAccess and replace the direct
guard call with:
await requirePageAccess(() => requireAdmin(new Headers(await headers())));
In src/app/redaktion/layout.tsx, import requirePageAccess and replace the
direct guard call with:
await requirePageAccess(requireEditorial);
Do not alter either layout's PortalShell, role navigation or principal guard.
- Step 6: Run focused tests, typecheck and lint
./node_modules/.bin/vitest run src/modules/auth/page-access.test.ts src/modules/auth/principal.test.ts
./node_modules/.bin/tsc --noEmit
./node_modules/.bin/eslint src/modules/auth/page-access.ts src/modules/auth/page-access.test.ts src/app/admin/layout.tsx src/app/redaktion/layout.tsx
Expected: all commands exit 0.
- Step 7: Commit the page-access behavior
git add src/modules/auth/page-access.ts src/modules/auth/page-access.test.ts src/app/admin/layout.tsx src/app/redaktion/layout.tsx
git commit -m "fix: redirect expired portal sessions"
Task 2: Branded unexpected-error recovery page
Files:
- Create:
src/app/error.tsx - Create:
src/app/error.test.tsx
Interfaces:
-
Consumes: Next.js error-boundary props
{ error: Error & { digest?: string }; reset: () => void },Link, and the existingButtoncomponent. -
Produces: the root route error UI for uncaught child-segment rendering errors.
-
Step 1: Write the failing recovery UI test
Create src/app/error.test.tsx:
// @vitest-environment jsdom
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, expect, test, vi } from "vitest";
import PortalError from "./error";
afterEach(cleanup);
test("offers retry and sign-in without exposing server details", () => {
const reset = vi.fn();
render(
<PortalError
error={Object.assign(new Error("database password leaked"), {
digest: "private-digest",
})}
reset={reset}
/>,
);
expect(
screen.getByRole("heading", { name: "Diese Seite konnte nicht geladen werden." }),
).toBeTruthy();
fireEvent.click(screen.getByRole("button", { name: "Erneut versuchen" }));
expect(reset).toHaveBeenCalledTimes(1);
expect(screen.getByRole("link", { name: "Zur Anmeldung" }).getAttribute("href")).toBe(
"/anmelden",
);
expect(document.body.textContent).not.toContain("database password leaked");
expect(document.body.textContent).not.toContain("private-digest");
});
- Step 2: Run the focused test and verify RED
./node_modules/.bin/vitest run src/app/error.test.tsx
Expected: FAIL because src/app/error.tsx does not exist.
- Step 3: Implement the minimal recovery page
Create src/app/error.tsx:
"use client";
import Link from "next/link";
import { Button } from "@/components/ui/button";
type PortalErrorProps = {
error: Error & { digest?: string };
reset: () => void;
};
export default function PortalError({ reset }: Readonly<PortalErrorProps>) {
return (
<main className="public-account-page">
<header className="masthead">
<span className="wordmark">Leon Tonhäuser</span>
<span className="section-label">Redaktionsportal</span>
</header>
<section className="account-panel" aria-labelledby="error-title">
<p className="eyebrow">Verbindung unterbrochen</p>
<h1 id="error-title">Diese Seite konnte nicht geladen werden.</h1>
<p className="lede">
Versuchen Sie es erneut oder melden Sie sich wieder am Redaktionsportal an.
</p>
<div className="mt-8 flex flex-wrap gap-3">
<Button className="min-h-11" size="lg" type="button" onClick={reset}>
Erneut versuchen
</Button>
<Button asChild className="min-h-11" size="lg" variant="outline">
<Link href="/anmelden">Zur Anmeldung</Link>
</Button>
</div>
</section>
</main>
);
}
The error prop remains part of the required Next.js interface but is not
rendered or logged by this component.
- Step 4: Run the focused test and verify GREEN
./node_modules/.bin/vitest run src/app/error.test.tsx
Expected: 1 file and 1 test PASS.
- Step 5: Run typecheck and focused lint
./node_modules/.bin/tsc --noEmit
./node_modules/.bin/eslint src/app/error.tsx src/app/error.test.tsx
Expected: both commands exit 0.
- Step 6: Commit the recovery UI
git add src/app/error.tsx src/app/error.test.tsx
git commit -m "feat: add portal error recovery page"
Task 3: Full verification and deployment handoff
Files:
- Verify only; no production file is added by this task.
Interfaces:
-
Consumes: completed page-access and recovery-page tasks.
-
Produces: verified commits ready for integration and a container-only deployment.
-
Step 1: Run the full deterministic verification
./node_modules/.bin/vitest run src
./node_modules/.bin/tsc --noEmit
./node_modules/.bin/eslint .
./node_modules/.bin/drizzle-kit check
git diff --check
Expected: all commands exit 0 with no failed tests, type errors, lint errors or migration inconsistencies.
- Step 2: Run the production build
env \
DATABASE_URL=postgres://portal:change-me@portal-db:5432/portal \
BETTER_AUTH_SECRET=replace-with-a-long-random-secret \
BETTER_AUTH_URL=https://redaktionen.leon-tonhaeuser.de \
IMMICH_BASE_URL=http://immich-server:2283 \
IMMICH_API_KEY=replace-with-a-restricted-immich-api-key \
SMTP_HOST=smtp.example.com SMTP_PORT=587 \
SMTP_USER=portal@example.com SMTP_PASSWORD=replace-with-an-smtp-password \
SMTP_FROM=portal@example.com \
LEGAL_IMPRINT_URL=https://leon-tonhaeuser.de/impressum \
LEGAL_PRIVACY_URL=https://leon-tonhaeuser.de/datenschutz \
LEGAL_TERMS_URL=https://leon-tonhaeuser.de/agb \
NEXT_DISABLE_TURBOPACK=1 \
./node_modules/.bin/next build --webpack
Expected: production build exits 0 and includes /anmelden, /admin and
/redaktion routes.
- Step 3: Verify scope and history
git status --short
git log -5 --oneline
Expected: no uncommitted implementation changes and both feature commits are present.
- Step 4: Deploy without database migration
git pull --ff-only origin main
docker compose build --pull portal-app
docker compose up -d --no-deps --force-recreate portal-app
Expected: the refreshed container serves the redirect and recovery UI; Zoraxy and PostgreSQL require no change.