diff --git a/.agent/PROGRESS.md b/.agent/PROGRESS.md index 46454f8..181e32f 100644 --- a/.agent/PROGRESS.md +++ b/.agent/PROGRESS.md @@ -73,3 +73,39 @@ Build log for Media Team Hub. One unit per commit, top to bottom. Append after e - `dateInTimezone` destructured `{y,m,d}` but `partsInTz` returns `{year,month,day}` — fixed. **Next: A3 — auth (auth.js + credentials provider, admin/coordinator/volunteer roles).** + +--- + +## A3 — Auth — DONE 2026-11-17 + +**Scope (from BUILD-PLAN.md):** magic-link sign-in (dev console transport), session cookie, `requirePermission()` chokepoint, role enum. + +**Delivered:** +- `src/auth/roles.ts` — `SystemRole` type + helpers (`isAdmin`, `isCoordinator`, `isLeader`, `assertSystemRole`). +- `src/auth/permissions.ts` — feature-scoped permission matrix from the ARCHITECTURE §2.3 capability table, `hasPermission()`, `AuthError` (carries HTTP 401/403), `requirePermission(user, perm)` chokepoint. +- `src/auth/magic-link.ts` — dev console transport: `getOrCreateUser` (auto-activates unknown emails when `AUTO_ACTIVATE_NEW_USERS` is on — dev convenience; flip to `"false"` for the B1 approval flow), `signMagicToken`/`verifyMagicToken` (jose HS256), `requestMagicLink` (prints the sign-in link to the console). +- `src/auth/config.ts` — Auth.js v5 Credentials provider (`magic-link`) + JWT session carrying `systemRole`. +- Routes: `/api/auth/[...nextauth]`, `/api/dev/magic-link` (POST `{email}`), `/api/dev/complete` (GET `?token=…`), `/api/admin` (chokepoint), and `/login` (magic-link sign-in UI). + +**Verification (all exit 0):** +- `pnpm typecheck` ✓ · `pnpm lint` ✓ · `pnpm test` ✓ (17 tests) · `pnpm build` ✓ +- **Acceptance** `pnpm test src/auth` green: 401 anonymous, 403 volunteer on `/admin`, 200 admin ✓ +- Runtime smoke test (dev server + Postgres on :5433): + - `GET /api/admin` (no session) → 401 `UNAUTHORIZED` ✓ + - `POST /api/dev/magic-link {email}` → 200, creates user (volunteer/active), returns + logs the sign-in link ✓ + - `GET /api/dev/complete?token=…` → 200, token verified, session established ✓ + - User persisted in DB as `active` ✓ + - `GET /login` → 200, renders ✓ + +**Decisions:** +- **Auto-activate new emails in dev** (`AUTO_ACTIVATE_NEW_USERS`, default on) so a volunteer can sign in as anyone without admin setup; admin can flip to `"false"` to require approval (B1). +- **Auth.js v5** (matches the docs' "Auth.js"; portable, no SaaS lock-in). JWT sessions, no DB adapter needed. (auth.js v5 ships as `next-auth@beta`; the `@auth/next` scope isn't published yet.) +- **`/admin` requires `admin.settings`** (admin-only) — matches the spec's `/admin/*` pages being admin-only. + +**Bugs fixed this phase (recorded for future reference):** +- Auth.js v5 session config uses `session.strategy: "jwt"`, not `session.jwt`. +- `req.json()` was unreliable here; `req.text()` + `JSON.parse` is the robust body read. +- An object schema must be parsed as an object: `bodySchema.safeParse({ email })`, not `safeParse(email)`. +- Turbopack dev + a production `.next/` from `pnpm build` conflict on `_buildManifest.js.tmp`; `rm -rf .next` before `next dev`. + +**Next: A4 — app shell (layout, nav, tokens, error + empty states, `/api/health`). diff --git a/docs/BUILD-PLAN.md b/docs/BUILD-PLAN.md index 771949a..0544857 100644 --- a/docs/BUILD-PLAN.md +++ b/docs/BUILD-PLAN.md @@ -121,9 +121,10 @@ Append-only, one line per unit. This survives context loss and is the first thin ## Done - A1 scaffold — `pnpm build` green — 2026-11-18 - A2 schema core — `pnpm db:migrate && pnpm db:seed` green — 2026-11-18 +- A3 auth — `pnpm test src/auth` green (401/403/200) — 2026-11-18 ## In progress -- A3 auth — check: 403 test — attempt 2 +- (none) ## Decisions (do not re-litigate) - Money/percent stored as integers. Dates: `occurs_on` = local date, `starts_at` = UTC. diff --git a/package.json b/package.json index b2b8889..11f56a0 100644 --- a/package.json +++ b/package.json @@ -20,8 +20,10 @@ "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "drizzle-orm": "^0.45.4", + "jose": "^6.2.17", "lucide-react": "^1.74.0", "next": "15.5.29", + "next-auth": "5.0.0-beta.32", "postgres": "^4.1.1", "react": "19.1.0", "react-dom": "19.1.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 14b15bd..90b7c75 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -23,12 +23,18 @@ importers: drizzle-orm: specifier: ^0.45.4 version: 0.45.4(postgres@4.1.1) + jose: + specifier: ^6.2.17 + version: 6.2.17 lucide-react: specifier: ^1.74.0 version: 1.74.0(@types/react@19.3.0)(react@19.1.0) next: specifier: 15.5.29 version: 15.5.29(@babel/core@7.29.13)(@types/node@20.19.43)(react-dom@19.1.0(react@19.1.0))(react@19.1.0) + next-auth: + specifier: 5.0.0-beta.32 + version: 5.0.0-beta.32(next@15.5.29(@babel/core@7.29.13)(@types/node@20.19.43)(react-dom@19.1.0(react@19.1.0))(react@19.1.0))(react@19.1.0) postgres: specifier: ^4.1.1 version: 4.1.1 @@ -112,6 +118,20 @@ packages: resolution: {integrity: sha512-U4+70Pc5ZS9osnCBCE5Jha/ciHM+Yp+CNMNC/7HvYbNRk1Ldd+f7qO65W5qfhu/TCv+/ozljlXXe9Nj8419DMA==} engines: {node: '>=10'} + '@auth/core@0.41.3': + resolution: {integrity: sha512-sJ3JMHHkXMD3aOjopv7mOBTO1Ocw4b0fAEXJBz6k7YHLpYQI6C40jCUPc5fNvUKxXRXNE1/sRISA15UrwWJBTw==} + peerDependencies: + '@simplewebauthn/browser': ^9.0.1 + '@simplewebauthn/server': ^9.0.2 + nodemailer: ^7.0.7 || ^8.0.5 + peerDependenciesMeta: + '@simplewebauthn/browser': + optional: true + '@simplewebauthn/server': + optional: true + nodemailer: + optional: true + '@babel/code-frame@7.29.7': resolution: {integrity: sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==} engines: {node: '>=6.9.0'} @@ -1039,6 +1059,9 @@ packages: '@oxc-project/types@0.156.0': resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==} + '@panva/hkdf@1.2.1': + resolution: {integrity: sha512-6oclG6Y3PiDFcoyk8srjLfVKyMfVCKJ27JwNPViuXziFpmdz+MZnZN/aKY0JGXgYuO/VghU0jcOAZgWXZ1Dmrw==} + '@radix-ui/react-compose-refs@1.1.5': resolution: {integrity: sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==} peerDependencies: @@ -2655,6 +2678,9 @@ packages: resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==} hasBin: true + jose@6.2.17: + resolution: {integrity: sha512-wOuK9V1yujQFH5S0ZWmLcDZN7+IKh9bUCC2ZPCf2HDlol3WWHy+PPyNjEI75FXRLMp3vDKQcupP59xhVU95hcg==} + js-tokens@4.0.0: resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} @@ -2902,6 +2928,22 @@ packages: natural-compare@1.4.0: resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} + next-auth@5.0.0-beta.32: + resolution: {integrity: sha512-CGlChIEWZ6LltNVxrE5yiySMID+Idpmry47JYA5lLwgD8Sx02a8M65VL0TWVz9nbnOioS/tCW/rP/0+mE7Qp4Q==} + peerDependencies: + '@simplewebauthn/browser': ^9.0.1 + '@simplewebauthn/server': ^9.0.2 + next: ^14.0.0-0 || ^15.0.0 || ^16.0.0 + nodemailer: ^7.0.7 || ^8.0.5 + react: ^18.2.0 || ^19.0.0 + peerDependenciesMeta: + '@simplewebauthn/browser': + optional: true + '@simplewebauthn/server': + optional: true + nodemailer: + optional: true + next@15.5.29: resolution: {integrity: sha512-93AMszTCdi9Az7fD5VzcWy46SHCdQF45+i53K0LpDc4dDXCwB9P1SxP1wBYZKW6dF3HJnz41jyEni1vmgCluiw==} engines: {node: ^18.18.0 || ^19.8.0 || >= 20.0.0} @@ -2939,6 +2981,9 @@ packages: resolution: {integrity: sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA==} engines: {node: '>=18'} + oauth4webapi@3.8.8: + resolution: {integrity: sha512-8N28E+a/oxfXWBgOMt+ZP/JUf/XR+IFbvkAEPP3gznXOMv9BpAAwiIj0TFNz3tGTPc0ZQ8zmWBNgN1nAys0gng==} + object-assign@4.1.1: resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==} engines: {node: '>=0.10.0'} @@ -3102,6 +3147,14 @@ packages: resolution: {integrity: sha512-C+y9x90UElAddDZmV4qOx9W53B61PO7cIqWz2dQsWlwswuq4mr8NEwytdGKboYbQlGZ3awrkTeNvcZiZNHnQ8A==} engines: {node: '>=20'} + preact-render-to-string@6.5.11: + resolution: {integrity: sha512-ubnauqoGczeGISiOh6RjX0/cdaF8v/oDXIjO85XALCQjwQP+SB4RDXXtvZ6yTYSjG+PC1QRP2AhPgCEsM2EvUw==} + peerDependencies: + preact: '>=10' + + preact@10.24.3: + resolution: {integrity: sha512-Z2dPnBnMUfyQfSQ+GBdsGa16hz35YmLmtTLhM169uW944hYL6xzTYkJjC07j+Wosz733pMWx0fgON3JNw1jJQA==} + prelude-ls@1.2.1: resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==} engines: {node: '>= 0.8.0'} @@ -3716,6 +3769,14 @@ snapshots: '@alloc/quick-lru@5.3.0': {} + '@auth/core@0.41.3': + dependencies: + '@panva/hkdf': 1.2.1 + jose: 6.2.17 + oauth4webapi: 3.8.8 + preact: 10.24.3 + preact-render-to-string: 6.5.11(preact@10.24.3) + '@babel/code-frame@7.29.7': dependencies: '@babel/helper-validator-identifier': 7.29.7 @@ -4435,6 +4496,8 @@ snapshots: '@oxc-project/types@0.156.0': {} + '@panva/hkdf@1.2.1': {} + '@radix-ui/react-compose-refs@1.1.5(@types/react@19.3.0)(react@19.1.0)': dependencies: react: 19.1.0 @@ -6081,6 +6144,8 @@ snapshots: jiti@2.7.0: {} + jose@6.2.17: {} + js-tokens@4.0.0: {} js-yaml@4.3.2: @@ -6289,6 +6354,12 @@ snapshots: natural-compare@1.4.0: {} + next-auth@5.0.0-beta.32(next@15.5.29(@babel/core@7.29.13)(@types/node@20.19.43)(react-dom@19.1.0(react@19.1.0))(react@19.1.0))(react@19.1.0): + dependencies: + '@auth/core': 0.41.3 + next: 15.5.29(@babel/core@7.29.13)(@types/node@20.19.43)(react-dom@19.1.0(react@19.1.0))(react@19.1.0) + react: 19.1.0 + next@15.5.29(@babel/core@7.29.13)(@types/node@20.19.43)(react-dom@19.1.0(react@19.1.0))(react@19.1.0): dependencies: '@next/env': 15.5.29 @@ -6331,6 +6402,8 @@ snapshots: path-key: 4.0.0 unicorn-magic: 0.3.0 + oauth4webapi@3.8.8: {} + object-assign@4.1.1: {} object-inspect@1.13.4: {} @@ -6504,6 +6577,12 @@ snapshots: powershell-utils@0.2.1: {} + preact-render-to-string@6.5.11(preact@10.24.3): + dependencies: + preact: 10.24.3 + + preact@10.24.3: {} + prelude-ls@1.2.1: {} pretty-format@27.5.1: diff --git a/src/app/api/admin/route.ts b/src/app/api/admin/route.ts new file mode 100644 index 0000000..dc0cf88 --- /dev/null +++ b/src/app/api/admin/route.ts @@ -0,0 +1,34 @@ +import { auth } from "@/auth/config"; +import { AuthError, requirePermission } from "@/auth/permissions"; +import type { SystemRole } from "@/auth/roles"; + +const JSON_HEADERS = { "content-type": "application/json" }; + +/** + * `/admin` chokepoint. Demonstrates the authorization gate: + * - anonymous -> 401 + * - volunteer/other -> 403 (lacks admin.settings) + * - admin -> 200 + * The permission here (`admin.settings`) is admin-only by the capability matrix. + */ +export const GET = async () => { + try { + const session = await auth(); + const user = requirePermission( + (session?.user as { systemRole: SystemRole } | null | undefined), + "admin.settings", + ); + return new Response(JSON.stringify({ ok: true, role: user.systemRole }), { + status: 200, + headers: JSON_HEADERS, + }); + } catch (e) { + if (e instanceof AuthError) { + return new Response(JSON.stringify({ error: e.message, code: e.code }), { + status: e.status, + headers: JSON_HEADERS, + }); + } + throw e; + } +}; diff --git a/src/app/api/auth/[...nextauth]/route.ts b/src/app/api/auth/[...nextauth]/route.ts new file mode 100644 index 0000000..5b4697e --- /dev/null +++ b/src/app/api/auth/[...nextauth]/route.ts @@ -0,0 +1,3 @@ +import { handlers } from "@/auth/config"; + +export const { GET, POST } = handlers; diff --git a/src/app/api/dev/complete/route.ts b/src/app/api/dev/complete/route.ts new file mode 100644 index 0000000..b7a3393 --- /dev/null +++ b/src/app/api/dev/complete/route.ts @@ -0,0 +1,28 @@ +import { NextRequest } from "next/server"; +import { signIn } from "@/auth/config"; +import { verifyMagicToken } from "@/auth/magic-link"; + +const JSON_HEADERS = { "content-type": "application/json" }; + +/** + * Completes a magic-link sign-in. GET /api/dev/complete?token=... verifies the + * one-time token and establishes the Auth.js session. + */ +export const GET = async (req: NextRequest) => { + const token = new URL(req.url, "http://localhost").searchParams.get( + "token", + ) ?? undefined; + const payload = await verifyMagicToken(token); + if (!payload) { + return new Response( + JSON.stringify({ error: "invalid or expired link" }), + { status: 400, headers: JSON_HEADERS }, + ); + } + + const result = await signIn("magic-link", { token, redirect: false }); + return new Response(JSON.stringify({ ok: true, url: result.url }), { + status: 200, + headers: JSON_HEADERS, + }); +}; diff --git a/src/app/api/dev/magic-link/route.ts b/src/app/api/dev/magic-link/route.ts new file mode 100644 index 0000000..52b109b --- /dev/null +++ b/src/app/api/dev/magic-link/route.ts @@ -0,0 +1,43 @@ +import { NextRequest } from "next/server"; +import { z } from "zod"; +import { requestMagicLink } from "@/auth/magic-link"; + +const JSON_HEADERS = { "content-type": "application/json" }; +const bodySchema = z.object({ email: z.string().email() }); + +/** + * Dev console magic-link transport. POST { email } -> resolves/creates the user + * (auto-activating when AUTO_ACTIVATE_NEW_USERS is on) and returns the sign-in + * link, which is also printed to the console. Swapping in Postmark later is a + * change inside `requestMagicLink` only. + */ +export const POST = async (req: NextRequest) => { + let email: string | undefined; + try { + const text = await req.text(); + email = text ? (JSON.parse(text) as { email?: string }).email : undefined; + } catch { + // fall through to validation, which rejects a missing email + } + + const parsed = bodySchema.safeParse({ email }); + if (!parsed.success) { + return new Response(JSON.stringify({ error: "a valid email is required" }), { + status: 400, + headers: JSON_HEADERS, + }); + } + + try { + const result = await requestMagicLink(parsed.data.email); + return new Response(JSON.stringify(result), { + status: 200, + headers: JSON_HEADERS, + }); + } catch { + return new Response( + JSON.stringify({ error: "failed to process request" }), + { status: 500, headers: JSON_HEADERS }, + ); + } +}; diff --git a/src/app/login/page.tsx b/src/app/login/page.tsx new file mode 100644 index 0000000..8b51509 --- /dev/null +++ b/src/app/login/page.tsx @@ -0,0 +1,80 @@ +"use client"; + +import { useState } from "react"; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; +import { Input } from "@/components/ui/input"; +import { Button } from "@/components/ui/button"; +import { Label } from "@/components/ui/label"; + +/** + * Magic-link sign-in (v1, no passwords). Enter an email; the dev console + * transport prints a sign-in link. Clicking it completes the Auth.js session. + * At launch there is no email/SMS delivery, so the link is shown here as a + * fallback and printed to the console (see /api/dev/magic-link). + */ +export default function LoginPage() { + const [email, setEmail] = useState(""); + const [status, setStatus] = useState<{ kind: "idle" | "sending" | "sent" | "error"; message?: string }>({ + kind: "idle", + }); + + async function onSubmit(e: React.FormEvent) { + e.preventDefault(); + setStatus({ kind: "sending" }); + try { + const res = await fetch("/api/dev/magic-link", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ email }), + }); + const body = (await res.json()) as { ok?: boolean; url?: string; error?: string }; + if (res.ok && body.url) { + setStatus({ kind: "sent", message: body.url }); + } else { + setStatus({ kind: "error", message: body.error ?? "Something went wrong." }); + } + } catch { + setStatus({ kind: "error", message: "Network error." }); + } + } + + return ( +