diff --git a/docs/superpowers/plans/2026-08-08-immich-redaktionsportal.md b/docs/superpowers/plans/2026-08-08-immich-redaktionsportal.md new file mode 100644 index 0000000..628a3aa --- /dev/null +++ b/docs/superpowers/plans/2026-08-08-immich-redaktionsportal.md @@ -0,0 +1,1203 @@ +# Immich-Redaktionsportal 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:** Build a production-ready, self-hosted editorial portal that exposes only administrator-approved Immich albums, records paid photo usages and free repeat downloads, and generates immutable billing PDFs. + +**Architecture:** A single Next.js 16 full-stack service runs beside Immich and a dedicated PostgreSQL database. All Immich access is isolated behind a typed server-only adapter; authorization, usage accounting, report finalization, SMTP, and PDF rendering are separate domain modules with transaction boundaries and explicit interfaces. + +**Tech Stack:** Node.js 24 LTS, pnpm, Next.js 16 App Router, React 19, TypeScript 5, Tailwind CSS 4, PostgreSQL 17, Drizzle ORM/Kit, Better Auth with the Drizzle adapter, Zod, Nodemailer, pdfmake 0.3, Vitest, Testing Library, MSW, Testcontainers, and Playwright. + +## Global Constraints + +- Work in an isolated worktree created with `superpowers:using-git-worktrees` before changing application code. +- Use `superpowers:test-driven-development` for every feature and bug fix; every behavior starts with a failing test. +- Use `frontend-design` and `vercel-react-best-practices` for UI tasks 7, 10, and 12. +- Use `superpowers:verification-before-completion` before any completion claim, commit handoff, or pull request. +- Use Node.js 24 LTS; reject unsupported Node versions through `engines` and CI. +- Use pnpm and commit `pnpm-lock.yaml`; dependency versions are frozen by that lockfile. +- Use only documented stable Immich API endpoints; never query or mutate the Immich database. +- Never expose the Immich API key, internal Immich URL, SMTP credentials, database URL, or session secret to client bundles or logs. +- Store monetary values as integer Euro cents. Do not use JavaScript floating-point values for billing arithmetic. +- Store all timestamps in UTC and calculate month/quarter boundaries with the `Europe/Berlin` time zone. +- Support photos only; every Immich search includes `type: "IMAGE"`. +- Do not add analytics, marketing cookies, videos, uploads, photo editing, payment processing, or multi-user editorial organizations. +- UI is German, monochrome, responsive, keyboard accessible, and uses the two provided Leon Tonhäuser logos. +- The portal database is separate from Immich's database, even when both run on the same host. +- Legal copy is externally configurable; implementation must not invent final legal advice or silently accept privacy terms as consent. + +--- + +## File and Module Map + +### Runtime and configuration + +- `package.json` - scripts, engine policy, runtime and test dependencies +- `pnpm-lock.yaml` - exact dependency resolution +- `next.config.ts` - standalone build and security-safe Next.js settings +- `tsconfig.json` - strict TypeScript configuration +- `postcss.config.mjs` - Tailwind CSS 4 integration +- `vitest.config.ts` - unit/integration test projects +- `playwright.config.ts` - end-to-end browser configuration +- `drizzle.config.ts` - PostgreSQL schema and migration paths +- `.env.example` - documented, non-secret configuration contract +- `Dockerfile` - multi-stage production image +- `compose.yaml` - portal app and separate PostgreSQL service +- `src/config/env.ts` - server environment parsing +- `src/config/public.ts` - allow-listed public legal URLs and public app name + +### Database + +- `src/db/client.ts` - PostgreSQL pool and Drizzle instance +- `src/db/schema/auth.ts` - Better Auth user, account, session, and verification tables +- `src/db/schema/editorials.ts` - editorial account and billing-address history +- `src/db/schema/albums.ts` - Immich album grants +- `src/db/schema/usages.ts` - usages and download events +- `src/db/schema/billing.ts` - reports and immutable report items +- `src/db/schema/audit.ts` - audit events +- `src/db/schema/index.ts` - schema exports and relations +- `drizzle/` - generated, committed SQL migrations +- `tests/db/postgres.ts` - Testcontainers PostgreSQL lifecycle + +### Authentication and accounts + +- `src/modules/auth/auth.ts` - Better Auth server configuration +- `src/modules/auth/client.ts` - Better Auth browser client +- `src/modules/auth/principal.ts` - `PortalPrincipal` and authorization guards +- `src/modules/auth/registration.ts` - transactional editorial registration +- `src/modules/auth/admin-bootstrap.ts` - idempotent first-admin creation +- `src/modules/mail/mailer.ts` - SMTP transport and typed mail methods +- `src/app/api/auth/[...all]/route.ts` - Better Auth route adapter +- `src/app/(public)/anmelden/page.tsx` - login +- `src/app/(public)/registrieren/page.tsx` - B2B registration +- `src/app/(public)/registrieren/bestaetigt/page.tsx` - pending-approval state +- `src/app/(public)/passwort-vergessen/page.tsx` - neutral password-reset request +- `src/app/(public)/passwort-zuruecksetzen/page.tsx` - token-based password reset + +### Immich and album permissions + +- `src/modules/immich/types.ts` - minimal validated API response types +- `src/modules/immich/client.ts` - server-only `ImmichClient` +- `src/modules/immich/errors.ts` - mapped upstream error taxonomy +- `src/modules/albums/grants.ts` - grant/revoke and visible-album queries +- `src/app/admin/redaktionen/[id]/alben/page.tsx` - album grants admin UI +- `src/app/redaktion/alben/page.tsx` - editorial album list +- `src/app/redaktion/alben/[albumId]/page.tsx` - album photo grid and search +- `src/app/api/assets/[assetId]/thumbnail/route.ts` - authorized thumbnail proxy + +### Usage and downloads + +- `src/modules/usages/service.ts` - new/existing usage decisions +- `src/modules/usages/types.ts` - domain inputs and outputs +- `src/modules/downloads/service.ts` - authorized download event lifecycle +- `src/modules/downloads/stream.ts` - upstream-to-browser stream accounting +- `src/app/api/download-intents/route.ts` - create idempotent download intent +- `src/app/api/downloads/[downloadId]/file/route.ts` - authorized original stream +- `src/components/download/usage-dialog.tsx` - existing/new purpose UI +- `src/app/redaktion/nutzungen/page.tsx` - editorial usage and download history + +### Billing and PDFs + +- `src/modules/billing/period.ts` - Berlin month/quarter boundaries +- `src/modules/billing/queries.ts` - open/billed usage list +- `src/modules/billing/reports.ts` - preview, finalization, and cancellation +- `src/modules/billing/types.ts` - immutable report snapshot types +- `src/modules/pdf/document.ts` - pdfmake document definition +- `src/modules/pdf/render.ts` - buffer renderer and SHA-256 calculation +- `src/app/admin/abrechnungen/page.tsx` - editorial and period selection +- `src/app/admin/abrechnungen/[editorialId]/page.tsx` - position selection +- `src/app/api/billing-reports/preview/route.ts` - preview PDF +- `src/app/api/billing-reports/route.ts` - finalize report +- `src/app/api/billing-reports/[reportId]/route.ts` - retrieve final PDF +- `src/app/api/billing-reports/[reportId]/cancel/route.ts` - cancel and reopen + +### UI, audit, deployment, and verification + +- `src/app/layout.tsx` - global Inter font and legal footer +- `src/app/globals.css` - black/white design tokens and accessible focus styles +- `src/components/brand/logo.tsx` - white/black logo variants +- `src/components/layout/portal-shell.tsx` - role-aware navigation +- `src/modules/audit/write.ts` - secret-safe audit writer +- `src/modules/security/rate-limit.ts` - PostgreSQL-backed fixed-window limits +- `src/modules/security/origin.ts` - same-origin enforcement for custom state-changing routes +- `src/app/admin/audit/page.tsx` - paginated administrator audit log +- `src/app/api/health/live/route.ts` - process liveness +- `src/app/api/health/ready/route.ts` - database and Immich readiness +- `scripts/backup-db.sh` - explicit database backup command +- `.github/workflows/ci.yml` - lint, typecheck, unit, integration, build, and E2E +- `e2e/registration.spec.ts` - registration and approval path +- `e2e/download.spec.ts` - paid usage and free repeat path +- `e2e/billing.spec.ts` - month selection and PDF path +- `docs/operations.md` - deployment, SMTP, Immich user, backup, restore, and update runbook + +--- + +### Task 1: Bootstrap a Verifiable Application Shell + +**Files:** +- Create: `package.json` +- Create: `pnpm-lock.yaml` +- Create: `next.config.ts` +- Create: `tsconfig.json` +- Create: `postcss.config.mjs` +- Create: `vitest.config.ts` +- Create: `.env.example` +- Create: `src/config/env.ts` +- Create: `src/app/layout.tsx` +- Create: `src/app/page.tsx` +- Create: `src/app/globals.css` +- Create: `src/app/api/health/live/route.ts` +- Test: `src/config/env.test.ts` +- Test: `src/app/api/health/live/route.test.ts` + +**Interfaces:** +- Produces: `env: ServerEnv`, parsed once from process environment. +- Produces: `GET /api/health/live -> { status: "ok" }` with HTTP 200. + +- [ ] **Step 1: Create the package and strict toolchain configuration** + +Create `package.json` with these scripts and engine policy; install the named dependencies with pnpm so the lockfile records exact versions. + +```json +{ + "private": true, + "packageManager": "pnpm@10", + "engines": { "node": ">=24 <25" }, + "scripts": { + "dev": "next dev", + "build": "next build", + "start": "next start", + "lint": "eslint .", + "typecheck": "tsc --noEmit", + "test": "vitest run", + "test:watch": "vitest", + "test:e2e": "playwright test" + } +} +``` + +Run: + +```bash +pnpm add next@16 react@19 react-dom@19 zod +pnpm add -D typescript@5 @types/node@24 @types/react @types/react-dom eslint eslint-config-next tailwindcss @tailwindcss/postcss vitest @vitejs/plugin-react jsdom @testing-library/react @testing-library/jest-dom +``` + +- [ ] **Step 2: Write failing environment and health tests** + +```ts +// src/config/env.test.ts +import { describe, expect, test } from "vitest"; +import { parseServerEnv } from "./env"; + +describe("parseServerEnv", () => { + test("rejects a missing Immich API key", () => { + expect(() => parseServerEnv({ DATABASE_URL: "postgres://db/app" })).toThrow(/IMMICH_API_KEY/); + }); +}); +``` + +```ts +// src/app/api/health/live/route.test.ts +import { expect, test } from "vitest"; +import { GET } from "./route"; + +test("returns a process liveness response", async () => { + const response = await GET(); + expect(response.status).toBe(200); + await expect(response.json()).resolves.toEqual({ status: "ok" }); +}); +``` + +- [ ] **Step 3: Run the tests and verify the failure** + +Run: `pnpm test src/config/env.test.ts src/app/api/health/live/route.test.ts` +Expected: FAIL because `parseServerEnv` and the health route do not exist. + +- [ ] **Step 4: Implement the minimum shell** + +Define `ServerEnv` with Zod fields for `DATABASE_URL`, `BETTER_AUTH_SECRET`, `BETTER_AUTH_URL`, `IMMICH_BASE_URL`, `IMMICH_API_KEY`, SMTP settings, and three legal URLs. Export `parseServerEnv(input: NodeJS.ProcessEnv): ServerEnv`. Mark the module server-only. Implement the health route exactly as tested and add a German home page that redirects unauthenticated users to `/anmelden` later. + +- [ ] **Step 5: Verify shell quality** + +Run: + +```bash +pnpm test +pnpm typecheck +pnpm lint +pnpm build +``` + +Expected: all commands exit 0. + +- [ ] **Step 6: Commit** + +```bash +git add package.json pnpm-lock.yaml next.config.ts tsconfig.json postcss.config.mjs vitest.config.ts .env.example src +git commit -m "chore: bootstrap portal application" +``` + +### Task 2: Create the Transactional Database Model + +**Files:** +- Create: `drizzle.config.ts` +- Create: `src/db/client.ts` +- Create: `src/db/schema/auth.ts` +- Create: `src/db/schema/editorials.ts` +- Create: `src/db/schema/albums.ts` +- Create: `src/db/schema/usages.ts` +- Create: `src/db/schema/billing.ts` +- Create: `src/db/schema/audit.ts` +- Create: `src/db/schema/index.ts` +- Create: `tests/db/postgres.ts` +- Create: `tests/db/schema.test.ts` +- Create: `drizzle/0000_initial.sql` + +**Interfaces:** +- Produces: `db: NodePgDatabase` and `pool: pg.Pool`. +- Produces: UUID-keyed tables and enums described in Design section 14. +- Produces: unique idempotency constraint on `(editorial_account_id, idempotency_key)` for download events. + +- [ ] **Step 1: Install database and integration-test dependencies** + +```bash +pnpm add drizzle-orm pg +pnpm add -D drizzle-kit @types/pg testcontainers @testcontainers/postgresql +``` + +- [ ] **Step 2: Write a failing database invariants test** + +```ts +// tests/db/schema.test.ts +import { afterAll, beforeAll, expect, test } from "vitest"; +import { startPostgres } from "./postgres"; + +const testDb = await startPostgres(); +afterAll(() => testDb.stop()); + +test("rejects duplicate download idempotency keys for one editorial", async () => { + const seed = await testDb.seedEditorialWithUsage(); + await testDb.insertDownload({ ...seed, idempotencyKey: "same-request" }); + await expect(testDb.insertDownload({ ...seed, idempotencyKey: "same-request" })).rejects.toThrow(); +}); +``` + +- [ ] **Step 3: Verify the test fails** + +Run: `pnpm test tests/db/schema.test.ts` +Expected: FAIL because the PostgreSQL fixture and schema do not exist. + +- [ ] **Step 4: Implement focused schemas and the initial migration** + +Use PostgreSQL enums for portal role, account status, usage billing status, download status, and report status. Use `integer` for cents, `timestamp(..., { withTimezone: true })` for timestamps, and foreign keys with restrictive deletes for immutable accounting records. Store report PDFs as `bytea` and SHA-256 as a 64-character hex string. + +Required state values: + +```ts +export const portalRoles = ["ADMIN", "EDITORIAL"] as const; +export const accountStatuses = ["pending_email", "pending_approval", "active", "suspended", "rejected"] as const; +export const usageBillingStatuses = ["open", "billed", "reopened"] as const; +export const downloadStatuses = ["authorized", "streaming", "completed", "failed_before_delivery", "interrupted"] as const; +export const reportStatuses = ["draft", "final", "cancelled"] as const; +``` + +- [ ] **Step 5: Generate, inspect, and test the migration** + +Run: + +```bash +pnpm drizzle-kit generate --name initial +pnpm drizzle-kit check +pnpm test tests/db/schema.test.ts +``` + +Expected: migration check succeeds and the uniqueness test passes. + +- [ ] **Step 6: Commit** + +```bash +git add drizzle.config.ts drizzle src/db tests/db package.json pnpm-lock.yaml +git commit -m "feat: add portal database schema" +``` + +### Task 3: Add Email/Password Authentication and B2B Registration + +**Files:** +- Create: `src/modules/auth/auth.ts` +- Create: `src/modules/auth/client.ts` +- Create: `src/modules/auth/registration.ts` +- Create: `src/modules/auth/admin-bootstrap.ts` +- Create: `src/modules/mail/mailer.ts` +- Create: `src/app/api/auth/[...all]/route.ts` +- Create: `src/app/(public)/anmelden/page.tsx` +- Create: `src/app/(public)/registrieren/page.tsx` +- Create: `src/app/(public)/registrieren/bestaetigt/page.tsx` +- Create: `src/app/(public)/passwort-vergessen/page.tsx` +- Create: `src/app/(public)/passwort-zuruecksetzen/page.tsx` +- Test: `src/modules/auth/registration.test.ts` +- Test: `src/modules/mail/mailer.test.ts` + +**Interfaces:** +- Produces: `registerEditorial(input: RegistrationInput): Promise<{ status: "pending_email" }>`. +- Produces: `Mailer.sendVerification`, `Mailer.sendPasswordReset`, and `Mailer.sendApprovalNotice`. +- Produces: Better Auth handler at `/api/auth/[...all]` with email verification required and automatic sign-in disabled. + +- [ ] **Step 1: Install authentication and SMTP dependencies** + +```bash +pnpm add better-auth @better-auth/drizzle-adapter nodemailer +pnpm add -D @types/nodemailer +``` + +- [ ] **Step 2: Write a failing registration service test** + +```ts +import { expect, test, vi } from "vitest"; +import { createRegistrationService } from "./registration"; + +test("creates a pending editorial and sends verification mail", async () => { + const auth = { signUpEmail: vi.fn().mockResolvedValue({ user: { id: "user-1" } }) }; + const repo = { createEditorial: vi.fn().mockResolvedValue(undefined) }; + const mailer = { sendVerification: vi.fn().mockResolvedValue(undefined) }; + const service = createRegistrationService({ auth, repo, mailer }); + + await expect(service.register(validRegistration)).resolves.toEqual({ status: "pending_email" }); + expect(repo.createEditorial).toHaveBeenCalledWith(expect.objectContaining({ userId: "user-1", status: "pending_email" })); + expect(mailer.sendVerification).toHaveBeenCalledOnce(); +}); + +test("moves a verified account from pending email to pending approval", async () => { + await service.onEmailVerified("user-1"); + expect(repo.markPendingApproval).toHaveBeenCalledWith("user-1"); +}); +``` + +- [ ] **Step 3: Run the test and verify the failure** + +Run: `pnpm test src/modules/auth/registration.test.ts` +Expected: FAIL because the registration service is missing. + +- [ ] **Step 4: Implement auth, mail, and the registration transaction** + +Configure Better Auth with the Drizzle adapter, `emailAndPassword.enabled = true`, `requireEmailVerification = true`, `autoSignIn = false`, one-hour reset tokens, and session revocation after password reset. Use its default secure password hashing unless a pinned Better Auth release fails the project security review. Normalize email addresses to lowercase. + +Connect the verified-email callback to an idempotent `pending_email -> pending_approval` transition. Refuse the transition when no matching editorial account exists and audit the inconsistency without including tokens or raw request data. + +`RegistrationInput` must include company name, contact name, email, password, structured billing address, `actsForBusiness: true`, `termsVersion`, and `privacyAcknowledged: true`. Reject false B2B/terms/privacy flags with stable German field errors. Create the first billing-address version in the same transaction as the editorial account. + +- [ ] **Step 5: Build public forms and prevent account enumeration** + +The registration and password-reset pages always return neutral success copy. Build both reset-request and token-reset pages; a successful reset revokes every existing session for that account. The registration page links to the configured legal URLs and uses separate B2B/terms and privacy-acknowledgment controls. The login rejects non-active editorials after valid authentication without revealing whether the problem is verification or approval. + +- [ ] **Step 6: Verify** + +Run: + +```bash +pnpm test src/modules/auth/registration.test.ts src/modules/mail/mailer.test.ts +pnpm typecheck +pnpm lint +``` + +Expected: all commands exit 0. + +- [ ] **Step 7: Commit** + +```bash +git add src/modules/auth src/modules/mail src/app/api/auth src/app/'(public)' package.json pnpm-lock.yaml +git commit -m "feat: add editorial registration and authentication" +``` + +### Task 4: Add Principals, Admin Approval, and Address History + +**Files:** +- Create: `src/modules/auth/principal.ts` +- Create: `src/modules/editorials/service.ts` +- Create: `src/app/admin/layout.tsx` +- Create: `src/app/admin/redaktionen/page.tsx` +- Create: `src/app/admin/redaktionen/[id]/page.tsx` +- Create: `src/app/redaktion/profil/page.tsx` +- Test: `src/modules/auth/principal.test.ts` +- Test: `src/modules/editorials/service.test.ts` + +**Interfaces:** +- Produces: `PortalPrincipal = { userId: string; role: "ADMIN" | "EDITORIAL"; editorialId: string | null; status: AccountStatus }`. +- Produces: `requireAdmin(requestHeaders): Promise`. +- Produces: `requireActiveEditorial(requestHeaders): Promise`. +- Produces: `approveEditorial({ editorialId, priceCents, adminUserId }): Promise`. +- Produces: `replaceBillingAddress(editorialId, input): Promise` returning the new address-version ID. + +- [ ] **Step 1: Write failing guard and approval tests** + +```ts +test("rejects a suspended editorial after session authentication", async () => { + const guard = createPrincipalGuard({ getSession: async () => editorialSession, getAccount: async () => suspendedEditorial }); + await expect(guard.requireActiveEditorial(new Headers())).rejects.toMatchObject({ code: "ACCOUNT_SUSPENDED" }); +}); + +test("approval requires a positive price in cents", async () => { + await expect(service.approveEditorial({ editorialId: "e1", priceCents: 0, adminUserId: "a1" })).rejects.toMatchObject({ code: "INVALID_PRICE" }); +}); + +test("approval activates the account and sends the approval notice", async () => { + await service.approveEditorial({ editorialId: "e1", priceCents: 1500, adminUserId: "a1" }); + expect(mailer.sendApprovalNotice).toHaveBeenCalledWith(expect.objectContaining({ editorialId: "e1" })); +}); +``` + +- [ ] **Step 2: Run and verify the failure** + +Run: `pnpm test src/modules/auth/principal.test.ts src/modules/editorials/service.test.ts` +Expected: FAIL because guards and services are missing. + +- [ ] **Step 3: Implement guards and editorial state transitions** + +Allow only `pending_approval -> active`, `active -> suspended`, `suspended -> active`, and pending states to `rejected`. Approval requires verified email, positive integer cents, and at least one album grant; until Task 6 supplies album grants, the admin page may save the price but the activation action remains disabled with German explanatory copy. + +Commit account activation before dispatching the approval email. Record mail delivery failure for retry without rolling back the already successful approval or sending a duplicate on an idempotent retry. + +- [ ] **Step 4: Implement address versioning** + +Insert a new `billing_address_versions` row and update the editorial's current address reference in one transaction. Never update or delete an old address version. + +- [ ] **Step 5: Verify and commit** + +Run: `pnpm test src/modules/auth/principal.test.ts src/modules/editorials/service.test.ts && pnpm typecheck && pnpm lint` + +```bash +git add src/modules/auth src/modules/editorials src/app/admin src/app/redaktion/profil +git commit -m "feat: add editorial approval and account guards" +``` + +### Task 5: Build the Stable Immich API Adapter + +**Files:** +- Create: `src/modules/immich/types.ts` +- Create: `src/modules/immich/client.ts` +- Create: `src/modules/immich/errors.ts` +- Create: `src/modules/immich/client.test.ts` +- Create: `tests/fixtures/immich.ts` + +**Interfaces:** +- Produces: + +```ts +export interface ImmichClient { + listAlbums(signal?: AbortSignal): Promise; + getAlbum(albumId: string, signal?: AbortSignal): Promise; + searchPhotos(input: { albumIds: string[]; description?: string; page: number; size: number }, signal?: AbortSignal): Promise; + getThumbnail(assetId: string, signal?: AbortSignal): Promise; + getOriginal(assetId: string, signal?: AbortSignal): Promise; +} + +export type ImmichBinary = { + body: ReadableStream; + contentType: string; + contentLength: number | null; + filename: string; +}; +``` + +- [ ] **Step 1: Install request mocking** + +Run: `pnpm add -D msw` + +- [ ] **Step 2: Write failing adapter contract tests** + +```ts +test("forces IMAGE and authorized album IDs in metadata search", async () => { + server.use(captureImmichSearch((body) => { + expect(body).toMatchObject({ albumIds: ["album-1"], description: "jubel", type: "IMAGE", page: 1, size: 60 }); + })); + await client.searchPhotos({ albumIds: ["album-1"], description: "jubel", page: 1, size: 60 }); +}); + +test("maps an Immich outage to IMMICH_UNAVAILABLE", async () => { + server.use(http.get("*/api/albums", () => HttpResponse.error())); + await expect(client.listAlbums()).rejects.toMatchObject({ code: "IMMICH_UNAVAILABLE" }); +}); +``` + +- [ ] **Step 3: Run and verify the failure** + +Run: `pnpm test src/modules/immich/client.test.ts` +Expected: FAIL because the adapter does not exist. + +- [ ] **Step 4: Implement a minimal fetch adapter with Zod response validation** + +Every request adds `x-api-key` server-side, uses `/api` endpoints, checks status before parsing, validates JSON responses, maps 401/403 to `IMMICH_AUTH_FAILED`, 404 to `IMMICH_NOT_FOUND`, network/5xx to `IMMICH_UNAVAILABLE`, and never includes response bodies or the key in thrown messages. + +- [ ] **Step 5: Verify and commit** + +Run: `pnpm test src/modules/immich/client.test.ts && pnpm typecheck && pnpm lint` + +```bash +git add src/modules/immich tests/fixtures package.json pnpm-lock.yaml +git commit -m "feat: add typed immich api adapter" +``` + +### Task 6: Add Album Grants and Admin Assignment + +**Files:** +- Create: `src/modules/albums/grants.ts` +- Create: `src/modules/albums/grants.test.ts` +- Create: `src/app/admin/redaktionen/[id]/alben/page.tsx` +- Create: `src/app/admin/redaktionen/[id]/alben/actions.ts` + +**Interfaces:** +- Produces: `listAssignableAlbums(editorialId): Promise`. +- Produces: `grantAlbum({ editorialId, immichAlbumId, adminUserId }): Promise`. +- Produces: `revokeAlbum({ editorialId, immichAlbumId, adminUserId }): Promise`. +- Produces: `getGrantedAlbumIds(editorialId): Promise`. + +- [ ] **Step 1: Write failing grant-boundary tests** + +```ts +test("refuses to grant an album that the service user cannot read", async () => { + immich.getAlbum.mockRejectedValue({ code: "IMMICH_NOT_FOUND" }); + await expect(service.grantAlbum({ editorialId: "e1", immichAlbumId: "hidden", adminUserId: "a1" })) + .rejects.toMatchObject({ code: "ALBUM_NOT_ASSIGNABLE" }); +}); + +test("revocation immediately removes the album from visible IDs", async () => { + await service.revokeAlbum({ editorialId: "e1", immichAlbumId: "album-1", adminUserId: "a1" }); + await expect(service.getGrantedAlbumIds("e1")).resolves.not.toContain("album-1"); +}); +``` + +- [ ] **Step 2: Run and verify failure** + +Run: `pnpm test src/modules/albums/grants.test.ts` +Expected: FAIL because the grant service is missing. + +- [ ] **Step 3: Implement grant/revoke transactions and audit calls** + +Use soft revocation timestamps so historical assignments remain explainable. Re-granting creates or reactivates one current grant without duplicates. After the first active grant and positive price exist, the admin approval service may activate the editorial. + +- [ ] **Step 4: Build the admin assignment page** + +Show Immich album cover, name, count, current grant state, and an explicit unavailable state. Use server actions protected by `requireAdmin`; revalidate only the affected editorial page. + +- [ ] **Step 5: Verify and commit** + +Run: `pnpm test src/modules/albums/grants.test.ts && pnpm typecheck && pnpm lint` + +```bash +git add src/modules/albums src/app/admin/redaktionen +git commit -m "feat: add editorial album permissions" +``` + +### Task 7: Build the Branded Editorial Album and Search Experience + +**Files:** +- Create: `public/brand/logo-white.png` +- Create: `public/brand/logo-black.png` +- Create: `src/components/brand/logo.tsx` +- Create: `src/components/layout/portal-shell.tsx` +- Create: `src/modules/albums/catalog.ts` +- Create: `src/modules/albums/catalog.test.ts` +- Create: `src/app/redaktion/layout.tsx` +- Create: `src/app/redaktion/alben/page.tsx` +- Create: `src/app/redaktion/alben/[albumId]/page.tsx` +- Create: `src/app/api/assets/[assetId]/thumbnail/route.ts` +- Create: `src/app/globals.css` + +**Interfaces:** +- Consumes: `requireActiveEditorial`, `getGrantedAlbumIds`, and `ImmichClient`. +- Produces: `getVisibleAlbums(editorialId): Promise`. +- Produces: `searchVisiblePhotos(editorialId, input): Promise`. +- Produces: authorized thumbnail proxy route. + +- [ ] **Step 1: Invoke required design/performance skills and copy the provided logo files** + +Use `frontend-design` for the monochrome UI and `vercel-react-best-practices` for server/client boundaries. Copy the provided logo sources into `public/brand/` without recompressing them. + +- [ ] **Step 2: Write failing access-filter tests** + +```ts +test("ignores a caller-supplied album outside the editorial grants", async () => { + grants.getGrantedAlbumIds.mockResolvedValue(["allowed"]); + await catalog.searchVisiblePhotos("editorial-1", { requestedAlbumId: "forbidden", description: "tor", page: 1 }); + expect(immich.searchPhotos).toHaveBeenCalledWith(expect.objectContaining({ albumIds: ["allowed"], description: "tor" }), expect.anything()); +}); +``` + +- [ ] **Step 3: Run and verify failure** + +Run: `pnpm test src/modules/albums/catalog.test.ts` +Expected: FAIL because the catalog service is missing. + +- [ ] **Step 4: Implement the catalog and authorized thumbnail proxy** + +The thumbnail route authenticates the editorial, resolves current grant IDs, verifies that the asset belongs to at least one granted album via Immich album/search data, then streams the thumbnail. Return generic 404 for forbidden and missing assets to avoid disclosure. + +- [ ] **Step 5: Implement the approved black/white UI** + +Use Inter, a black header, black/white logo variants, album cards populated from Immich covers, responsive photo grids, German search copy, pagination, loading, no-results, and Immich-unavailable states. Keep pages as Server Components; isolate only search input and interactive gallery controls as Client Components. + +- [ ] **Step 6: Verify accessibility and commit** + +Run: + +```bash +pnpm test src/modules/albums/catalog.test.ts +pnpm typecheck +pnpm lint +pnpm build +``` + +```bash +git add public/brand src/components src/modules/albums src/app/redaktion src/app/api/assets src/app/globals.css +git commit -m "feat: add branded editorial photo catalog" +``` + +### Task 8: Implement New and Existing Usage Accounting + +**Files:** +- Create: `src/modules/usages/types.ts` +- Create: `src/modules/usages/service.ts` +- Create: `src/modules/usages/service.test.ts` +- Create: `src/modules/downloads/service.ts` +- Create: `src/modules/downloads/service.test.ts` + +**Interfaces:** +- Produces: + +```ts +type CreateNewUsageInput = { + editorialId: string; + assetId: string; + albumId: string; + purpose: string; + reference?: string; + idempotencyKey: string; +}; + +type CreateRepeatDownloadInput = { + editorialId: string; + usageId: string; + note?: string; + idempotencyKey: string; +}; + +createNewUsage(input: CreateNewUsageInput): Promise; +createRepeatDownload(input: CreateRepeatDownloadInput): Promise; +listPriorUsages(editorialId: string, assetId: string): Promise; +``` + +- [ ] **Step 1: Write failing price-snapshot and idempotency tests** + +```ts +test("snapshots the current editorial price on a new usage", async () => { + repo.getEditorialPrice.mockResolvedValue(1500); + const intent = await service.createNewUsage(newUsageInput); + expect(intent.priceCents).toBe(1500); + expect(repo.insertUsage).toHaveBeenCalledWith(expect.objectContaining({ priceCents: 1500, billingStatus: "open" })); +}); + +test("returns the same intent for a repeated idempotency key", async () => { + const first = await service.createNewUsage(newUsageInput); + const second = await service.createNewUsage(newUsageInput); + expect(second.id).toBe(first.id); + await expect(repo.countUsages()).resolves.toBe(1); +}); +``` + +- [ ] **Step 2: Run and verify failure** + +Run: `pnpm test src/modules/usages/service.test.ts src/modules/downloads/service.test.ts` +Expected: FAIL because usage services are missing. + +- [ ] **Step 3: Implement one transaction per intent** + +For new usage: verify active account, positive price, current album grant, asset membership, and current Immich metadata; snapshot filename/album/price; insert usage plus authorized download event. For repeat: verify the usage belongs to the editorial and asset, then insert only a zero-cost download event. Normalize purpose to trimmed text of 3-200 characters and reference/note to at most 200 characters. + +- [ ] **Step 4: Add a real PostgreSQL concurrency test** + +Use two simultaneous calls with the same idempotency key and assert exactly one usage and one download event exist. Use a unique constraint plus insert-on-conflict/readback rather than an in-memory lock. + +- [ ] **Step 5: Verify and commit** + +Run: `pnpm test src/modules/usages src/modules/downloads && pnpm typecheck && pnpm lint` + +```bash +git add src/modules/usages src/modules/downloads +git commit -m "feat: add usage and download intent accounting" +``` + +### Task 9: Stream Authorized Originals and Track Delivery Outcomes + +**Files:** +- Create: `src/modules/downloads/stream.ts` +- Create: `src/modules/downloads/stream.test.ts` +- Create: `src/app/api/download-intents/route.ts` +- Create: `src/app/api/downloads/[downloadId]/file/route.ts` +- Create: `src/components/download/usage-dialog.tsx` +- Create: `src/app/redaktion/nutzungen/page.tsx` +- Test: `src/app/api/downloads/[downloadId]/file/route.test.ts` + +**Interfaces:** +- Consumes: usage intent service and `ImmichClient.getOriginal`. +- Produces: `POST /api/download-intents -> { downloadId, fileUrl, priceCents, billable }`. +- Produces: `GET /api/downloads/:id/file` streaming response with safe `Content-Disposition`. +- Produces: `streamWithAccounting(input): ReadableStream`. +- Produces: `listEditorialUsageHistory(editorialId, page): Promise` scoped to one editorial. + +- [ ] **Step 1: Write failing stream lifecycle tests** + +```ts +test("marks a failure before the first byte and voids a new usage", async () => { + immich.getOriginal.mockRejectedValue({ code: "IMMICH_UNAVAILABLE" }); + const response = await GET(request, routeContext("download-1")); + expect(response.status).toBe(503); + expect(repo.failBeforeDelivery).toHaveBeenCalledWith("download-1", { voidNewUsage: true }); +}); + +test("marks an interrupted stream but keeps the usage for free retry", async () => { + const stream = streamWithAccounting(interruptingUpstream); + await expect(readAll(stream)).rejects.toBeDefined(); + expect(repo.markInterrupted).toHaveBeenCalledOnce(); + expect(repo.deleteUsage).not.toHaveBeenCalled(); +}); +``` + +- [ ] **Step 2: Run and verify failure** + +Run: `pnpm test src/modules/downloads/stream.test.ts src/app/api/downloads/'[downloadId]'/file/route.test.ts` +Expected: FAIL because route and stream wrapper are missing. + +- [ ] **Step 3: Implement secure stream delivery** + +Require the same active editorial session that owns the download event. Permit only an `authorized` event; an interrupted attempt must create a new zero-cost repeat intent so every concrete attempt has its own event. Mark `streaming` before enqueueing the first byte, count delivered bytes, mark `completed` on close, and mark `interrupted` on cancel/error. Sanitize filenames to remove path separators and CR/LF before `Content-Disposition`. + +- [ ] **Step 4: Implement the approved usage dialog** + +When prior usages exist, show existing usage and new usage choices. Existing usage shows `0,00 EUR`; new usage shows the exact editorial price and requires purpose. Generate a UUID idempotency key once per submitted dialog, not on every React render. + +- [ ] **Step 5: Build the editorial's own usage history** + +List date/time, filename, source album, purpose, billable price, and every completed/interrupted download attempt for the authenticated editorial. Scope the repository query by the principal's `editorialId`; do not accept an editorial ID from the URL or client. Add pagination and empty/error states. + +- [ ] **Step 6: Verify and commit** + +Run: `pnpm test src/modules/downloads src/app/api/downloads && pnpm typecheck && pnpm lint && pnpm build` + +```bash +git add src/modules/downloads src/app/api/download-intents src/app/api/downloads src/components/download src/app/redaktion/nutzungen +git commit -m "feat: stream originals with download accounting" +``` + +### Task 10: Build Billing Periods and Selection Queries + +**Files:** +- Create: `src/modules/billing/period.ts` +- Create: `src/modules/billing/period.test.ts` +- Create: `src/modules/billing/queries.ts` +- Create: `src/modules/billing/queries.test.ts` +- Create: `src/app/admin/abrechnungen/page.tsx` +- Create: `src/app/admin/abrechnungen/[editorialId]/page.tsx` + +**Interfaces:** +- Produces: `monthPeriod(year, month, zone = "Europe/Berlin"): BillingPeriod`. +- Produces: `quarterPeriod(year, quarter, zone = "Europe/Berlin"): BillingPeriod`. +- Produces: `listBillablePositions(editorialId, period): Promise`. +- Produces: `listNonBillableDownloads(editorialId, period): Promise`. + +- [ ] **Step 1: Install the time-zone dependency and write failing daylight-saving and status tests** + +```bash +pnpm add @js-temporal/polyfill +``` + +```ts +test("converts a Berlin month to an exclusive UTC range", () => { + expect(monthPeriod(2026, 3)).toEqual({ + fromUtc: new Date("2026-02-28T23:00:00.000Z"), + toUtcExclusive: new Date("2026-03-31T22:00:00.000Z") + }); +}); + +test("returns billed rows disabled and open rows selectable", async () => { + const result = await queries.listBillablePositions("e1", august2026); + expect(result.find((x) => x.status === "billed")?.selectable).toBe(false); + expect(result.find((x) => x.status === "open")?.selectable).toBe(true); + expect(result.find((x) => x.status === "reopened")?.selectable).toBe(true); +}); +``` + +- [ ] **Step 2: Run and verify failure** + +Run: `pnpm test src/modules/billing/period.test.ts src/modules/billing/queries.test.ts` +Expected: FAIL because period and query functions are missing. + +- [ ] **Step 3: Implement time-zone-safe periods and queries** + +Use `@js-temporal/polyfill`; do not calculate Berlin boundaries by adding milliseconds. Query by half-open `[fromUtc, toUtcExclusive)` ranges. Treat `open` and `reopened` positions as selectable and `billed` positions as disabled. Include all repeat download events in the period, even when their original usage was billed earlier. + +- [ ] **Step 4: Build the approved admin selection UI** + +Invoke `frontend-design` and `vercel-react-best-practices`. Provide individual checkboxes, `Alle offenen im Monat`, `Ganzes Quartal`, and `Auswahl aufheben`. Display selected count and cents-derived German EUR total. Render billed rows gray and disabled with report/invoice reference. + +- [ ] **Step 5: Verify and commit** + +Run: `pnpm test src/modules/billing && pnpm typecheck && pnpm lint && pnpm build` + +```bash +git add src/modules/billing src/app/admin/abrechnungen package.json pnpm-lock.yaml +git commit -m "feat: add billing period selection" +``` + +### Task 11: Render the Invoice-Styled PDF + +**Files:** +- Create: `src/modules/billing/types.ts` +- Create: `src/modules/pdf/document.ts` +- Create: `src/modules/pdf/render.ts` +- Create: `src/modules/pdf/render.test.ts` +- Create: `tests/fixtures/billing-report.ts` +- Create: `scripts/render-pdf-fixture.ts` + +**Interfaces:** +- Produces: `BillingReportSnapshot` containing address, selected paid positions, period repeat downloads, totals, report metadata, and invoice number. +- Produces: `renderBillingPdf(snapshot: BillingReportSnapshot): Promise<{ bytes: Buffer; sha256: string }>`. + +- [ ] **Step 1: Install PDF dependencies** + +```bash +pnpm add pdfmake@0.3 +pnpm add -D @types/pdfmake pdfjs-dist tsx +``` + +- [ ] **Step 2: Write failing content and integrity tests** + +```ts +test("renders paid and free-repeat sections with the net total", async () => { + const result = await renderBillingPdf(reportFixture); + const text = await extractPdfText(result.bytes); + expect(text).toContain("Nutzungsnachweis"); + expect(text).toContain("Berechnete Bildnutzungen"); + expect(text).toContain("Nicht erneut berechnete Downloads"); + expect(text).toContain("60,00 EUR"); + expect(result.sha256).toMatch(/^[a-f0-9]{64}$/); +}); +``` + +- [ ] **Step 3: Run and verify failure** + +Run: `pnpm test src/modules/pdf/render.test.ts` +Expected: FAIL because the renderer is missing. + +- [ ] **Step 4: Implement the approved monochrome document** + +Embed a licensed monospaced font, the black logo, sender block, recipient block, rounded black summary panel, repeated black table headers, light-gray rows, German dates, exact cents-derived totals, page numbers, document ID, invoice reference, and legal separation notice. Never read live database or Immich data inside the renderer; it accepts only an immutable snapshot. + +- [ ] **Step 5: Render and visually inspect stress fixtures** + +Generate PDFs for one row, 60 rows, long German company/address text, long filenames/purposes, umlauts, and three pages. + +Run: + +```bash +pnpm tsx scripts/render-pdf-fixture.ts +pdftoppm -png tmp/pdfs/billing-stress.pdf tmp/pdfs/billing-stress +``` + +Inspect every page PNG for clipping, overlap, broken glyphs, table-header repetition, and page numbering. Fix any defect before proceeding. + +- [ ] **Step 6: Verify and commit** + +Run: `pnpm test src/modules/pdf/render.test.ts && pnpm typecheck && pnpm lint` + +```bash +git add src/modules/pdf src/modules/billing/types.ts tests/fixtures scripts/render-pdf-fixture.ts package.json pnpm-lock.yaml +git commit -m "feat: render billing usage pdf" +``` + +### Task 12: Finalize, Retrieve, and Cancel Immutable Reports + +**Files:** +- Create: `src/modules/billing/reports.ts` +- Create: `src/modules/billing/reports.test.ts` +- Create: `src/app/api/billing-reports/preview/route.ts` +- Create: `src/app/api/billing-reports/route.ts` +- Create: `src/app/api/billing-reports/[reportId]/route.ts` +- Create: `src/app/api/billing-reports/[reportId]/cancel/route.ts` +- Modify: `src/app/admin/abrechnungen/[editorialId]/page.tsx` + +**Interfaces:** +- Produces: `previewReport(input): Promise` without state changes. +- Produces: `finalizeReport(input): Promise<{ reportId: string; reportNumber: string }>`. +- Produces: `cancelReport({ reportId, reason, adminUserId }): Promise`. + +- [ ] **Step 1: Write failing transaction tests** + +```ts +test("does not bill positions when PDF rendering fails", async () => { + pdf.render.mockRejectedValue(new Error("render failed")); + await expect(service.finalizeReport(validSelection)).rejects.toThrow("render failed"); + await expect(repo.getUsageStatuses(validSelection.usageIds)).resolves.toEqual(["open", "open"]); +}); + +test("cancellation reopens positions and preserves the cancelled report", async () => { + await service.cancelReport({ reportId: "r1", reason: "Falscher Zeitraum", adminUserId: "a1" }); + await expect(repo.getReport("r1")).resolves.toMatchObject({ status: "cancelled" }); + await expect(repo.getUsageStatuses(["u1"])).resolves.toEqual(["reopened"]); +}); +``` + +- [ ] **Step 2: Run and verify failure** + +Run: `pnpm test src/modules/billing/reports.test.ts` +Expected: FAIL because report finalization is missing. + +- [ ] **Step 3: Implement preview and locked finalization** + +Validate that every selected usage belongs to the editorial, is currently open/reopened, and falls within the chosen period. Build the address and item snapshot, render PDF bytes, then use a serializable transaction or row locks to re-check eligibility, allocate the report number, insert report/items/PDF/hash, and mark usages billed. A concurrent report must receive a stable conflict response rather than duplicate positions. + +- [ ] **Step 4: Implement protected routes and UI confirmation** + +All routes require admin. Preview returns `application/pdf` without persistence. Final GET returns only stored bytes with `Content-Disposition: attachment`. Cancellation requires a non-empty 5-500 character reason and explicit confirmation. + +- [ ] **Step 5: Verify and commit** + +Run: `pnpm test src/modules/billing/reports.test.ts && pnpm typecheck && pnpm lint && pnpm build` + +```bash +git add src/modules/billing/reports.ts src/modules/billing/reports.test.ts src/app/api/billing-reports src/app/admin/abrechnungen +git commit -m "feat: finalize immutable billing reports" +``` + +### Task 13: Add Audit, Rate Limits, Legal Footer, and Security Headers + +**Files:** +- Create: `src/modules/audit/write.ts` +- Create: `src/modules/audit/write.test.ts` +- Create: `src/modules/security/rate-limit.ts` +- Create: `src/modules/security/rate-limit.test.ts` +- Create: `src/modules/security/origin.ts` +- Create: `src/modules/security/origin.test.ts` +- Create: `src/components/layout/legal-footer.tsx` +- Create: `src/app/admin/audit/page.tsx` +- Modify: `src/app/layout.tsx` +- Modify: `next.config.ts` +- Modify: state-changing services from Tasks 4, 6, 8, and 12 + +**Interfaces:** +- Produces: `writeAudit(event: AuditInput): Promise` with recursive secret redaction. +- Produces: `consumeRateLimit(key, policy): Promise<{ allowed: boolean; retryAfterSeconds: number }>`. +- Produces: `assertSameOrigin(request): void` for custom state-changing API routes. +- Produces: `listAuditEvents(filters, cursor): Promise` for administrators only. + +- [ ] **Step 1: Write failing secret-redaction and rate-limit tests** + +```ts +test("redacts secrets before writing audit metadata", async () => { + await writeAudit({ type: "CONFIG_CHECK", metadata: { apiKey: "secret", nested: { password: "secret" }, albumId: "a1" } }); + expect(repo.insert).toHaveBeenCalledWith(expect.objectContaining({ metadata: { apiKey: "[REDACTED]", nested: { password: "[REDACTED]" }, albumId: "a1" } })); +}); + +test("blocks the sixth login attempt in a fifteen-minute window", async () => { + for (let i = 0; i < 5; i++) expect((await limiter.consume("login:hash", loginPolicy)).allowed).toBe(true); + expect((await limiter.consume("login:hash", loginPolicy)).allowed).toBe(false); +}); + +test("rejects a cross-origin state-changing request", () => { + const request = requestWithHeaders({ origin: "https://evil.example", host: "portal.example.de" }); + expect(() => assertSameOrigin(request)).toThrowError(expect.objectContaining({ code: "CROSS_ORIGIN_REQUEST" })); +}); +``` + +- [ ] **Step 2: Run and verify failure** + +Run: `pnpm test src/modules/audit src/modules/security` +Expected: FAIL because the modules are missing. + +- [ ] **Step 3: Implement database-backed security primitives** + +Hash rate-limit identity material before storage. Implement these initial policies, configurable only within bounded server-side limits: login `5 / 15 minutes` per hashed IP plus normalized email; registration `5 / hour` per hashed IP; password reset `5 / hour` per hashed IP plus normalized email; search `120 / minute` per active editorial; download intents `30 / minute` per active editorial. Return `429` with `Retry-After`. + +Enforce `Origin`/`Host` agreement on every custom state-changing API route in Tasks 8 and 12; rely on Better Auth's documented protections only for its own route handler. Audit approval, suspension, price change, address change, grant/revoke, usage creation, report finalization, and cancellation. Never audit raw request bodies. + +- [ ] **Step 4: Add the protected administrator audit view** + +Build a cursor-paginated audit table showing timestamp, actor, event type, affected editorial/resource, and redacted metadata. Require `requireAdmin` in the server component and query layer. Add event-type and Berlin-local date filters without exposing secrets or accepting arbitrary SQL sort fields. + +- [ ] **Step 5: Add legal footer and headers** + +Render configured `Impressum`, `Datenschutz`, and `Nutzungs- und Lizenzbedingungen` links on public and authenticated pages. Set Content-Security-Policy, Referrer-Policy, X-Content-Type-Options, frame denial, and a restrictive Permissions-Policy. Do not add a cookie banner or analytics. + +- [ ] **Step 6: Verify and commit** + +Run: `pnpm test src/modules/audit src/modules/security && pnpm typecheck && pnpm lint && pnpm build` + +```bash +git add src/modules/audit src/modules/security src/components/layout src/app/admin/audit src/app/layout.tsx next.config.ts +git commit -m "feat: harden portal security and auditability" +``` + +### Task 14: Add Docker Deployment, Health Checks, Backups, and Operations Docs + +**Files:** +- Create: `Dockerfile` +- Create: `compose.yaml` +- Create: `src/app/api/health/ready/route.ts` +- Create: `src/app/api/health/ready/route.test.ts` +- Create: `scripts/backup-db.sh` +- Create: `docs/operations.md` +- Modify: `.env.example` + +**Interfaces:** +- Produces: `GET /api/health/ready -> 200` only when PostgreSQL is reachable and Immich authentication succeeds. +- Produces: reproducible standalone image and explicit backup command. + +- [ ] **Step 1: Write the failing readiness test** + +```ts +test("returns 503 when Immich is unavailable", async () => { + const route = createReadinessRoute({ checkDb: async () => true, checkImmich: async () => false }); + const response = await route(); + expect(response.status).toBe(503); + await expect(response.json()).resolves.toEqual({ status: "not_ready", checks: { database: "ok", immich: "failed" } }); +}); +``` + +- [ ] **Step 2: Run and verify failure** + +Run: `pnpm test src/app/api/health/ready/route.test.ts` +Expected: FAIL because readiness logic is missing. + +- [ ] **Step 3: Implement deployment artifacts** + +Use a multi-stage Node 24 Alpine image and Next.js standalone output. Run as an unprivileged user. Define `portal-db` as PostgreSQL 17 with a dedicated volume and healthcheck. Define internal DB and Immich networks without exposing PostgreSQL publicly. Reference secrets by environment or Docker secrets; commit no secret value. + +- [ ] **Step 4: Implement backup and restore runbook** + +`scripts/backup-db.sh` accepts an explicit output directory argument, rejects `/`, `$HOME`, and empty paths, and runs `pg_dump --format=custom`. `docs/operations.md` documents reverse-proxy streaming timeouts, Immich service-user permissions, SMTP TLS, migration order, nightly backup, restore drill, API-key rotation, DPA/service-condition archive, staging tests, and rollback. + +- [ ] **Step 5: Verify image and compose configuration** + +Run: + +```bash +docker compose config +docker compose build portal-app +docker compose up -d portal-db +pnpm test src/app/api/health/ready/route.test.ts +``` + +Expected: config/build/test succeed and the database healthcheck becomes healthy. + +- [ ] **Step 6: Commit** + +```bash +git add Dockerfile compose.yaml src/app/api/health scripts/backup-db.sh docs/operations.md .env.example +git commit -m "ops: add portal deployment and backup runbook" +``` + +### Task 15: Add End-to-End Coverage and CI Quality Gates + +**Files:** +- Create: `playwright.config.ts` +- Create: `e2e/fixtures.ts` +- Create: `e2e/registration.spec.ts` +- Create: `e2e/download.spec.ts` +- Create: `e2e/billing.spec.ts` +- Create: `tests/fake-immich/server.ts` +- Create: `.github/workflows/ci.yml` +- Modify: `package.json` + +**Interfaces:** +- Produces: deterministic fake Immich server with albums, descriptions, thumbnails, originals, and outage modes. +- Produces: CI gates for lint, typecheck, unit/integration tests, Next build, Docker build, and Chromium E2E. + +- [ ] **Step 1: Install and configure Playwright** + +Run: + +```bash +pnpm add -D @playwright/test +pnpm exec playwright install chromium +``` + +- [ ] **Step 2: Write the three failing E2E journeys** + +```ts +test("registration remains pending until admin price and album approval", async ({ page, admin }) => { + await registerEditorial(page, editorialFixture); + await expect(page.getByText("wartet auf Freigabe")).toBeVisible(); + await admin.approveEditorial(editorialFixture.email, { priceCents: 1500, albumId: "album-1" }); + await login(page, editorialFixture); + await expect(page.getByText("Freigegebene Fotos")).toBeVisible(); +}); +``` + +```ts +test("new purpose is billed once and repeat download is free", async ({ page }) => { + await createNewUsageAndDownload(page, { asset: "IMG_4821.jpg", purpose: "Spielbericht" }); + await repeatExistingUsageDownload(page, "Spielbericht"); + await expect(page.getByText("0,00 €")).toBeVisible(); +}); +``` + +```ts +test("month selection disables billed rows after final PDF", async ({ page }) => { + await selectAllOpenInMonth(page, "August 2026"); + await finalizeReport(page); + await expect(page.getByRole("checkbox", { name: /IMG_4821/ })).toBeDisabled(); +}); +``` + +- [ ] **Step 3: Run and verify failures** + +Run: `pnpm test:e2e` +Expected: FAIL until fixtures, selectors, and remaining integration seams are complete. + +- [ ] **Step 4: Complete deterministic fixtures and fix only product defects exposed by E2E** + +The fake Immich server must assert that every search contains only seeded permitted album IDs and `IMAGE`. E2E data is created through public/admin interfaces where practical; direct DB seeds are limited to first-admin bootstrap and deterministic base albums. + +- [ ] **Step 5: Add CI and run the full local gate** + +CI uses Node 24, pnpm cache, PostgreSQL service, and Chromium. It must fail on any skipped mandatory test, type error, lint error, migration drift, build error, or E2E failure. + +Run: + +```bash +pnpm lint +pnpm typecheck +pnpm test +pnpm build +pnpm test:e2e +docker compose config +docker compose build portal-app +git diff --check +``` + +Expected: every command exits 0. + +- [ ] **Step 6: Perform final spec and security verification** + +Use `superpowers:verification-before-completion`. Check every acceptance criterion in the design spec, render the multi-page PDF fixture again, verify no secret appears in `.next`, logs, client JavaScript, or committed files, and perform one backup/restore drill. + +- [ ] **Step 7: Commit** + +```bash +git add playwright.config.ts e2e tests/fake-immich .github/workflows/ci.yml package.json pnpm-lock.yaml +git commit -m "test: add portal end-to-end quality gates" +``` + +--- + +## Final Release Checklist + +- [ ] Immich technical user exists and only approved albums are shared read-only. +- [ ] API key has only `album.read`, `asset.read`, `asset.view`, and `asset.download`, verified against the installed Immich version. +- [ ] Reverse proxy HTTPS, upload/download timeouts, and streaming behavior are tested with a large original photo. +- [ ] Infomaniak SMTP verification, reset, and approval mails arrive with the production sender. +- [ ] Infomaniak DPA, service conditions, subprocessors, and breach-notification address are checked and archived. +- [ ] Final privacy and license texts have received the required professional review. +- [ ] No non-essential cookie or analytics request appears in browser network logs. +- [ ] Database backup and restore drill succeeds. +- [ ] Staging contract tests pass against the exact production Immich version. +- [ ] All design acceptance criteria and Task 15 commands pass from a clean checkout.