158 lines
5.2 KiB
TypeScript
158 lines
5.2 KiB
TypeScript
/**
|
|
* One-time platform setup: create or promote the first administrator.
|
|
*/
|
|
|
|
import crypto from 'crypto';
|
|
import argon2 from 'argon2';
|
|
import { config } from '../config';
|
|
import * as userRepository from '../repositories/userRepository';
|
|
import * as roleRepository from '../repositories/roleRepository';
|
|
import * as auditLogRepository from '../repositories/auditLogRepository';
|
|
import * as referralService from './referralService';
|
|
import { hashForIndex, encrypt } from '../utils/crypto';
|
|
|
|
export type SetupStatus = {
|
|
needsSetup: boolean;
|
|
setupEnabled: boolean;
|
|
};
|
|
|
|
function assertSetupAllowed(): void {
|
|
if (!config.setup.token || config.setup.token.length < 16) {
|
|
throw new Error(
|
|
'Platform setup is disabled. Set INITIAL_SETUP_TOKEN (min. 16 characters) in the server environment.'
|
|
);
|
|
}
|
|
}
|
|
|
|
function assertSetupToken(provided: string): void {
|
|
assertSetupAllowed();
|
|
const expected = config.setup.token;
|
|
const a = Buffer.from(provided);
|
|
const b = Buffer.from(expected);
|
|
if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
|
|
throw new Error('Invalid setup token');
|
|
}
|
|
}
|
|
|
|
/** True when at least one administrator exists (admin or super_admin in user_roles). */
|
|
async function hasPlatformAdministrator(): Promise<boolean> {
|
|
const adminCount = await roleRepository.countUsersWithRoleName('admin');
|
|
const superAdminCount = await roleRepository.countUsersWithRoleName('super_admin');
|
|
return adminCount > 0 || superAdminCount > 0;
|
|
}
|
|
|
|
export async function getSetupStatus(): Promise<SetupStatus> {
|
|
return {
|
|
needsSetup: !(await hasPlatformAdministrator()),
|
|
setupEnabled: Boolean(config.setup.token && config.setup.token.length >= 16),
|
|
};
|
|
}
|
|
|
|
async function ensureNoAdminYet(): Promise<void> {
|
|
if (await hasPlatformAdministrator()) {
|
|
throw new Error('Platform setup is already complete. An administrator account exists.');
|
|
}
|
|
}
|
|
|
|
export async function createFirstAdmin(input: {
|
|
email: string;
|
|
password: string;
|
|
fullName: string;
|
|
setupToken: string;
|
|
}): Promise<{ userId: string; referralCode: string; message: string }> {
|
|
await ensureNoAdminYet();
|
|
assertSetupToken(input.setupToken.trim());
|
|
|
|
const email = input.email.trim().toLowerCase();
|
|
if (!email || !email.includes('@')) throw new Error('Valid email is required');
|
|
if (!input.password || input.password.length < 8) {
|
|
throw new Error('Password must be at least 8 characters');
|
|
}
|
|
const fullName = input.fullName.trim();
|
|
if (!fullName) throw new Error('Full name is required');
|
|
|
|
const emailHash = hashForIndex(email);
|
|
const existing = await userRepository.findByEmailHash(emailHash);
|
|
if (existing) {
|
|
throw new Error('An account with this email already exists. Use “Promote existing user” instead.');
|
|
}
|
|
|
|
const adminRoleId = await userRepository.getRoleIdByName('admin');
|
|
const passwordHash = await argon2.hash(input.password, { type: argon2.argon2id });
|
|
const nameParts = fullName.split(/\s+/);
|
|
const firstName = nameParts[0] ?? fullName;
|
|
const lastName = nameParts.length > 1 ? nameParts.slice(1).join(' ') : null;
|
|
|
|
const user = await userRepository.create({
|
|
emailHash,
|
|
emailEncrypted: encrypt(email),
|
|
passwordHash,
|
|
roleId: adminRoleId,
|
|
firstName,
|
|
lastName,
|
|
});
|
|
|
|
await userRepository.setEmailVerified(user.id, true);
|
|
await roleRepository.setUserRoles(user.id, ['admin', 'super_admin']);
|
|
|
|
const referralCode = await referralService.bootstrapReferralRootAtPlatformSetup(user.id);
|
|
|
|
await auditLogRepository.create({
|
|
userId: user.id,
|
|
action: 'setup_first_admin_created',
|
|
resourceType: 'user',
|
|
resourceId: user.id,
|
|
metadata: { email, referral_code: referralCode },
|
|
});
|
|
|
|
return {
|
|
userId: user.id,
|
|
referralCode,
|
|
message: 'Administrator account created. You can now sign in.',
|
|
};
|
|
}
|
|
|
|
export async function promoteExistingUserToAdmin(input: {
|
|
email: string;
|
|
setupToken: string;
|
|
role?: 'admin' | 'moderator';
|
|
}): Promise<{ userId: string; role: string; referralCode: string; message: string }> {
|
|
await ensureNoAdminYet();
|
|
assertSetupToken(input.setupToken.trim());
|
|
|
|
const targetRole = input.role === 'moderator' ? 'moderator' : 'admin';
|
|
if (targetRole !== 'admin') {
|
|
throw new Error('The first platform account must be an administrator');
|
|
}
|
|
|
|
const email = input.email.trim().toLowerCase();
|
|
if (!email) throw new Error('Email is required');
|
|
|
|
const user = await userRepository.findByEmailHash(hashForIndex(email));
|
|
if (!user) {
|
|
throw new Error('No user found with this email. Register first or create a new administrator account.');
|
|
}
|
|
|
|
const roleId = await userRepository.getRoleIdByName(targetRole);
|
|
await userRepository.updateUserRole(user.id, roleId);
|
|
await roleRepository.setUserRoles(user.id, ['admin', 'super_admin']);
|
|
await userRepository.setEmailVerified(user.id, true);
|
|
|
|
const referralCode = await referralService.bootstrapReferralRootAtPlatformSetup(user.id);
|
|
|
|
await auditLogRepository.create({
|
|
userId: user.id,
|
|
action: 'setup_first_admin_promoted',
|
|
resourceType: 'user',
|
|
resourceId: user.id,
|
|
metadata: { email, role: targetRole, referral_code: referralCode },
|
|
});
|
|
|
|
return {
|
|
userId: user.id,
|
|
role: targetRole,
|
|
referralCode,
|
|
message: `User promoted to ${targetRole}. They can sign in with their existing password.`,
|
|
};
|
|
}
|