unit(B1): invite -> pending -> approve/deny with console outbox

Admin-invite lifecycle (BUILD-PLAN Phase B, depends A3):
- src/auth/invites.ts: pure nextUserStatus() rule (invite->pending_approval,
  approve->active, deny->denied) + isSignInEligible() mirroring the Auth.js
  authorize guard; thin DB wrappers inviteUser/approveUser/denyUser;
  enqueueOutbox() console transport (launch, ARCHITECTURE 3.4).
- Routes: /api/dev/invite, /api/dev/approve, /api/dev/deny.
- src/auth/invites.test.ts: 7 tests named after the rules.
- magic-link.ts exports APP_ORIGIN.
No migration: users.status already carries the enum (A2).
Verify: typecheck, lint, 24 unit tests (+7), build, 4 e2e all green; runtime
smoke test confirms invite->pending, approve->active signs in, deny->denied
gets no session.
This commit is contained in:
Tiel Coder
2026-11-17 23:46:07 +00:00
parent 3451bced82
commit 5f0b94af6a
7 changed files with 418 additions and 1 deletions
+48
View File
@@ -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,
});
}
};
+48
View File
@@ -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,
});
}
};
+50
View File
@@ -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,
});
}
};
+57
View File
@@ -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);
});
});
+159
View File
@@ -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<string, unknown>) {
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;
}
+1 -1
View File
@@ -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 ??