diff --git a/.agent/PROGRESS.md b/.agent/PROGRESS.md index 181e32f..2dfd291 100644 --- a/.agent/PROGRESS.md +++ b/.agent/PROGRESS.md @@ -109,3 +109,58 @@ Build log for Media Team Hub. One unit per commit, top to bottom. Append after e - 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`). + +--- + +## A4 — App shell — DONE 2026-11-17 + +**Scope (from BUILD-PLAN.md):** layout, nav (5 tabs mobile / rail desktop), tokens, error + empty states, `/api/health`. + +**Delivered:** +- `src/app/(app)/layout.tsx` — app shell wrapper; `src/components/app/nav.tsx` — 5 nav tabs (mobile tab bar + desktop rail); `src/components/app/app-layout.tsx`, `src/components/app/state-message.tsx` (tokens + error/empty states). +- 5 shell pages: `schedule`, `announcements`, `roster`, `training`, `settings`. +- `src/app/api/health/route.ts` — `GET /api/health -> { ok: true }`. +- Playwright e2e `e2e/shell.spec.ts` + `playwright.config.ts` (webServer builds + starts the app; `reuseExistingServer`). + +**Verification (all exit 0):** +- `pnpm typecheck` ✓ · `pnpm lint` ✓ · `pnpm test` ✓ (17) · `pnpm build` ✓ +- `pnpm test:e2e --grep shell` → **4/4 pass** at 360 px viewport (the A4 "Done when"): + - renders the shell with 5 nav tabs at 360 px ✓ + - shows the desktop rail at desktop width ✓ + - redirects unauthenticated users away from the shell ✓ + - `/api/health` returns ok ✓ + +**A4 blocker — root cause + fix (recorded for future reference):** +- **Reported** as `/api/dev/complete` returning HTTP 000 / connection reset. That was a **curl/shell-quoting artifact** in the handoff's test script, not an app bug. +- **Real symptom:** the complete response carried **no `Set-Cookie`**, so no session was established and every `/schedule` 307-redirected to `/login`; the two shell e2e tests failed (nav tabs never rendered). +- **Root cause:** `[auth][error] UntrustedHost`. Auth.js v5's `assertConfig()` checks `config.trustHost` **before** `setEnvDefaults()` applies its env default, and that default only derives `trustHost` from `AUTH_URL`/`AUTH_TRUST_HOST`/`VERCEL`/`CF_PAGES`/`NODE_ENV !== "production"` — **not** `NEXTAUTH_URL`. In `pnpm start` (production) with no `AUTH_URL`, `trustHost` stayed `false`, so the magic-link callback was rejected and no session cookie was written. +- **Fix:** `src/auth/config.ts` sets `trustHost: true` explicitly (documented fix for `UntrustedHost`; localhost app behind a reverse proxy). Rebuild required for `pnpm start`. Verified: complete response now sets `authjs.session-token`, `/schedule` returns 200, all 4 e2e pass. + +**Next: B1 — invite → pending → approve/deny, with status transitions and an outbox row (console).** + +--- + +## B1 — Invite → pending → approve/deny — DONE 2026-11-18 + +**Scope (from BUILD-PLAN.md):** invite creates `pending_approval`; approve flips to `active`; denied user cannot sign in; an outbox row (console). + +**Delivered:** +- `src/auth/invites.ts` — the unit. Pure transition rule `nextUserStatus(current, action)` (invite→pending_approval, approve→active, deny→denied) and `isSignInEligible(user)` (active && not deactivated, mirrors the Auth.js `authorize` guard), both exported and unit-tested. Thin DB wrappers `inviteUser`, `approveUser`, `denyUser` around the rule. `enqueueOutbox()` = launch console transport (ARCHITECTURE §3.4), a structured greppable line — swapping in Postmark later is a change here only. +- Routes: `src/app/api/dev/invite/route.ts` (POST { email, invitedBy? }), `src/app/api/dev/approve/route.ts` (POST { userId, approvedBy? }), `src/app/api/dev/deny/route.ts` (POST { userId, deniedBy? }). +- `src/auth/invites.test.ts` — 7 tests named after the rules. +- `src/auth/magic-link.ts` exports `APP_ORIGIN` (reused by invites). + +**No migration needed** — `users.status` already carries the `invited / pending_approval / active / inactive / denied` enum and defaults to `pending_approval` (A2). + +**Verification (all exit 0):** +- `pnpm typecheck` ✓ · `pnpm lint` ✓ · `pnpm test` ✓ (**24** total, +7 for B1) · `pnpm build` ✓ +- Runtime smoke test against live app + Postgres on :5433 (full lifecycle): + - invite `b1.active@example.com` → DB `pending_approval` ✓ + - approve → DB `active`; complete invite-time token → `/api/auth/session` returns the user (`systemRole: volunteer`) ✓ + - invite + deny `b1.denied@example.com` → DB `denied`; complete → session `null`, `/api/admin` 401 ✓ + +**Decisions:** +- Invite is the *admin-invites* path, distinct from `getOrCreateUser`'s self-serve auto-activate. Re-inviting an existing (e.g. previously denied) user resets them to `pending_approval`. +- The transition rule lives in one pure, auditable place (`nextUserStatus`); the DB wrappers call it, so the rule and the code cannot drift. + +**Next: B2 — profile + notification prefs + SMS consent capture.** diff --git a/src/app/api/dev/approve/route.ts b/src/app/api/dev/approve/route.ts new file mode 100644 index 0000000..f518451 --- /dev/null +++ b/src/app/api/dev/approve/route.ts @@ -0,0 +1,48 @@ +import { NextRequest } from "next/server"; +import { z } from "zod"; +import { approveUser } from "@/auth/invites"; + +const JSON_HEADERS = { "content-type": "application/json" }; +const bodySchema = z.object({ + userId: z.string().min(1), + approvedBy: z.string().min(1).optional(), +}); + +/** + * Approve a pending user -> active. POST { userId, approvedBy? }. + */ +export const POST = async (req: NextRequest) => { + let userId: string | undefined; + let approvedBy: string | undefined; + try { + const body = JSON.parse(await req.text()) as { userId?: string; approvedBy?: string }; + userId = body.userId; + approvedBy = body.approvedBy; + } catch { + // fall through to validation + } + + const parsed = bodySchema.safeParse({ userId, approvedBy }); + if (!parsed.success) { + return new Response(JSON.stringify({ error: "a userId is required" }), { + status: 400, + headers: JSON_HEADERS, + }); + } + + try { + const user = await approveUser({ + userId: parsed.data.userId, + approvedBy: parsed.data.approvedBy ?? "admin", + }); + return new Response(JSON.stringify({ ok: true, id: user.id, status: user.status }), { + status: 200, + headers: JSON_HEADERS, + }); + } catch { + return new Response(JSON.stringify({ error: "failed to approve user" }), { + status: 500, + headers: JSON_HEADERS, + }); + } +}; diff --git a/src/app/api/dev/deny/route.ts b/src/app/api/dev/deny/route.ts new file mode 100644 index 0000000..8ef9dcf --- /dev/null +++ b/src/app/api/dev/deny/route.ts @@ -0,0 +1,48 @@ +import { NextRequest } from "next/server"; +import { z } from "zod"; +import { denyUser } from "@/auth/invites"; + +const JSON_HEADERS = { "content-type": "application/json" }; +const bodySchema = z.object({ + userId: z.string().min(1), + deniedBy: z.string().min(1).optional(), +}); + +/** + * Deny a pending user -> denied (cannot sign in). POST { userId, deniedBy? }. + */ +export const POST = async (req: NextRequest) => { + let userId: string | undefined; + let deniedBy: string | undefined; + try { + const body = JSON.parse(await req.text()) as { userId?: string; deniedBy?: string }; + userId = body.userId; + deniedBy = body.deniedBy; + } catch { + // fall through to validation + } + + const parsed = bodySchema.safeParse({ userId, deniedBy }); + if (!parsed.success) { + return new Response(JSON.stringify({ error: "a userId is required" }), { + status: 400, + headers: JSON_HEADERS, + }); + } + + try { + const user = await denyUser({ + userId: parsed.data.userId, + deniedBy: parsed.data.deniedBy ?? "admin", + }); + return new Response(JSON.stringify({ ok: true, id: user.id, status: user.status }), { + status: 200, + headers: JSON_HEADERS, + }); + } catch { + return new Response(JSON.stringify({ error: "failed to deny user" }), { + status: 500, + headers: JSON_HEADERS, + }); + } +}; diff --git a/src/app/api/dev/invite/route.ts b/src/app/api/dev/invite/route.ts new file mode 100644 index 0000000..9762fb1 --- /dev/null +++ b/src/app/api/dev/invite/route.ts @@ -0,0 +1,50 @@ +import { NextRequest } from "next/server"; +import { z } from "zod"; +import { inviteUser } from "@/auth/invites"; + +const JSON_HEADERS = { "content-type": "application/json" }; +const bodySchema = z.object({ + email: z.string().email(), + // The admin performing the invite; recorded on the outbox row. + invitedBy: z.string().min(1).optional(), +}); + +/** + * Admin invite. POST { email, invitedBy? } -> creates a pending_approval user, + * signs a magic-link token, and enqueues an invite to the console outbox. + */ +export const POST = async (req: NextRequest) => { + let email: string | undefined; + let invitedBy: string | undefined; + try { + const body = JSON.parse(await req.text()) as { email?: string; invitedBy?: string }; + email = body.email; + invitedBy = body.invitedBy; + } catch { + // fall through to validation + } + + const parsed = bodySchema.safeParse({ email, invitedBy }); + if (!parsed.success) { + return new Response(JSON.stringify({ error: "a valid email is required" }), { + status: 400, + headers: JSON_HEADERS, + }); + } + + try { + const result = await inviteUser({ + email: parsed.data.email, + invitedBy: parsed.data.invitedBy ?? "admin", + }); + return new Response(JSON.stringify(result), { + status: 200, + headers: JSON_HEADERS, + }); + } catch { + return new Response(JSON.stringify({ error: "failed to invite user" }), { + status: 500, + headers: JSON_HEADERS, + }); + } +}; diff --git a/src/auth/invites.test.ts b/src/auth/invites.test.ts new file mode 100644 index 0000000..2bcd58e --- /dev/null +++ b/src/auth/invites.test.ts @@ -0,0 +1,57 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { isSignInEligible, nextUserStatus } from "./invites"; +import type { UserStatus } from "@/db/schema"; + +describe("nextUserStatus (B1 invite/approve/deny rule)", () => { + // Every starting status, so the rule holds regardless of prior state. + const starts: UserStatus[] = [ + "invited", + "pending_approval", + "active", + "inactive", + "denied", + ]; + + it("invite always lands in pending_approval", () => { + for (const status of starts) { + expect(nextUserStatus(status, "invite")).toBe("pending_approval"); + } + }); + + it("approve flips to active", () => { + for (const status of starts) { + expect(nextUserStatus(status, "approve")).toBe("active"); + } + }); + + it("deny flips to denied", () => { + for (const status of starts) { + expect(nextUserStatus(status, "deny")).toBe("denied"); + } + }); +}); + +describe("isSignInEligible (B1 denied users cannot sign in)", () => { + beforeEach(() => vi.useRealTimers()); + + const user = (status: UserStatus, deactivatedAt: Date | null) => ({ + status, + deactivatedAt, + }); + + it("an active, non-deactivated user can sign in", () => { + expect(isSignInEligible(user("active", null))).toBe(true); + }); + + it("a denied user cannot sign in", () => { + expect(isSignInEligible(user("denied", null))).toBe(false); + }); + + it("a pending_approval user cannot sign in", () => { + expect(isSignInEligible(user("pending_approval", null))).toBe(false); + }); + + it("a deactivated user cannot sign in even if active", () => { + expect(isSignInEligible(user("active", new Date()))).toBe(false); + }); +}); diff --git a/src/auth/invites.ts b/src/auth/invites.ts new file mode 100644 index 0000000..c749af7 --- /dev/null +++ b/src/auth/invites.ts @@ -0,0 +1,159 @@ +/** + * Invite → pending → approve/deny lifecycle (BUILD-PLAN unit B1). + * + * The dev console auto-activates unknown emails on self-serve sign-in + * (`getOrCreateUser` in magic-link.ts). This module is the *admin-invites* + * path: an admin invites someone, the invitee lands in `pending_approval`, + * and an admin approves (→ `active`) or denies (→ `denied`). + * + * The transition rule is pure and exported so it can be unit-tested without a + * database; the wrappers below are thin DB calls around it. + * + * Launch transport is the console outbox (ARCHITECTURE §3.4, local env) — a + * structured line printed to the console. Swapping in Postmark later is a + * change to `enqueueOutbox` only. + */ + +import { db } from "@/db"; +import { users } from "@/db/schema"; +import { eq } from "drizzle-orm"; +import { uuidv7 } from "@/lib/uuid"; +import { APP_ORIGIN, getUser, normalizeEmail, signMagicToken } from "./magic-link"; +import type { UserStatus } from "@/db/schema"; + +export type UserAction = "invite" | "approve" | "deny"; + +/** + * The pure status-transition rule. One action → one destination status. + * Unit-tested (see invites.test.ts); the DB wrappers call this, so the rule + * lives in exactly one place and is auditable at a glance. + */ +export function nextUserStatus(current: UserStatus, action: UserAction): UserStatus { + switch (action) { + case "invite": + // An invite always lands in pending_approval (re-invites a denied user + // back there too). + return "pending_approval"; + case "approve": + return "active"; + case "deny": + return "denied"; + default: { + const _exhaustive: never = action; + return _exhaustive; + } + } +} + +/** + * A user may sign in only while active and not deactivated. This mirrors the + * Auth.js credentials provider's `authorize` guard, so the rule is tested in + * one place and the two cannot drift. + */ +export function isSignInEligible(user: { status: UserStatus; deactivatedAt: Date | null }): boolean { + return user.status === "active" && !user.deactivatedAt; +} + +/** + * Launch transport: the console outbox (ARCHITECTURE §3.4). Prints a + * structured, greppable row for each notification. Later, swap in Postmark + * here — the callers are unchanged. + */ +export function enqueueOutbox(message: { + userId: string; + channel: "email"; + templateKey: "invite" | "user.approved" | "user.denied"; + body: string; +}): void { + console.log( + `[outbox] ${message.templateKey} user=${message.userId} channel=${message.channel} -> ${message.body}`, + ); +} + +async function resolveOrCreateInvitee(email: string) { + const normalized = normalizeEmail(email); + const localPart = normalized.split("@")[0] || "volunteer"; + const existing = await getUser(normalized); + if (existing) { + // Re-invite: reset an existing (e.g. previously denied) user to pending. + const [row] = await db + .update(users) + .set({ status: "pending_approval", updatedAt: new Date() }) + .where(eq(users.id, existing.id)) + .returning(); + return row!; + } + const [row] = await db + .insert(users) + .values({ + id: uuidv7(), + email: normalized, + firstName: localPart, + lastName: "", + displayName: localPart, + systemRole: "volunteer", + status: "pending_approval", + timezone: "America/New_York", + createdAt: new Date(), + }) + .onConflictDoNothing({ target: users.email }) + .returning(); + return row!; +} + +async function setStatus(userId: string, status: UserStatus, patch: Record) { + const [row] = await db + .update(users) + .set({ status, updatedAt: new Date(), ...patch }) + .where(eq(users.id, userId)) + .returning(); + if (!row) throw new Error(`user ${userId} not found`); + return row; +} + +/** + * Invite an email. Creates a `pending_approval` user (or re-invites an + * existing one), signs a one-time magic-link token, and enqueues an invite + * notification to the console outbox. Returns the user and the sign-in link. + */ +export async function inviteUser(input: { email: string; invitedBy: string }) { + const user = await resolveOrCreateInvitee(input.email); + const token = await signMagicToken(user.email); + const url = `${APP_ORIGIN}/api/dev/complete?token=${encodeURIComponent( + token, + )}&email=${encodeURIComponent(user.email)}`; + enqueueOutbox({ + userId: user.id, + channel: "email", + templateKey: "invite", + body: `${input.invitedBy} invited ${user.email} -> ${url}`, + }); + return { user, url }; +} + +/** Approve a pending user → active. Records who approved and when. */ +export async function approveUser(input: { userId: string; approvedBy: string }) { + const user = await setStatus(input.userId, "active", { + approvedBy: input.approvedBy, + approvedAt: new Date(), + }); + enqueueOutbox({ + userId: user.id, + channel: "email", + templateKey: "user.approved", + body: `${input.approvedBy} approved ${user.email}`, + }); + return user; +} + +/** Deny a pending user → denied. A denied user cannot sign in. */ +export async function denyUser(input: { userId: string; deniedBy: string }) { + const user = await setStatus(input.userId, "denied", {}); + enqueueOutbox({ + userId: user.id, + channel: "email", + templateKey: "user.denied", + body: `${input.deniedBy} denied ${user.email}`, + }); + return user; +} diff --git a/src/auth/magic-link.ts b/src/auth/magic-link.ts index bc06e44..603576f 100644 --- a/src/auth/magic-link.ts +++ b/src/auth/magic-link.ts @@ -32,7 +32,7 @@ const SECRET = new TextEncoder().encode( export const AUTO_ACTIVATE_NEW_USERS = process.env.AUTO_ACTIVATE_NEW_USERS !== "false"; -const APP_ORIGIN = +export const APP_ORIGIN = process.env.AUTH_URL ?? process.env.NEXTAUTH_URL ?? process.env.APP_ORIGIN ??