Multi-administrator support
CI / ci (push) Canceled after 0s

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:
Stefan Lazic committed 2026-09-05 23:32:54 +01:00
1 parent 94aa1b2f26
commit 973187dcc7
33 files changed
+1348 -265

No files matched your search

+14 -7
View File
@@ -55,7 +55,7 @@ const rateLimitBypassed = process.env.E2E_TEST_MODE === "true";
// the exact same reason (account/state enumeration via timing).
const DUMMY_HASH = bcrypt.hashSync("nextchair-otp-timing-safety-placeholder", BCRYPT_COST);
export type OtpPurpose = "login" | "register" | "install" | "staff-invite";
export type OtpPurpose = "login" | "register" | "install" | "staff-invite" | "email-change";
function normalizeEmail(email: string): string {
return email.trim().toLowerCase();
@@ -76,10 +76,17 @@ export interface RequestOtpOptions {
senderName?: string;
/**
* Login-specific: only actually generates/sends a code if a User already
* exists for this email. The caller still gets the same {ok:true} result
* either way — this is what keeps "do not reveal whether an email
* address exists" true for the sign-in page without silently creating a
* dead OTP row (or emailing a stranger) for a typo'd/unregistered address.
* exists for this email *and* that email has been verified at least
* once. The caller still gets the same {ok:true} result either way —
* this is what keeps "do not reveal whether an email address exists"
* true for the sign-in page without silently creating a dead OTP row (or
* emailing a stranger) for a typo'd/unregistered address. Requiring
* emailVerified too (not just existence) is what stops a newly-invited-
* but-not-yet-accepted staff/administrator account from signing in
* before ever touching their invitation link — createStaffProfile
* creates the User row immediately, well before invitation acceptance
* sets emailVerified (see staff-invitation.service.ts's acceptInvitation
* and accept-invitation.ts).
*/
onlyIfUserExists?: boolean;
/** Required, not defaulted internally — see this file's own import comment for why. Real callers pass getEmailProvider(); tests pass a MockEmailProvider. */
@@ -105,9 +112,9 @@ export async function requestOtp(db: Db, options: RequestOtpOptions): Promise<Re
}
if (options.onlyIfUserExists) {
const user = await db.user.findUnique({ where: { email }, select: { id: true } });
const user = await db.user.findUnique({ where: { email }, select: { id: true, emailVerified: true } });
// Same generic {ok:true} either way — see this option's own doc comment.
if (!user) return { ok: true };
if (!user || !user.emailVerified) return { ok: true };
}
// ~1% of requests — see cleanupExpiredOtps's own comment.
+12 -7
View File
@@ -38,13 +38,18 @@ export const isSuperAdmin = cache(async (userId: string): Promise<boolean> => {
});
/**
* A Super Administrator has every permission an Owner has — OWNER_PERMISSIONS
* (src/lib/roles/default-permissions.ts) already IS the full Permission enum,
* so short-circuiting true here rather than granting a StaffProfile/Role is
* exactly equivalent, without giving the Super Admin a StaffProfile row at
* all (see docs/phase-9-summary.md, "Super Administrator" — this is what
* keeps them out of the Team list, barber picker, and appointment FKs
* structurally rather than via a filter).
* A platform-level Super Administrator has every permission a business
* Administrator has — ADMINISTRATOR_PERMISSIONS (src/lib/roles/default-
* permissions.ts) already IS the full Permission enum, so short-circuiting
* true here rather than granting a StaffProfile/Role is exactly equivalent,
* without giving the Super Admin a StaffProfile row at all (see docs/
* phase-9-summary.md, "Super Administrator" — this is what keeps them out
* of the Team list, barber picker, and appointment FKs structurally rather
* than via a filter). These are two distinct concepts: a business
* Administrator is a per-business Role assignment (see docs/phase-6-
* summary.md); the platform Super Administrator is a single global flag
* provisioned only by scripts/ensure-super-admin.ts. This work does not
* change the Super Administrator or NextChair Manager in any way.
*/
export async function hasPermission(userId: string, permission: Permission): Promise<boolean> {
if (await isSuperAdmin(userId)) return true;
+11 -4
View File
@@ -5,11 +5,18 @@ import { Permission } from "@/generated/prisma/enums";
* The two system roles' permission sets — single source of truth, used by
* both `prisma/seed.ts` (dev/demo fixtures) and the installation wizard
* (`src/features/installation/installer.service.ts`, the real "first
* owner" creation path). Previously duplicated only in seed.ts; extracted
* here in Phase 8 so a permission added to one path can't silently miss
* the other (see docs/phase-8-summary.md).
* Administrator" creation path). Previously duplicated only in seed.ts;
* extracted here in Phase 8 so a permission added to one path can't
* silently miss the other (see docs/phase-8-summary.md).
*
* "Administrator" (formerly "Owner" — renamed so the role reads as what it
* is: an assignable permission set, not a special account type. See
* docs/phase-6-summary.md, "Roles and permissions" — every "is this an
* administrator" check in the app is already keyed on holding
* MANAGE_STAFF, not on this role's name, so the rename is cosmetic to the
* authorization logic and only changes what gets displayed/assigned.)
*/
export const OWNER_PERMISSIONS: Permission[] = [
export const ADMINISTRATOR_PERMISSIONS: Permission[] = [
Permission.MANAGE_BUSINESS_PROFILE,
Permission.MANAGE_BOOKING_RULES,
Permission.MANAGE_SERVICES,