1. Summary of changes
The installer-created account is no longer special. "Owner" is now literally renamed Administrator and behaves exactly like the existing role/permission system already allowed — the codebase turned out to already define "administrator" structurally (a StaffProfile whose role holds MANAGE_STAFF), not as a name or a business.ownerId-style field, and last-administrator protection already existed. The real work was: closing the gap between that and a full admin-management UI, fixing two OTP-migration bugs the new spec's requirements exposed, and making the existing protection transactional.
Businesses can now have any number of Administrators, added via Invite Administrator (name + email → OTP-verified before access), promoted/demoted via the existing staff role dropdown (now intercepted with a confirmation dialog when it crosses the Administrator boundary), or removed via the existing deactivate flow.
Two real bugs found and fixed, both required for the spec's "unverified email must not get access":
Invitation acceptance (/invite/accept) never actually verified an OTP — it silently relied on a sign-in path that would have failed for every real invitee. It now sends and verifies a real code, reusing the shared OtpCodeStep UI.
A newly-invited (not-yet-accepted) account could sign in via plain email OTP before ever touching the invite link, because sign-in only checked "does a User row exist," not whether it was verified. Fixed in the shared OTP service, benefiting every invitation, not just administrators'.
Last-administrator protection (already existed) is now transactional — a SELECT ... FOR UPDATE lock on the business row closes the race where two concurrent removals of two different administrators could both succeed.
Administrators (any staff member, in fact) can now change their own email — new address must be OTP-verified before it replaces the login email.
No hidden installer privilege: confirmed via code audit and a live install → the account is a plain Administrator-role staff member, provable identically via the Team UI as any later-added one.
NextChair Manager and platform Super Administrator are untouched.
2. Prisma/database changes
No schema changes. One data-only migration: prisma/migrations/20260905214944_administrator_role_rename — UPDATE Role SET name = 'Administrator' WHERE name = 'Owner' AND isSystem = true. Runs through the normal migration-deploy process; not something to run by hand.
3. How Administrator roles are represented
A per-business Role row named "Administrator" (was "Owner"), isSystem: true, holding every Permission — created identically at install and in dev seed data. This is what "Invite"/"Make Administrator" assign.
Whether a StaffProfile currently counts as an Administrator is permission-based (holds MANAGE_STAFF), not a name check — the same definition the codebase already used for last-owner protection (isStaffAdministrator in staff.service.ts). This is deliberately reused rather than introduced, and stays correct if a business ever gets a custom role that also grants MANAGE_STAFF.
No Business.adminId-style field anywhere — confirmed none existed before this work either.
4. How administrator invitations work
Reuses the existing StaffInvitation model and createStaffProfile/createInvitation machinery verbatim — a new inviteAdministratorAction just pre-selects the Administrator role and uses a minimal Name+Email form (invite-administrator-form.tsx). Acceptance (accept-invitation.ts) now requires a real OTP code sent to the invited email before the account activates — expiry (7 days), resend, and revoke are all the pre-existing invitation mechanics (revoke = the existing deactivate action, relabeled "Revoke Invitation" while pending).
5. How last-administrator protection is enforced
Server-side only, inside staff.service.ts's updateStaffAsOwner (role change) and deactivateStaff (remove), each wrapped in prisma.$transaction that first locks the business row (SELECT ... FOR UPDATE), then counts other active Administrators before allowing the change. Verified with a genuine concurrency test (two simultaneous removals against a 2-admin business) and manually in-browser (see below).
6. Installation flow changes
Only the role name and one line of wizard copy changed ("This becomes the first Administrator..."). No structural UX change — still collects name/email, verifies via OTP, creates/activates the account, assigns the role, exactly as before.
7. Files changed
New: the migration; email-change.service.ts + change-email.ts action + change-email-section.tsx; invite-administrator-form.tsx + add-administrator/page.tsx; 3 new integration test files.
Modified — core: staff.service.ts (transactional protection, isStaffAdministrator), staff-invitation.service.ts, otp.service.ts (onlyIfUserExists fix, email-change purpose), default-permissions.ts, permissions.ts, auth.ts (JWT email-refresh, simplified finalize path).
Modified — actions/UI: owner/actions/staff.ts, staff-detail-panel.tsx, team/page.tsx, add-staff-form.tsx, accept-invitation.ts/form/page, otp-code-step.tsx, profile-form.tsx, installer files, seed.ts, plus a terminology sweep ("owner" → "administrator" copy in breaks.ts/time-off.ts/staff-emails.ts/profile page).
8. Manual testing steps
Sign in as the seeded owner → /owner/team shows an Administrator badge and an "Invite Administrator" icon next to "+". Invite someone, accept via /invite/accept?token=... printed to the terminal (code also prints there) — they land signed in with full Manage access. Promote/demote any staff member via the role dropdown on their detail page — crossing the Administrator boundary shows a confirmation dialog. With only one Administrator left, attempting to demote or deactivate them shows "You can't remove the only administrator. Add another administrator first." Change your own email from Profile settings — the new address must be OTP-verified before it replaces the old one.
9. Deployment steps on the VPS
None beyond the normal deploy process — the migration is a standard Prisma migration that prisma migrate deploy (whatever already runs it there) will pick up automatically. No new environment variables. No changes to NextChair Manager or its authentication.
Verification performed: tsc/lint/unit — all clean; full test:integration — 219 passed (up from 207, all new); full test:e2e — same 36/37 as before this work (the 1 failure is a pre-existing, auth-unrelated flake unrelated to any of this); a full live manual pass covering every scenario above, including the last-administrator block and the email-change JWT-refresh behavior.
This commit is contained in:
33 files changed
+1348
-265
No files matched your search
@@ -1,44 +1,80 @@
|
||||
"use server";
|
||||
|
||||
import { signIn } from "@/auth";
|
||||
import { signInVerifySchema } from "@/features/auth/schemas";
|
||||
import { requestOtp, verifyOtp } from "@/lib/auth/otp.service";
|
||||
import { prisma } from "@/lib/db/prisma";
|
||||
import { getRequestIp } from "@/lib/security/request-ip";
|
||||
import { getEmailProvider } from "@/services/notifications/providers";
|
||||
import { acceptInvitation, validateInvitationToken } from "@/services/staff/staff-invitation.service";
|
||||
|
||||
export interface AcceptInvitationResult {
|
||||
success: boolean;
|
||||
export interface InvitationOtpActionResult {
|
||||
ok: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
function invalidTokenMessage(reason: "INVALID_TOKEN" | "EXPIRED" | "ALREADY_ACCEPTED"): string {
|
||||
return reason === "EXPIRED"
|
||||
? "This invitation link has expired. Ask an administrator to send you a new one."
|
||||
: reason === "ALREADY_ACCEPTED"
|
||||
? "This invitation has already been used — try signing in instead."
|
||||
: "This invitation link isn't valid.";
|
||||
}
|
||||
|
||||
/**
|
||||
* Public — the invited person has no account/session yet. No password or
|
||||
* OTP step: the invite token itself (delivered only to the invited
|
||||
* email) is already the trust anchor — see acceptInvitation's own doc
|
||||
* comment. Signs in via src/auth.ts's token-gated finalize path,
|
||||
* reusing this same token as the required secret.
|
||||
* Step 1 of accepting an invitation — sends a code to the invited email.
|
||||
* Public (the invitee has no account/session yet), but only reachable with
|
||||
* a valid, unexpired, unaccepted invitation token, so there's no need for
|
||||
* requestSignInOtpAction's `onlyIfUserExists` secrecy here: a real
|
||||
* invitation already proves this exact email was chosen by an
|
||||
* administrator, not guessed by the caller.
|
||||
*/
|
||||
export async function acceptInvitationAction(token: string): Promise<AcceptInvitationResult> {
|
||||
export async function requestInvitationOtpAction(token: string): Promise<InvitationOtpActionResult> {
|
||||
const check = await validateInvitationToken(prisma, token);
|
||||
if (!check.valid) {
|
||||
const message =
|
||||
check.reason === "EXPIRED"
|
||||
? "This invitation link has expired. Ask the business owner to send you a new one."
|
||||
: check.reason === "ALREADY_ACCEPTED"
|
||||
? "This invitation has already been used — try signing in instead."
|
||||
: "This invitation link isn't valid.";
|
||||
return { success: false, error: message };
|
||||
}
|
||||
if (!check.valid) return { ok: false, error: invalidTokenMessage(check.reason) };
|
||||
|
||||
const email = check.invitation.staff.user.email;
|
||||
if (!email) return { ok: false, error: "This invitation link isn't valid." };
|
||||
|
||||
const ip = await getRequestIp();
|
||||
const result = await requestOtp(prisma, {
|
||||
email,
|
||||
purpose: "staff-invite",
|
||||
ip,
|
||||
senderName: check.invitation.staff.business.name,
|
||||
emailProvider: getEmailProvider(),
|
||||
});
|
||||
if (!result.ok) return { ok: false, error: "Too many attempts. Please try again later." };
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Step 2 — verifies the code, activates the account (acceptInvitation sets
|
||||
* emailVerified + StaffInvitation.acceptedAt), then signs in with the same
|
||||
* still-valid (verified-but-not-yet-consumed) code — same shape as
|
||||
* src/features/auth/actions/register.ts's verifyRegisterOtpAction, and for
|
||||
* the same reason: verifyOtp doesn't consume the code, only the following
|
||||
* signIn's own authorize() call does, so it can safely run again here.
|
||||
*/
|
||||
export async function verifyInvitationOtpAction(token: string, code: string): Promise<InvitationOtpActionResult> {
|
||||
const check = await validateInvitationToken(prisma, token);
|
||||
if (!check.valid) return { ok: false, error: invalidTokenMessage(check.reason) };
|
||||
|
||||
const email = check.invitation.staff.user.email;
|
||||
if (!email) return { ok: false, error: "This invitation link isn't valid." };
|
||||
const parsed = signInVerifySchema.safeParse({ email, code });
|
||||
if (!parsed.success) return { ok: false, error: "Enter the 6-digit code." };
|
||||
|
||||
const ip = await getRequestIp();
|
||||
const verified = await verifyOtp(prisma, email, parsed.data.code, ip);
|
||||
if (!verified.ok) return { ok: false, error: "Incorrect or expired code. Please try again." };
|
||||
|
||||
const result = await acceptInvitation(prisma, { token });
|
||||
if (!result.success) {
|
||||
return { success: false, error: "Couldn't accept this invitation. Please try again." };
|
||||
return { ok: false, error: result.reason ? invalidTokenMessage(result.reason) : "Couldn't accept this invitation. Please try again." };
|
||||
}
|
||||
|
||||
await signIn("credentials", {
|
||||
email: check.invitation.staff.user.email,
|
||||
finalize: "true",
|
||||
token,
|
||||
redirectTo: "/staff",
|
||||
});
|
||||
await signIn("credentials", { email, code: parsed.data.code, redirectTo: "/staff" });
|
||||
|
||||
return { success: true };
|
||||
return { ok: true };
|
||||
}
|
||||
@@ -2,37 +2,55 @@
|
||||
|
||||
import { useState, useTransition } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { acceptInvitationAction } from "@/features/auth/actions/accept-invitation";
|
||||
import { OtpCodeStep } from "@/features/auth/components/otp-code-step";
|
||||
import { requestInvitationOtpAction, verifyInvitationOtpAction } from "@/features/auth/actions/accept-invitation";
|
||||
|
||||
export function AcceptInvitationForm({ token, businessName }: { token: string; businessName: string }) {
|
||||
export function AcceptInvitationForm({ token, email, businessName }: { token: string; email: string; businessName: string }) {
|
||||
const [codeRequested, setCodeRequested] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
const onAccept = () => {
|
||||
const sendCode = () => {
|
||||
setError(null);
|
||||
startTransition(async () => {
|
||||
const result = await acceptInvitationAction(token);
|
||||
if (!result.success) {
|
||||
const result = await requestInvitationOtpAction(token);
|
||||
if (!result.ok) {
|
||||
setError(result.error ?? "Something went wrong. Please try again.");
|
||||
return;
|
||||
}
|
||||
// On success, acceptInvitationAction signs the user in and redirects
|
||||
// server-side — nothing else to do here.
|
||||
setCodeRequested(true);
|
||||
});
|
||||
};
|
||||
|
||||
const verifyCode = async (code: string) => {
|
||||
const result = await verifyInvitationOtpAction(token, code);
|
||||
// On success, verifyInvitationOtpAction signs the user in and redirects
|
||||
// server-side — nothing else to do here.
|
||||
return { ok: result.ok, error: result.error };
|
||||
};
|
||||
|
||||
const resendCode = async () => {
|
||||
const result = await requestInvitationOtpAction(token);
|
||||
return { ok: result.ok, error: result.error };
|
||||
};
|
||||
|
||||
if (codeRequested) {
|
||||
return <OtpCodeStep email={email} onVerify={verifyCode} onResend={resendCode} verifyLabel="Accept & Sign In" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<p className="text-muted text-sm">
|
||||
You've been invited to join <span className="text-ink font-bold">{businessName}</span>. This link
|
||||
confirms it's really you — no password needed.
|
||||
You've been invited to join <span className="text-ink font-bold">{businessName}</span>. Verify your
|
||||
email to get started — no password needed.
|
||||
</p>
|
||||
{error && (
|
||||
<p role="alert" className="text-danger text-sm font-medium">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<Button type="button" className="mt-4 w-full" isLoading={isPending} onClick={onAccept}>
|
||||
Accept & Sign In
|
||||
<Button type="button" className="mt-4 w-full" isLoading={isPending} onClick={sendCode}>
|
||||
Send Verification Code
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -13,19 +13,21 @@ export interface OtpCodeStepProps {
|
||||
email: string;
|
||||
onVerify: (code: string) => Promise<OtpVerifyResult>;
|
||||
onResend: () => Promise<OtpVerifyResult>;
|
||||
onChangeEmail: () => void;
|
||||
/** Omit when the email isn't user-chosen at this step (e.g. accept-invitation, where it's fixed by the invitation itself) — hides the "Change email" link entirely rather than wiring it to a no-op. */
|
||||
onChangeEmail?: () => void;
|
||||
verifyLabel?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The "enter the code" half of every OTP flow in the app — reused
|
||||
* verbatim by sign-in, registration, and the installer's administrator
|
||||
* step (embedded inline there, not a redirect — see install-wizard.tsx).
|
||||
* Deliberately owns only this step: each caller manages its own "email"
|
||||
* vs "code" phase and renders whatever step-1 fields it needs (sign-in
|
||||
* needs just an email, registration/installer also need a name) before
|
||||
* mounting this component — trying to also genericize step 1 fought the
|
||||
* different field sets more than it saved.
|
||||
* verbatim by sign-in, registration, the installer's administrator step
|
||||
* (embedded inline there, not a redirect — see install-wizard.tsx), and
|
||||
* invitation acceptance. Deliberately owns only this step: each caller
|
||||
* manages its own "email" vs "code" phase and renders whatever step-1
|
||||
* fields it needs (sign-in needs just an email, registration/installer
|
||||
* also need a name, invitation acceptance needs none — the email comes
|
||||
* from the invitation) before mounting this component — trying to also
|
||||
* genericize step 1 fought the different field sets more than it saved.
|
||||
*/
|
||||
export function OtpCodeStep({ email, onVerify, onResend, onChangeEmail, verifyLabel = "Verify" }: OtpCodeStepProps) {
|
||||
const [code, setCode] = useState("");
|
||||
@@ -89,9 +91,11 @@ export function OtpCodeStep({ email, onVerify, onResend, onChangeEmail, verifyLa
|
||||
>
|
||||
Resend code
|
||||
</button>
|
||||
<button type="button" onClick={onChangeEmail} className="text-muted font-bold underline">
|
||||
Change email
|
||||
</button>
|
||||
{onChangeEmail && (
|
||||
<button type="button" onClick={onChangeEmail} className="text-muted font-bold underline">
|
||||
Change email
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
Reference in new issue
Block a user