355 lines
13 KiB
JavaScript
355 lines
13 KiB
JavaScript
"use strict";
|
|
/**
|
|
* RBAC service — custom roles CRUD and permission assignment.
|
|
*/
|
|
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;
|
|
};
|
|
})();
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.listPermissions = listPermissions;
|
|
exports.listRoles = listRoles;
|
|
exports.getRole = getRole;
|
|
exports.createRole = createRole;
|
|
exports.updateRole = updateRole;
|
|
exports.deleteRole = deleteRole;
|
|
exports.bumpUserTokenOnRoleChange = bumpUserTokenOnRoleChange;
|
|
exports.listAdminUsers = listAdminUsers;
|
|
exports.getAdminUser = getAdminUser;
|
|
exports.applyUserPermissionChanges = applyUserPermissionChanges;
|
|
const roleRepository = __importStar(require("../repositories/roleRepository"));
|
|
const auditLogRepository = __importStar(require("../repositories/auditLogRepository"));
|
|
const userRepository = __importStar(require("../repositories/userRepository"));
|
|
const permissionCatalog_1 = require("../rbac/permissionCatalog");
|
|
const crypto_1 = require("../utils/crypto");
|
|
async function listPermissions() {
|
|
const rows = await roleRepository.listAllPermissions();
|
|
const categories = {};
|
|
for (const row of rows) {
|
|
const cat = row.category ?? 'other';
|
|
if (!categories[cat])
|
|
categories[cat] = [];
|
|
categories[cat].push({
|
|
key: row.key,
|
|
description: row.description,
|
|
category: row.category,
|
|
resource: row.resource,
|
|
action: row.action,
|
|
});
|
|
}
|
|
return { categories };
|
|
}
|
|
async function listRoles() {
|
|
const roles = await roleRepository.listAllRoles();
|
|
const result = [];
|
|
for (const role of roles) {
|
|
const permissionKeys = await roleRepository.getRolePermissionKeys(role.id);
|
|
const userCount = await roleRepository.countUsersWithRoleId(role.id);
|
|
result.push({
|
|
id: role.id,
|
|
name: role.name,
|
|
description: role.description,
|
|
isSystem: role.is_system,
|
|
permissionKeys,
|
|
userCount,
|
|
});
|
|
}
|
|
return result;
|
|
}
|
|
async function getRole(roleId) {
|
|
const role = await roleRepository.findRoleById(roleId);
|
|
if (!role)
|
|
return null;
|
|
const permissionKeys = await roleRepository.getRolePermissionKeys(roleId);
|
|
const userCount = await roleRepository.countUsersWithRoleId(roleId);
|
|
const assigned = await roleRepository.listUsersForRole(roleId);
|
|
return {
|
|
id: role.id,
|
|
name: role.name,
|
|
description: role.description,
|
|
isSystem: role.is_system,
|
|
permissionKeys,
|
|
userCount,
|
|
assignedUsers: assigned.map((u) => ({
|
|
id: u.id,
|
|
email: decryptEmail(u.email_encrypted),
|
|
fullName: fullName(u.first_name, u.last_name),
|
|
})),
|
|
};
|
|
}
|
|
function validateCustomRoleName(name) {
|
|
const trimmed = name.trim().toLowerCase().replace(/\s+/g, '_');
|
|
if (trimmed.length < 2 || trimmed.length > 50) {
|
|
throw new Error('Role name must be between 2 and 50 characters');
|
|
}
|
|
if (!/^[a-z][a-z0-9_]*$/.test(trimmed)) {
|
|
throw new Error('Role name must start with a letter and contain only letters, numbers, and underscores');
|
|
}
|
|
if ((0, permissionCatalog_1.isSystemRole)(trimmed)) {
|
|
throw new Error('This name is reserved for a system role');
|
|
}
|
|
return trimmed;
|
|
}
|
|
function validatePermissionKeys(keys) {
|
|
const catalogKeys = new Set(permissionCatalog_1.PERMISSION_CATALOG.map((p) => p.key));
|
|
const unique = [...new Set(keys)];
|
|
for (const k of unique) {
|
|
if (!catalogKeys.has(k)) {
|
|
throw new Error(`Unknown permission: ${k}`);
|
|
}
|
|
}
|
|
return unique;
|
|
}
|
|
async function createRole(input, actorUserId) {
|
|
const name = validateCustomRoleName(input.name);
|
|
const existing = await roleRepository.findRoleByName(name);
|
|
if (existing)
|
|
throw new Error('A role with this name already exists');
|
|
const permissionKeys = validatePermissionKeys(input.permissionKeys);
|
|
const role = await roleRepository.createRole({
|
|
name,
|
|
description: input.description?.trim() || null,
|
|
isSystem: false,
|
|
});
|
|
await roleRepository.setRolePermissions(role.id, permissionKeys);
|
|
await auditLogRepository.create({
|
|
userId: actorUserId,
|
|
action: 'rbac_role_created',
|
|
resourceType: 'role',
|
|
resourceId: String(role.id),
|
|
metadata: { name, permissionKeys },
|
|
});
|
|
return (await getRole(role.id));
|
|
}
|
|
async function updateRole(roleId, input, actorUserId) {
|
|
const role = await roleRepository.findRoleById(roleId);
|
|
if (!role)
|
|
throw new Error('Role not found');
|
|
let newName = role.name;
|
|
if (input.name !== undefined) {
|
|
const normalizedIncoming = input.name.trim().toLowerCase().replace(/\s+/g, '_');
|
|
if (role.is_system) {
|
|
if (normalizedIncoming !== role.name) {
|
|
throw new Error('System role names cannot be changed');
|
|
}
|
|
}
|
|
else {
|
|
newName = validateCustomRoleName(input.name);
|
|
const existing = await roleRepository.findRoleByName(newName);
|
|
if (existing && existing.id !== roleId) {
|
|
throw new Error('A role with this name already exists');
|
|
}
|
|
}
|
|
}
|
|
const description = input.description !== undefined ? input.description.trim() || null : role.description;
|
|
await roleRepository.updateRole(roleId, { name: newName, description });
|
|
if (input.permissionKeys !== undefined) {
|
|
const permissionKeys = validatePermissionKeys(input.permissionKeys);
|
|
await roleRepository.setRolePermissions(roleId, permissionKeys);
|
|
await bumpTokenVersionForRoleUsers(roleId);
|
|
}
|
|
await auditLogRepository.create({
|
|
userId: actorUserId,
|
|
action: 'rbac_role_updated',
|
|
resourceType: 'role',
|
|
resourceId: String(roleId),
|
|
metadata: { name: newName, permissionKeys: input.permissionKeys },
|
|
});
|
|
return (await getRole(roleId));
|
|
}
|
|
async function deleteRole(roleId, actorUserId) {
|
|
const role = await roleRepository.findRoleById(roleId);
|
|
if (!role)
|
|
throw new Error('Role not found');
|
|
if (role.is_system)
|
|
throw new Error('System roles cannot be deleted');
|
|
const userCount = await roleRepository.countUsersWithRoleId(roleId);
|
|
if (userCount > 0) {
|
|
throw new Error(`Cannot delete role: ${userCount} user(s) still assigned. Remove the role from all users first.`);
|
|
}
|
|
await roleRepository.deleteRole(roleId);
|
|
await auditLogRepository.create({
|
|
userId: actorUserId,
|
|
action: 'rbac_role_deleted',
|
|
resourceType: 'role',
|
|
resourceId: String(roleId),
|
|
metadata: { name: role.name },
|
|
});
|
|
}
|
|
/** Invalidate JWTs for all users with this role after permission changes. */
|
|
async function bumpTokenVersionForRoleUsers(roleId) {
|
|
const userIds = await roleRepository.listUserIdsWithRole(roleId);
|
|
for (const userId of userIds) {
|
|
await userRepository.incrementTokenVersion(userId);
|
|
}
|
|
}
|
|
async function bumpUserTokenOnRoleChange(userId) {
|
|
await userRepository.incrementTokenVersion(userId);
|
|
}
|
|
function decryptEmail(encrypted) {
|
|
if (!encrypted)
|
|
return null;
|
|
try {
|
|
return (0, crypto_1.decrypt)(encrypted);
|
|
}
|
|
catch {
|
|
return null;
|
|
}
|
|
}
|
|
function fullName(first, last) {
|
|
const name = [first, last].filter(Boolean).join(' ').trim();
|
|
return name || null;
|
|
}
|
|
async function assertAdministrativeUser(userId) {
|
|
const user = await userRepository.getForAdmin(userId);
|
|
if (!user)
|
|
throw new Error('User not found');
|
|
const roles = await roleRepository.getUserRoleNames(userId);
|
|
const overrides = await roleRepository.getUserPermissionOverrides(userId);
|
|
const isAdminStaff = roles.some((r) => r !== 'user') || overrides.length > 0;
|
|
if (!isAdminStaff) {
|
|
throw new Error('Permission overrides can only be applied to administrative users');
|
|
}
|
|
return roles;
|
|
}
|
|
async function listAdminUsers(filters) {
|
|
const search = filters.search?.trim() ?? '';
|
|
let searchHash = null;
|
|
let searchText = null;
|
|
if (search.includes('@')) {
|
|
searchHash = (0, crypto_1.hashForIndex)(search.toLowerCase());
|
|
}
|
|
else if (search) {
|
|
searchText = search;
|
|
}
|
|
const result = await roleRepository.listAdministrativeUsers({
|
|
searchHash,
|
|
searchText,
|
|
role: filters.role ?? null,
|
|
exception: filters.exception ?? 'all',
|
|
permission: filters.permission ?? null,
|
|
limit: filters.limit ?? 50,
|
|
offset: filters.offset ?? 0,
|
|
});
|
|
return {
|
|
total: result.total,
|
|
users: result.users.map((u) => ({
|
|
id: u.id,
|
|
email: decryptEmail(u.email_encrypted),
|
|
fullName: fullName(u.first_name, u.last_name),
|
|
isEnabled: u.is_enabled,
|
|
roles: u.roles,
|
|
inheritedCount: u.inherited_count,
|
|
allowCount: u.allow_count,
|
|
denyCount: u.deny_count,
|
|
effectiveCount: u.effective_count,
|
|
})),
|
|
};
|
|
}
|
|
async function getAdminUser(userId) {
|
|
const user = await userRepository.getForAdmin(userId);
|
|
if (!user)
|
|
return null;
|
|
const [roles, inherited, overrides, breakdown, names] = await Promise.all([
|
|
roleRepository.getUserRoleNames(userId),
|
|
roleRepository.getUserInheritedPermissionKeys(userId),
|
|
roleRepository.getUserPermissionOverrides(userId),
|
|
roleRepository.getUserPermissionBreakdown(userId),
|
|
roleRepository.getUserNameFields(userId),
|
|
]);
|
|
const allow = overrides.filter((o) => o.effect === 'allow');
|
|
const deny = overrides.filter((o) => o.effect === 'deny');
|
|
const items = breakdown.map((p) => ({
|
|
key: p.key,
|
|
description: p.description,
|
|
category: p.category,
|
|
inherited: p.inherited,
|
|
directAllow: p.directAllow,
|
|
directDeny: p.directDeny,
|
|
effective: (p.inherited || p.directAllow) && !p.directDeny,
|
|
sources: p.sources,
|
|
}));
|
|
const categories = {};
|
|
for (const item of items) {
|
|
const cat = item.category ?? 'other';
|
|
if (!categories[cat])
|
|
categories[cat] = [];
|
|
categories[cat].push(item);
|
|
}
|
|
return {
|
|
user: {
|
|
id: user.id,
|
|
email: decryptEmail(user.email_encrypted),
|
|
fullName: fullName(names?.first_name ?? null, names?.last_name ?? null),
|
|
isEnabled: user.is_enabled,
|
|
roles,
|
|
inheritedCount: inherited.length,
|
|
allowCount: allow.length,
|
|
denyCount: deny.length,
|
|
effectiveCount: items.filter((p) => p.effective).length,
|
|
},
|
|
permissions: items,
|
|
categories,
|
|
};
|
|
}
|
|
async function applyUserPermissionChanges(userId, changes, actorUserId) {
|
|
if (!changes.length)
|
|
throw new Error('At least one permission change is required');
|
|
await assertAdministrativeUser(userId);
|
|
const catalogKeys = new Set(permissionCatalog_1.PERMISSION_CATALOG.map((p) => p.key));
|
|
for (const change of changes) {
|
|
if (!catalogKeys.has(change.key)) {
|
|
throw new Error(`Unknown permission: ${change.key}`);
|
|
}
|
|
}
|
|
await roleRepository.applyUserPermissionOverrideChanges(userId, changes, actorUserId);
|
|
await bumpUserTokenOnRoleChange(userId);
|
|
for (const change of changes) {
|
|
const action = change.action === 'allow'
|
|
? 'admin_user_permission_override_added'
|
|
: change.action === 'deny'
|
|
? 'admin_user_permission_override_removed'
|
|
: 'admin_user_permission_override_reset';
|
|
await auditLogRepository.create({
|
|
userId: actorUserId,
|
|
action,
|
|
resourceType: 'user',
|
|
resourceId: userId,
|
|
metadata: { permissionKey: change.key, effect: change.action },
|
|
});
|
|
}
|
|
const updated = await getAdminUser(userId);
|
|
if (!updated)
|
|
throw new Error('User not found');
|
|
return updated;
|
|
}
|
|
//# sourceMappingURL=rbacService.js.map
|