A3: auth (magic-link sign-in, requirePermission chokepoint, role enum)
- Auth.js v5 Credentials provider (magic-link) + JWT session carrying systemRole - src/auth: roles, permissions (feature-scoped matrix), magic-link dev console transport - requirePermission(user, perm) chokepoint -> AuthError(401/403) - Routes: /api/auth/[...nextauth], /api/dev/magic-link, /api/dev/complete, /api/admin, /login - Auto-activate new emails in dev (AUTO_ACTIVATE_NEW_USERS, flip to require approval) - Acceptance pnpm test src/auth green: 401 anonymous, 403 volunteer on /admin, 200 admin - Verified at runtime against Postgres on :5433
This commit is contained in:
@@ -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`).
|
||||
|
||||
+2
-1
@@ -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.
|
||||
|
||||
@@ -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",
|
||||
|
||||
Generated
+79
@@ -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:
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,3 @@
|
||||
import { handlers } from "@/auth/config";
|
||||
|
||||
export const { GET, POST } = handlers;
|
||||
@@ -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,
|
||||
});
|
||||
};
|
||||
@@ -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 },
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -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 (
|
||||
<div className="flex min-h-screen items-center justify-center px-4">
|
||||
<Card className="w-full max-w-sm">
|
||||
<CardHeader>
|
||||
<CardTitle>Sign in</CardTitle>
|
||||
<CardDescription>Enter your work email — no password required.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={onSubmit} className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="email">Email</Label>
|
||||
<Input
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
required
|
||||
autoComplete="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder="you@church.local"
|
||||
/>
|
||||
</div>
|
||||
<Button type="submit" disabled={status.kind === "sending"}>
|
||||
{status.kind === "sending" ? "Sending link…" : "Send sign-in link"}
|
||||
</Button>
|
||||
{status.kind === "sent" && status.message && (
|
||||
<p className="rounded border border-border bg-muted p-3 text-sm break-all">
|
||||
Sign-in link (dev console transport):<br />
|
||||
<span className="text-foreground underline">{status.message}</span>
|
||||
</p>
|
||||
)}
|
||||
{status.kind === "error" && status.message && (
|
||||
<p className="text-sm text-destructive">{status.message}</p>
|
||||
)}
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
// Mock the Auth.js session so the chokepoint is exercised without a server.
|
||||
vi.mock("@/auth/config", () => ({
|
||||
auth: vi.fn(),
|
||||
}));
|
||||
|
||||
import { auth } from "@/auth/config";
|
||||
import { GET } from "@/app/api/admin/route";
|
||||
import type { Mock } from "vitest";
|
||||
|
||||
const authMock = auth as unknown as Mock;
|
||||
|
||||
describe("/api/admin chokepoint", () => {
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
it("401 for anonymous (no session)", async () => {
|
||||
authMock.mockResolvedValue(null);
|
||||
const res = await GET();
|
||||
expect(res.status).toBe(401);
|
||||
const body = (await res.json()) as { code: string };
|
||||
expect(body.code).toBe("UNAUTHORIZED");
|
||||
});
|
||||
|
||||
it("403 for a volunteer on /admin", async () => {
|
||||
authMock.mockResolvedValue({
|
||||
user: { systemRole: "volunteer", email: "jordan@example.com" },
|
||||
});
|
||||
const res = await GET();
|
||||
expect(res.status).toBe(403);
|
||||
const body = (await res.json()) as { code: string };
|
||||
expect(body.code).toBe("FORBIDDEN");
|
||||
});
|
||||
|
||||
it("200 for an admin on /admin", async () => {
|
||||
authMock.mockResolvedValue({
|
||||
user: { systemRole: "admin", email: "admin@example.com" },
|
||||
});
|
||||
const res = await GET();
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as { ok: boolean; role: string };
|
||||
expect(body.ok).toBe(true);
|
||||
expect(body.role).toBe("admin");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* Auth.js (v5) configuration: the magic-link credentials provider plus a JWT
|
||||
* session that carries `systemRole` so `requirePermission()` can read it from
|
||||
* `session.user` without another DB hit.
|
||||
*
|
||||
* No database adapter is needed — JWT sessions are self-contained. The
|
||||
* credentials provider's `authorize` verifies the one-time magic-link token and
|
||||
* returns the active user.
|
||||
*/
|
||||
|
||||
import NextAuth from "next-auth";
|
||||
import Credentials from "next-auth/providers/credentials";
|
||||
import { getUser, verifyMagicToken } from "./magic-link";
|
||||
import type { SystemRole } from "./roles";
|
||||
|
||||
export const authConfig = {
|
||||
providers: [
|
||||
Credentials({
|
||||
id: "magic-link",
|
||||
name: "Magic Link",
|
||||
credentials: {
|
||||
token: { label: "Token", type: "text" },
|
||||
},
|
||||
async authorize(credentials) {
|
||||
const token = credentials?.token as string | undefined;
|
||||
const payload = await verifyMagicToken(token);
|
||||
if (!payload) return null;
|
||||
const user = await getUser(payload.email);
|
||||
if (!user || user.status !== "active" || user.deactivatedAt) return null;
|
||||
return {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
name: user.displayName ?? user.email,
|
||||
systemRole: user.systemRole,
|
||||
};
|
||||
},
|
||||
}),
|
||||
],
|
||||
session: { strategy: "jwt" },
|
||||
secret: process.env.AUTH_SECRET ?? process.env.NEXTAUTH_SECRET,
|
||||
pages: { signIn: "/login" },
|
||||
callbacks: {
|
||||
async jwt({ token, user }) {
|
||||
if (user) {
|
||||
(token as { systemRole?: SystemRole }).systemRole =
|
||||
(user as { systemRole?: SystemRole }).systemRole ?? "volunteer";
|
||||
}
|
||||
return token;
|
||||
},
|
||||
async session({ session, token }) {
|
||||
(session.user as { systemRole?: SystemRole }).systemRole =
|
||||
(token as { systemRole?: SystemRole }).systemRole ?? "volunteer";
|
||||
return session;
|
||||
},
|
||||
},
|
||||
} satisfies Parameters<typeof NextAuth>[0];
|
||||
|
||||
export const { handlers, auth, signIn, signOut } = NextAuth(authConfig);
|
||||
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* Magic-link sign-in with a dev console transport.
|
||||
*
|
||||
* At launch there is no email/SMS delivery wired up, so a "sent" magic link is
|
||||
* printed to the console (and returned to the caller) instead of emailed. A
|
||||
* volunteer copies/clicks the link to complete sign-in. This is the transport
|
||||
* the BUILD-PLAN calls "dev console transport"; swapping in Postmark later is a
|
||||
* change to `requestMagicLink` only — the sign-in path is unchanged.
|
||||
*
|
||||
* The `AUTO_ACTIVATE_NEW_USERS` flag (default on) auto-creates and activates
|
||||
* unknown emails so a volunteer can sign in as anyone without admin setup. Flip
|
||||
* it to `"false"` to require admin approval for new emails (the B1 invite flow).
|
||||
*/
|
||||
|
||||
import { db } from "@/db";
|
||||
import { users } from "@/db/schema";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { SignJWT, jwtVerify } from "jose";
|
||||
import { uuidv7 } from "@/lib/uuid";
|
||||
|
||||
const SECRET = new TextEncoder().encode(
|
||||
process.env.AUTH_SECRET ??
|
||||
process.env.NEXTAUTH_SECRET ??
|
||||
// Dev-only fallback; never ship relying on this.
|
||||
"media-team-hub-dev-insecure-secret",
|
||||
);
|
||||
|
||||
/**
|
||||
* Dev convenience: auto-activate unknown emails on sign-in. Set env
|
||||
* `AUTO_ACTIVATE_NEW_USERS=false` to require admin approval instead.
|
||||
*/
|
||||
export const AUTO_ACTIVATE_NEW_USERS =
|
||||
process.env.AUTO_ACTIVATE_NEW_USERS !== "false";
|
||||
|
||||
const APP_ORIGIN =
|
||||
process.env.AUTH_URL ??
|
||||
process.env.NEXTAUTH_URL ??
|
||||
process.env.APP_ORIGIN ??
|
||||
"http://localhost:3000";
|
||||
|
||||
export type MagicTokenPayload = { email: string; iat: number; exp: number };
|
||||
|
||||
export function normalizeEmail(email: string): string {
|
||||
return email.trim().toLowerCase();
|
||||
}
|
||||
|
||||
export async function getUser(email: string) {
|
||||
// Emails are stored lowercased; an exact match is correct (the lower() index
|
||||
// is an optimization, not a correctness requirement).
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(users)
|
||||
.where(eq(users.email, normalizeEmail(email)))
|
||||
.limit(1);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an existing user by email, or create a new one. New users are created as
|
||||
* `volunteer`; status is `active` when auto-activation is on, otherwise
|
||||
* `pending_approval`.
|
||||
*/
|
||||
export async function getOrCreateUser(email: string) {
|
||||
const normalized = normalizeEmail(email);
|
||||
const existing = await getUser(normalized);
|
||||
if (existing) return existing;
|
||||
|
||||
const localPart = normalized.split("@")[0] || "volunteer";
|
||||
const inserted = await db
|
||||
.insert(users)
|
||||
.values({
|
||||
id: uuidv7(),
|
||||
email: normalized,
|
||||
firstName: localPart,
|
||||
lastName: "",
|
||||
displayName: localPart,
|
||||
systemRole: "volunteer",
|
||||
status: AUTO_ACTIVATE_NEW_USERS ? "active" : "pending_approval",
|
||||
timezone: "America/New_York",
|
||||
createdAt: new Date(),
|
||||
})
|
||||
.onConflictDoNothing({ target: users.email })
|
||||
.returning();
|
||||
return inserted[0]!;
|
||||
}
|
||||
|
||||
export async function signMagicToken(email: string): Promise<string> {
|
||||
return new SignJWT({ email } as unknown as Record<string, unknown>)
|
||||
.setProtectedHeader({ alg: "HS256" })
|
||||
.setIssuedAt()
|
||||
.setExpirationTime("10m")
|
||||
.sign(SECRET);
|
||||
}
|
||||
|
||||
export async function verifyMagicToken(
|
||||
token: string | undefined,
|
||||
): Promise<MagicTokenPayload | null> {
|
||||
if (!token) return null;
|
||||
try {
|
||||
return (await jwtVerify(token, SECRET)).payload as MagicTokenPayload;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Dev console transport: resolve-or-create the user, sign a one-time token, and
|
||||
* print the sign-in link. Returns the link so callers (and tests) can see it.
|
||||
*/
|
||||
export async function requestMagicLink(email: string) {
|
||||
const user = await getOrCreateUser(email);
|
||||
const token = await signMagicToken(user.email);
|
||||
const url = `${APP_ORIGIN}/api/dev/complete?token=${encodeURIComponent(
|
||||
token,
|
||||
)}&email=${encodeURIComponent(user.email)}`;
|
||||
|
||||
// Console transport (dev): print the link so it can be clicked.
|
||||
console.log(
|
||||
`[magic-link] ${user.email} (${user.systemRole}, ${user.status}) -> ${url}`,
|
||||
);
|
||||
|
||||
return { ok: true as const, email: user.email, role: user.systemRole, url };
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { AuthError, hasPermission, requirePermission } from "./permissions";
|
||||
import type { SystemRole } from "./roles";
|
||||
|
||||
const user = (role: SystemRole) => ({ systemRole: role });
|
||||
|
||||
describe("hasPermission", () => {
|
||||
it("grants admin everything", () => {
|
||||
expect(hasPermission("admin", "admin.settings")).toBe(true);
|
||||
expect(hasPermission("admin", "volunteer.blackout")).toBe(true);
|
||||
});
|
||||
|
||||
it("bounds coordinator by feature (no admin.settings / design.theme)", () => {
|
||||
expect(hasPermission("coordinator", "schedule.publish")).toBe(true);
|
||||
expect(hasPermission("coordinator", "content.author")).toBe(true);
|
||||
expect(hasPermission("coordinator", "admin.settings")).toBe(false);
|
||||
expect(hasPermission("coordinator", "design.theme")).toBe(false);
|
||||
});
|
||||
|
||||
it("volunteer can serve but not manage users", () => {
|
||||
expect(hasPermission("volunteer", "volunteer.serve")).toBe(true);
|
||||
expect(hasPermission("volunteer", "users.manage")).toBe(false);
|
||||
});
|
||||
|
||||
it("no permission without a role", () => {
|
||||
expect(hasPermission(null, "schedule.view")).toBe(false);
|
||||
expect(hasPermission(undefined, "schedule.view")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("requirePermission", () => {
|
||||
it("throws 401 for anonymous", () => {
|
||||
let caught: unknown;
|
||||
try {
|
||||
requirePermission(null, "admin.settings");
|
||||
} catch (e) {
|
||||
caught = e;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(AuthError);
|
||||
expect((caught as AuthError).status).toBe(401);
|
||||
expect((caught as AuthError).code).toBe("UNAUTHORIZED");
|
||||
});
|
||||
|
||||
it("throws 403 for a volunteer on an admin-only permission", () => {
|
||||
let caught: unknown;
|
||||
try {
|
||||
requirePermission(user("volunteer"), "admin.settings");
|
||||
} catch (e) {
|
||||
caught = e;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(AuthError);
|
||||
expect((caught as AuthError).status).toBe(403);
|
||||
expect((caught as AuthError).code).toBe("FORBIDDEN");
|
||||
});
|
||||
|
||||
it("returns the user (no throw) for an admin on an admin-only permission", () => {
|
||||
const u = user("admin");
|
||||
expect(() => requirePermission(u, "admin.settings")).not.toThrow();
|
||||
expect(requirePermission(u, "admin.settings")).toBe(u);
|
||||
});
|
||||
|
||||
it("coordinator passes schedule.publish but not admin.settings", () => {
|
||||
expect(() => requirePermission(user("coordinator"), "schedule.publish")).not.toThrow();
|
||||
let caught: unknown;
|
||||
try {
|
||||
requirePermission(user("coordinator"), "admin.settings");
|
||||
} catch (e) {
|
||||
caught = e;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(AuthError);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* Feature-scoped permission model.
|
||||
*
|
||||
* The capability matrix in ARCHITECTURE §2.3 is expressed here as a static
|
||||
* role → permission map. A coordinator's scope is bound by *feature*, not by
|
||||
* role: full control over scheduling/people/events/training/notifications,
|
||||
* everything except design/theme and admin/system settings (ARCHITECTURE §2.3).
|
||||
*
|
||||
* This module is intentionally pure (no DB, no Next.js) so the chokepoint can
|
||||
* be unit-tested without a running server.
|
||||
*/
|
||||
|
||||
import type { SystemRole } from "./roles";
|
||||
|
||||
export type Permission =
|
||||
// Admin-only.
|
||||
| "admin.settings"
|
||||
| "design.theme"
|
||||
| "users.manage"
|
||||
| "training.author"
|
||||
// Coordinator + admin.
|
||||
| "content.author"
|
||||
| "schedule.publish"
|
||||
// Everyone authenticated.
|
||||
| "schedule.view"
|
||||
| "roster.view"
|
||||
| "volunteer.serve"
|
||||
| "volunteer.blackout";
|
||||
|
||||
/**
|
||||
* Permissions granted to each role, from the capability matrix.
|
||||
* `admin` is written out explicitly (all permissions) so the matrix is
|
||||
* auditable at a glance rather than derived.
|
||||
*/
|
||||
export const ROLE_PERMISSIONS: Readonly<Record<SystemRole, readonly Permission[]>> = {
|
||||
admin: [
|
||||
"admin.settings",
|
||||
"design.theme",
|
||||
"users.manage",
|
||||
"training.author",
|
||||
"content.author",
|
||||
"schedule.publish",
|
||||
"schedule.view",
|
||||
"roster.view",
|
||||
"volunteer.serve",
|
||||
"volunteer.blackout",
|
||||
],
|
||||
coordinator: [
|
||||
"content.author",
|
||||
"schedule.publish",
|
||||
"schedule.view",
|
||||
"roster.view",
|
||||
"volunteer.serve",
|
||||
"volunteer.blackout",
|
||||
],
|
||||
volunteer: [
|
||||
"schedule.view",
|
||||
"roster.view",
|
||||
"volunteer.serve",
|
||||
"volunteer.blackout",
|
||||
],
|
||||
trainee: ["schedule.view", "volunteer.serve", "volunteer.blackout"],
|
||||
};
|
||||
|
||||
export function hasPermission(
|
||||
role: SystemRole | null | undefined,
|
||||
permission: Permission,
|
||||
): boolean {
|
||||
if (!role) return false;
|
||||
return ROLE_PERMISSIONS[role].includes(permission);
|
||||
}
|
||||
|
||||
/**
|
||||
* Authorization error with an HTTP status, so a route handler can turn it into
|
||||
* a 401/403 response directly.
|
||||
*/
|
||||
export class AuthError extends Error {
|
||||
constructor(
|
||||
readonly status: 401 | 403,
|
||||
readonly code: "UNAUTHORIZED" | "FORBIDDEN",
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
this.name = "AuthError";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The authorization chokepoint. Returns the user when the check passes, or
|
||||
* throws AuthError(401) for an anonymous caller and AuthError(403) when the
|
||||
* role lacks the permission. Callers map the thrown status to an HTTP response.
|
||||
*/
|
||||
export function requirePermission(
|
||||
user: { systemRole: SystemRole } | null | undefined,
|
||||
permission: Permission,
|
||||
): { systemRole: SystemRole } {
|
||||
if (!user) {
|
||||
throw new AuthError(401, "UNAUTHORIZED", "Authentication required");
|
||||
}
|
||||
if (!hasPermission(user.systemRole, permission)) {
|
||||
throw new AuthError(
|
||||
403,
|
||||
"FORBIDDEN",
|
||||
`Role "${user.systemRole}" is not permitted to access "${permission}"`,
|
||||
);
|
||||
}
|
||||
return user;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
assertSystemRole,
|
||||
isAdmin,
|
||||
isCoordinator,
|
||||
isLeader,
|
||||
SYSTEM_ROLES,
|
||||
} from "./roles";
|
||||
|
||||
describe("role helpers", () => {
|
||||
it("lists the four system roles", () => {
|
||||
expect([...SYSTEM_ROLES].sort()).toEqual([
|
||||
"admin",
|
||||
"coordinator",
|
||||
"trainee",
|
||||
"volunteer",
|
||||
]);
|
||||
});
|
||||
|
||||
it("classifies roles", () => {
|
||||
expect(isAdmin("admin")).toBe(true);
|
||||
expect(isAdmin("volunteer")).toBe(false);
|
||||
expect(isCoordinator("coordinator")).toBe(true);
|
||||
expect(isLeader("coordinator")).toBe(true);
|
||||
expect(isLeader("volunteer")).toBe(false);
|
||||
expect(isLeader(null)).toBe(false);
|
||||
});
|
||||
|
||||
it("guards unknown values", () => {
|
||||
expect(assertSystemRole("admin")).toBe(true);
|
||||
expect(assertSystemRole("nope")).toBe(false);
|
||||
expect(assertSystemRole(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* System roles for Media Team Hub.
|
||||
*
|
||||
* Mirrors the `users.system_role` enum in src/db/schema.ts. Kept in its own
|
||||
* module so both the auth layer and the schema layer agree on the vocabulary.
|
||||
*/
|
||||
|
||||
export type SystemRole = "admin" | "coordinator" | "volunteer" | "trainee";
|
||||
|
||||
export const SYSTEM_ROLES: readonly SystemRole[] = [
|
||||
"admin",
|
||||
"coordinator",
|
||||
"volunteer",
|
||||
"trainee",
|
||||
] as const;
|
||||
|
||||
export const isAdmin = (
|
||||
role: SystemRole | null | undefined,
|
||||
): role is "admin" => role === "admin";
|
||||
|
||||
export const isCoordinator = (
|
||||
role: SystemRole | null | undefined,
|
||||
): role is "coordinator" => role === "coordinator";
|
||||
|
||||
/** Leaders = anyone who can build or edit the schedule. */
|
||||
export const isLeader = (role: SystemRole | null | undefined): boolean =>
|
||||
role === "admin" || role === "coordinator";
|
||||
|
||||
/** Runtime guard: coerce an unknown value to SystemRole or reject it. */
|
||||
export function assertSystemRole(value: unknown): value is SystemRole {
|
||||
return (SYSTEM_ROLES as readonly unknown[]).includes(value);
|
||||
}
|
||||
Reference in New Issue
Block a user