Files
glenloch-media/src/auth/magic-link.ts
T
Tiel Coder 5f0b94af6a 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.
2026-11-17 23:46:07 +00:00

124 lines
4.0 KiB
TypeScript

/**
* 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";
export 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 };
}