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:
Tiel Coder
2026-11-17 19:34:06 +00:00
parent a68e1c6277
commit 3cd932e1a1
16 changed files with 779 additions and 1 deletions
+34
View File
@@ -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;
}
};
+3
View File
@@ -0,0 +1,3 @@
import { handlers } from "@/auth/config";
export const { GET, POST } = handlers;
+28
View File
@@ -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,
});
};
+43
View File
@@ -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 },
);
}
};
+80
View File
@@ -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>
);
}
+45
View File
@@ -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");
});
});
+58
View File
@@ -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);
+123
View File
@@ -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 };
}
+72
View File
@@ -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);
});
});
+108
View File
@@ -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;
}
+34
View File
@@ -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);
});
});
+32
View File
@@ -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);
}