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
+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 };
}