games_app/backend/dist/services/setupService.js
2026-06-29 15:01:23 +02:00

151 lines
6.1 KiB
JavaScript

"use strict";
/**
* One-time platform setup: create or promote the first administrator.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSetupStatus = getSetupStatus;
exports.createFirstAdmin = createFirstAdmin;
exports.promoteExistingUserToAdmin = promoteExistingUserToAdmin;
const crypto_1 = __importDefault(require("crypto"));
const argon2_1 = __importDefault(require("argon2"));
const config_1 = require("../config");
const userRepository = __importStar(require("../repositories/userRepository"));
const auditLogRepository = __importStar(require("../repositories/auditLogRepository"));
const crypto_2 = require("../utils/crypto");
function assertSetupAllowed() {
if (!config_1.config.setup.token || config_1.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) {
assertSetupAllowed();
const expected = config_1.config.setup.token;
const a = Buffer.from(provided);
const b = Buffer.from(expected);
if (a.length !== b.length || !crypto_1.default.timingSafeEqual(a, b)) {
throw new Error('Invalid setup token');
}
}
async function getSetupStatus() {
const adminCount = await userRepository.countUsersWithRole('admin');
return {
needsSetup: adminCount === 0,
setupEnabled: Boolean(config_1.config.setup.token && config_1.config.setup.token.length >= 16),
};
}
async function ensureNoAdminYet() {
const adminCount = await userRepository.countUsersWithRole('admin');
if (adminCount > 0) {
throw new Error('Platform setup is already complete. An administrator account exists.');
}
}
async function createFirstAdmin(input) {
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 = (0, crypto_2.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_1.default.hash(input.password, { type: argon2_1.default.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: (0, crypto_2.encrypt)(email),
passwordHash,
roleId: adminRoleId,
firstName,
lastName,
});
await userRepository.setEmailVerified(user.id, true);
await auditLogRepository.create({
userId: user.id,
action: 'setup_first_admin_created',
resourceType: 'user',
resourceId: user.id,
metadata: { email },
});
return {
userId: user.id,
message: 'Administrator account created. You can now sign in.',
};
}
async function promoteExistingUserToAdmin(input) {
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((0, crypto_2.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 userRepository.setEmailVerified(user.id, true);
await auditLogRepository.create({
userId: user.id,
action: 'setup_first_admin_promoted',
resourceType: 'user',
resourceId: user.id,
metadata: { email, role: targetRole },
});
return {
userId: user.id,
role: targetRole,
message: `User promoted to ${targetRole}. They can sign in with their existing password.`,
};
}
//# sourceMappingURL=setupService.js.map