games_app/backend/dist-test-faq/services/fundApprovalService.js

691 lines
30 KiB
JavaScript

"use strict";
/**
* Approval workflow for sensitive platform fund operations (N-of-M + auto-execute).
*/
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.FundApprovalError = void 0;
exports.executeApprovedRequest = executeApprovedRequest;
exports.createFundRequest = createFundRequest;
exports.castVote = castVote;
exports.approveFundRequest = approveFundRequest;
exports.rejectFundRequest = rejectFundRequest;
exports.cancelFundRequest = cancelFundRequest;
exports.getFundRequest = getFundRequest;
exports.listFundRequests = listFundRequests;
exports.draftPolicyChange = draftPolicyChange;
exports.listApprovalPolicies = listApprovalPolicies;
exports.listPolicyRevisions = listPolicyRevisions;
exports.updateUserRoles = updateUserRoles;
const fundOperationRequestRepository = __importStar(require("../repositories/fundOperationRequestRepository"));
const fundOperationVoteRepository = __importStar(require("../repositories/fundOperationVoteRepository"));
const approvalPolicyRepository = __importStar(require("../repositories/approvalPolicyRepository"));
const roleRepository = __importStar(require("../repositories/roleRepository"));
const rbacService_1 = require("./rbacService");
const auditLogRepository = __importStar(require("../repositories/auditLogRepository"));
const securityNotificationService = __importStar(require("./securityNotificationService"));
const adminCreditService = __importStar(require("./adminCreditService"));
const treasuryService = __importStar(require("./treasuryService"));
const bonusPoolRepository = __importStar(require("../repositories/bonusPoolRepository"));
const sweepService = __importStar(require("./sweepService"));
const approvalPolicyEngine = __importStar(require("./approvalPolicyEngine"));
class FundApprovalError extends Error {
constructor(message) {
super(message);
this.name = 'FundApprovalError';
}
}
exports.FundApprovalError = FundApprovalError;
async function toDto(row, viewerId) {
const votes = await fundOperationVoteRepository.listByRequest(row.id);
const decision = row.policy_snapshot ?? {
mode: 'require_approvals',
quorum: row.required_quorum ?? [{ role: 'super_admin', count: 1 }],
forbid_self_approve: true,
};
const quorum = Array.isArray(decision.quorum) ? decision.quorum : [];
const approveVotes = votes.filter((v) => v.decision === 'approve');
const progress = approvalPolicyEngine.countQuorumProgress(quorum, approveVotes);
let policyName = null;
if (row.policy_id) {
const p = await approvalPolicyRepository.findById(row.policy_id);
policyName = p?.name ?? null;
}
let canVote = false;
if (viewerId && row.status === 'pending_approval') {
const existing = votes.find((v) => v.voter_id === viewerId);
if (!existing) {
if (decision.forbid_self_approve && viewerId === row.requested_by) {
canVote = false;
}
else {
const roles = await roleRepository.getUserRoleNames(viewerId);
const perms = await roleRepository.getUserPermissions(viewerId);
const hasApprovePerm = perms.includes('fund_operation.approve');
canVote =
hasApprovePerm &&
approvalPolicyEngine.voterFillsOpenSlot(quorum, approveVotes, roles, perms);
}
}
}
return {
id: row.id,
operationType: row.operation_type,
status: row.status,
payload: row.payload,
requestedBy: row.requested_by,
approvedBy: row.approved_by,
rejectionReason: row.rejection_reason,
executionResult: row.execution_result,
createdAt: row.created_at.toISOString(),
approvedAt: row.approved_at?.toISOString() ?? null,
executedAt: row.executed_at?.toISOString() ?? null,
policyId: row.policy_id,
policyName,
requiredQuorum: quorum,
forbidSelfApprove: decision.forbid_self_approve !== false,
amountRaw: row.amount_raw,
assetCode: row.asset_code,
network: row.network,
fromAddress: row.from_address,
toAddress: row.to_address,
votes: votes.map((v) => ({
voterId: v.voter_id,
decision: v.decision,
reason: v.reason,
voterRoles: v.voter_roles,
createdAt: v.created_at.toISOString(),
})),
quorumProgress: { required: progress.required, approved: progress.approved },
canVote,
};
}
function extractContext(operationType, payload) {
const amountRaw = payload.amountRaw ??
payload.amount ??
null;
const walletTypeId = typeof payload.walletTypeId === 'number'
? payload.walletTypeId
: payload.walletTypeId != null
? Number(payload.walletTypeId)
: null;
const network = payload.network ?? null;
const assetCode = payload.assetCode ?? payload.walletCode ?? null;
const fromAddress = payload.fromAddress ?? null;
const toAddress = payload.toAddress ?? null;
let sourceKind = 'any';
let destKind = 'any';
if (operationType === 'treasury_hot_to_cold' || operationType === 'treasury_hot_to_cold_gas') {
sourceKind = 'hot';
destKind = 'cold';
}
else if (operationType === 'treasury_cold_to_hot' || operationType === 'treasury_cold_to_hot_gas') {
sourceKind = 'cold';
destKind = 'hot';
}
else if (operationType === 'sweep_batch' || operationType === 'sweep_manual') {
sourceKind = 'hd';
destKind = 'cold';
}
else if (operationType === 'user_withdrawal') {
sourceKind = 'hot';
destKind = 'user';
}
return { amountRaw, walletTypeId, network, assetCode, fromAddress, toAddress, sourceKind, destKind };
}
async function executeApprovedRequest(request, approverId) {
const approvedBy = approverId;
switch (request.operation_type) {
case 'ledger_credit': {
const { userId, walletTypeId, adjustmentType, amountRaw, reason } = request.payload;
return adminCreditService.grantLedgerCredit({
userId,
walletTypeId,
adjustmentType,
amountRaw,
reason,
approvedBy,
requestedBy: request.requested_by,
});
}
case 'treasury_cold_to_hot': {
const { walletTypeId, amountRaw, notes } = request.payload;
return treasuryService.requestColdToHotFunding(request.requested_by, {
walletTypeId,
amountRaw: BigInt(amountRaw),
notes,
approvedBy,
});
}
case 'bonus_pool_fund': {
const { amountRaw } = request.payload;
const amount = BigInt(amountRaw);
// Always credit the locked USDT_TRC20 ledger pool (ignore payload walletTypeId).
const { walletTypeId } = await bonusPoolRepository.lockCommissionLedgerPool();
const referralRepository = await Promise.resolve().then(() => __importStar(require('../repositories/referralRepository')));
await referralRepository.updateSettings({ commissionWalletTypeId: walletTypeId });
await bonusPoolRepository.fundPool(walletTypeId, amount);
const pools = await bonusPoolRepository.listCommissionPools();
return { message: 'Pool funded', pools };
}
case 'sweep_manual': {
const { createSweepBatchApprovalRequests } = await Promise.resolve().then(() => __importStar(require('./sweepBatchService')));
const batchesSubmitted = await createSweepBatchApprovalRequests();
const processedUnbatched = await sweepService.processPendingSweeps({ unbatchedOnly: true });
return { batchesSubmitted, processedUnbatched };
}
case 'sweep_batch': {
const { batchId } = request.payload;
const processed = await sweepService.executeApprovedBatch(batchId);
return { batchId, processed };
}
case 'treasury_hot_to_cold_gas': {
const { walletTypeId, amountRaw, notes } = request.payload;
return treasuryService.executeHotToColdGas({
walletTypeId,
amountRaw: BigInt(amountRaw),
notes,
requestedBy: request.requested_by,
approvedBy,
});
}
case 'treasury_hot_to_cold': {
const { walletTypeId, amountRaw, notes } = request.payload;
return treasuryService.executeHotToColdUsdt({
walletTypeId,
amountRaw: BigInt(amountRaw),
notes,
requestedBy: request.requested_by,
approvedBy,
});
}
case 'treasury_cold_to_hot_gas': {
const { walletTypeId, amountRaw, notes } = request.payload;
return treasuryService.requestColdToHotGasFunding(request.requested_by, {
walletTypeId,
amountRaw: BigInt(amountRaw),
notes,
approvedBy,
});
}
case 'user_withdrawal': {
const { broadcastApprovedWithdrawal } = await Promise.resolve().then(() => __importStar(require('./withdrawalService')));
const { transactionId } = request.payload;
return broadcastApprovedWithdrawal(transactionId, approvedBy);
}
case 'approval_policy_change': {
return applyPolicyChangeFromRequest(request, approvedBy);
}
default:
throw new FundApprovalError(`Unknown operation type: ${request.operation_type}`);
}
}
async function applyPolicyChangeFromRequest(request, actorId) {
const { after, note } = request.payload;
if (!Array.isArray(after) || !after.length) {
throw new FundApprovalError('approval_policy_change payload.after must be a non-empty array');
}
const before = await approvalPolicyRepository.listAllPolicies();
const applied = await approvalPolicyRepository.replaceAllPolicies(after, actorId);
await approvalPolicyRepository.insertRevision({
changeRequestId: request.id,
actorId,
beforeSnapshot: before,
afterSnapshot: applied,
note: note ?? null,
});
await auditLogRepository.create({
userId: actorId,
action: 'approval_policies_applied',
resourceType: 'approval_policy',
resourceId: request.id,
metadata: {
beforeCount: before.length,
afterCount: applied.length,
note: note ?? null,
},
});
return { applied: applied.length };
}
async function createFundRequest(input) {
if (!input.skipRequestPermission) {
const canRequest = await roleRepository.userHasPermission(input.requestedBy, 'fund_operation.request');
if (!canRequest)
throw new FundApprovalError('Permission denied: fund_operation.request');
}
const ctx = extractContext(input.operationType, input.payload);
const evaluated = await approvalPolicyEngine.evaluate({
operationType: input.operationType,
amountRaw: ctx.amountRaw,
walletTypeId: ctx.walletTypeId,
network: ctx.network,
sourceKind: ctx.sourceKind,
destKind: ctx.destKind,
});
const decision = evaluated.decision;
const meta = {
policyId: evaluated.policy?.id ?? null,
policySnapshot: decision,
requiredQuorum: decision.quorum,
amountRaw: ctx.amountRaw,
assetCode: ctx.assetCode,
network: ctx.network,
fromAddress: ctx.fromAddress,
toAddress: ctx.toAddress,
};
// Auto-execute path (never for policy changes)
if (!input.forceQueue &&
decision.mode === 'auto_execute' &&
input.operationType !== 'approval_policy_change') {
let row;
try {
row = await fundOperationRequestRepository.createRequest({
operationType: input.operationType,
payload: input.payload,
requestedBy: input.requestedBy,
meta,
});
}
catch (e) {
const msg = e instanceof Error ? e.message : '';
if (/operation_type_check|violates check constraint/i.test(msg)) {
throw new FundApprovalError('Database schema is missing this operation type. Run db migrations and restart the backend.');
}
throw e;
}
await fundOperationRequestRepository.markApproved(row.id, input.requestedBy);
await fundOperationRequestRepository.markProcessing(row.id);
try {
const fresh = await fundOperationRequestRepository.findById(row.id);
const executionResult = await executeApprovedRequest(fresh, input.requestedBy);
await fundOperationRequestRepository.markConfirmed(row.id, executionResult);
await auditLogRepository.create({
userId: input.requestedBy,
action: 'fund_operation_auto_executed',
resourceType: 'fund_operation_request',
resourceId: row.id,
metadata: {
operation_type: input.operationType,
policy_id: evaluated.policy?.id ?? null,
amount_raw: ctx.amountRaw,
network: ctx.network,
from_address: ctx.fromAddress,
to_address: ctx.toAddress,
execution_result: executionResult,
},
});
const final = await fundOperationRequestRepository.findById(row.id);
return { ...(await toDto(final)), autoExecuted: true };
}
catch (e) {
const msg = e instanceof Error ? e.message : 'Execution failed';
await fundOperationRequestRepository.markFailed(row.id, msg);
await auditLogRepository.create({
userId: input.requestedBy,
action: 'fund_operation_failed',
resourceType: 'fund_operation_request',
resourceId: row.id,
metadata: { error: msg, auto: true },
});
throw new FundApprovalError(msg);
}
}
let row;
try {
row = await fundOperationRequestRepository.createRequest({
operationType: input.operationType,
payload: input.payload,
requestedBy: input.requestedBy,
meta,
});
}
catch (e) {
const msg = e instanceof Error ? e.message : '';
if (/operation_type_check|violates check constraint/i.test(msg)) {
throw new FundApprovalError('Database schema is missing this operation type. Run db migrations and restart the backend.');
}
throw e;
}
await auditLogRepository.create({
userId: input.requestedBy,
action: 'fund_operation_requested',
resourceType: 'fund_operation_request',
resourceId: row.id,
metadata: {
operation_type: input.operationType,
policy_id: evaluated.policy?.id ?? null,
amount_raw: ctx.amountRaw,
asset_code: ctx.assetCode,
network: ctx.network,
from_address: ctx.fromAddress,
to_address: ctx.toAddress,
quorum: decision.quorum,
},
});
return toDto(row, input.requestedBy);
}
async function castVote(requestId, voterId, decision, reason) {
const canApprove = await roleRepository.userHasPermission(voterId, 'fund_operation.approve');
if (!canApprove)
throw new FundApprovalError('Permission denied: fund_operation.approve');
const existing = await fundOperationRequestRepository.findById(requestId);
if (!existing)
throw new FundApprovalError('Request not found');
if (existing.status !== 'pending_approval') {
throw new FundApprovalError(`Request is not pending (status: ${existing.status})`);
}
const policyDecision = existing.policy_snapshot ?? {
mode: 'require_approvals',
quorum: existing.required_quorum ?? [{ role: 'super_admin', count: 1 }],
forbid_self_approve: true,
};
const quorum = policyDecision.quorum ?? [];
if (policyDecision.forbid_self_approve !== false && voterId === existing.requested_by) {
throw new FundApprovalError('Self-approval is not allowed for this operation');
}
const prior = await fundOperationVoteRepository.findByRequestAndVoter(requestId, voterId);
if (prior)
throw new FundApprovalError('You have already voted on this request');
const roles = await roleRepository.getUserRoleNames(voterId);
const perms = await roleRepository.getUserPermissions(voterId);
const annotated = approvalPolicyEngine.annotateVoterRolesForQuorum(roles, perms, quorum);
if (decision === 'approve') {
const approveVotes = (await fundOperationVoteRepository.listByRequest(requestId)).filter((v) => v.decision === 'approve');
if (!approvalPolicyEngine.voterFillsOpenSlot(quorum, approveVotes, roles, perms)) {
throw new FundApprovalError('Your role does not fill an open approval slot for this policy');
}
}
if (decision === 'reject') {
const trimmed = reason?.trim();
if (!trimmed)
throw new FundApprovalError('Rejection reason is required');
await fundOperationVoteRepository.insertVote({
requestId,
voterId,
decision: 'reject',
reason: trimmed,
voterRoles: annotated,
});
const rejected = await fundOperationRequestRepository.markRejected(requestId, voterId, trimmed);
if (!rejected)
throw new FundApprovalError('Failed to reject request');
if (existing.operation_type === 'user_withdrawal') {
const { transactionId } = existing.payload;
if (transactionId) {
const { abandonPendingWithdrawal } = await Promise.resolve().then(() => __importStar(require('./withdrawalService')));
await abandonPendingWithdrawal(transactionId, trimmed);
}
}
await auditLogRepository.create({
userId: voterId,
action: 'fund_operation_rejected',
resourceType: 'fund_operation_request',
resourceId: requestId,
metadata: {
reason: trimmed,
operation_type: existing.operation_type,
amount_raw: existing.amount_raw,
network: existing.network,
from_address: existing.from_address,
to_address: existing.to_address,
},
});
return toDto(rejected, voterId);
}
await fundOperationVoteRepository.insertVote({
requestId,
voterId,
decision: 'approve',
reason: reason?.trim() || null,
voterRoles: annotated,
});
await fundOperationRequestRepository.touchApprovedBy(requestId, voterId);
const allVotes = await fundOperationVoteRepository.listByRequest(requestId);
const approveVotes = allVotes.filter((v) => v.decision === 'approve');
const complete = approvalPolicyEngine.isQuorumComplete(quorum, approveVotes);
await auditLogRepository.create({
userId: voterId,
action: 'fund_operation_vote_approved',
resourceType: 'fund_operation_request',
resourceId: requestId,
metadata: {
operation_type: existing.operation_type,
quorum_complete: complete,
progress: approvalPolicyEngine.countQuorumProgress(quorum, approveVotes),
},
});
if (!complete) {
const pending = await fundOperationRequestRepository.findById(requestId);
return toDto(pending, voterId);
}
const approved = await fundOperationRequestRepository.markApproved(requestId, voterId);
if (!approved) {
// Race: already approved
const current = await fundOperationRequestRepository.findById(requestId);
return toDto(current, voterId);
}
await fundOperationRequestRepository.markProcessing(requestId);
try {
const fresh = await fundOperationRequestRepository.findById(requestId);
const executionResult = await executeApprovedRequest(fresh, voterId);
await fundOperationRequestRepository.markConfirmed(requestId, executionResult);
await auditLogRepository.create({
userId: voterId,
action: 'fund_operation_approved',
resourceType: 'fund_operation_request',
resourceId: requestId,
metadata: {
operation_type: approved.operation_type,
execution_result: executionResult,
amount_raw: approved.amount_raw,
network: approved.network,
from_address: approved.from_address,
to_address: approved.to_address,
tx_hash: executionResult.txHash ??
executionResult.blockchainTxId ??
null,
},
});
const final = await fundOperationRequestRepository.findById(requestId);
return toDto(final, voterId);
}
catch (e) {
const msg = e instanceof Error ? e.message : 'Execution failed';
await fundOperationRequestRepository.markFailed(requestId, msg);
await auditLogRepository.create({
userId: voterId,
action: 'fund_operation_failed',
resourceType: 'fund_operation_request',
resourceId: requestId,
metadata: { error: msg },
});
throw new FundApprovalError(msg);
}
}
async function approveFundRequest(requestId, approverId) {
return castVote(requestId, approverId, 'approve');
}
async function rejectFundRequest(requestId, approverId, reason) {
return castVote(requestId, approverId, 'reject', reason);
}
async function cancelFundRequest(requestId, actorId) {
const existing = await fundOperationRequestRepository.findById(requestId);
if (!existing)
throw new FundApprovalError('Request not found');
if (existing.status !== 'pending_approval') {
throw new FundApprovalError('Only pending requests can be cancelled');
}
const isRequester = existing.requested_by === actorId;
const isSuperAdmin = await roleRepository.userHasRole(actorId, 'super_admin');
if (!isRequester && !isSuperAdmin) {
throw new FundApprovalError('Only the requester or a super admin can cancel');
}
const cancelled = await fundOperationRequestRepository.markCancelled(requestId);
if (!cancelled)
throw new FundApprovalError('Failed to cancel request');
if (existing.operation_type === 'user_withdrawal') {
const { transactionId } = existing.payload;
if (transactionId) {
const { abandonPendingWithdrawal } = await Promise.resolve().then(() => __importStar(require('./withdrawalService')));
await abandonPendingWithdrawal(transactionId, 'cancelled');
}
}
await auditLogRepository.create({
userId: actorId,
action: 'fund_operation_cancelled',
resourceType: 'fund_operation_request',
resourceId: requestId,
metadata: { operation_type: existing.operation_type },
});
return toDto(cancelled, actorId);
}
async function getFundRequest(requestId, viewerId) {
const row = await fundOperationRequestRepository.findById(requestId);
return row ? toDto(row, viewerId) : null;
}
async function listFundRequests(filters, viewerId) {
const result = await fundOperationRequestRepository.listRequests(filters);
const items = await Promise.all(result.items.map((r) => toDto(r, viewerId)));
return { items, total: result.total };
}
/** Submit a full policy set replacement via Approvals (does not apply immediately). */
async function draftPolicyChange(input) {
const canManage = (await roleRepository.userHasPermission(input.requestedBy, 'approval_policy.manage')) ||
(await roleRepository.userHasPermission(input.requestedBy, 'admin.approval_policies.manage')) ||
(await roleRepository.userHasPermission(input.requestedBy, 'fund_operation.approve')) ||
(await roleRepository.userHasRole(input.requestedBy, 'super_admin'));
if (!canManage) {
throw new FundApprovalError('Permission denied: approval_policy.manage');
}
if (!Array.isArray(input.after) || !input.after.length) {
throw new FundApprovalError('after must be a non-empty policies array');
}
const before = await approvalPolicyRepository.listAllPolicies();
return createFundRequest({
operationType: 'approval_policy_change',
payload: {
before,
after: input.after,
note: input.note,
},
requestedBy: input.requestedBy,
});
}
async function listApprovalPolicies(actorId) {
const canView = (await roleRepository.userHasPermission(actorId, 'approval_policy.view')) ||
(await roleRepository.userHasPermission(actorId, 'admin.approval_policies.view')) ||
(await roleRepository.userHasPermission(actorId, 'approval_policy.manage')) ||
(await roleRepository.userHasPermission(actorId, 'admin.approval_policies.manage')) ||
(await roleRepository.userHasPermission(actorId, 'fund_operation.approve')) ||
(await roleRepository.userHasRole(actorId, 'super_admin'));
if (!canView)
throw new FundApprovalError('Permission denied: approval_policy.view');
await approvalPolicyRepository.ensureDefaultPoliciesSeeded();
return approvalPolicyRepository.listAllPolicies();
}
async function listPolicyRevisions(actorId, limit) {
const canView = (await roleRepository.userHasPermission(actorId, 'approval_policy.view')) ||
(await roleRepository.userHasPermission(actorId, 'admin.approval_policies.view')) ||
(await roleRepository.userHasPermission(actorId, 'fund_operation.approve')) ||
(await roleRepository.userHasRole(actorId, 'super_admin'));
if (!canView)
throw new FundApprovalError('Permission denied: approval_policy.view');
return approvalPolicyRepository.listRevisions(limit);
}
async function updateUserRoles(targetUserId, roleNames, adminUserId, notifyCtx = {}) {
const canManage = await roleRepository.userHasPermission(adminUserId, 'user.manage_roles');
if (!canManage)
throw new FundApprovalError('Permission denied: user.manage_roles');
const unique = [...new Set(roleNames.map((r) => r.trim().toLowerCase()))].filter((r) => roleRepository.isKnownRoleName(r));
if (!unique.length)
throw new FundApprovalError('At least one role is required');
const currentRoles = await roleRepository.getUserRoleNames(targetUserId);
const permissionsBefore = await roleRepository.getUserPermissions(targetUserId);
const removingSuperAdmin = currentRoles.includes('super_admin') && !unique.includes('super_admin');
if (removingSuperAdmin) {
const count = await roleRepository.countUsersWithRoleName('super_admin');
if (count <= 1) {
throw new FundApprovalError('At least one super administrator must remain on the platform');
}
}
const removingAdmin = currentRoles.includes('admin') && !unique.includes('admin');
if (removingAdmin) {
const adminCount = await roleRepository.countUsersWithRoleName('admin');
if (adminCount <= 1) {
throw new FundApprovalError('At least one administrator must remain on the platform');
}
}
if (targetUserId === adminUserId &&
currentRoles.includes('admin') &&
!unique.includes('admin')) {
throw new FundApprovalError('You cannot remove your own administrator role');
}
await roleRepository.setUserRoles(targetUserId, unique);
await (0, rbacService_1.bumpUserTokenOnRoleChange)(targetUserId);
const permissionsAfter = await roleRepository.getUserPermissions(targetUserId);
await auditLogRepository.create({
userId: adminUserId,
action: 'admin_user_roles_changed',
resourceType: 'user',
resourceId: targetUserId,
metadata: {
changed: ['roles'],
before: { roles: currentRoles },
after: { roles: unique },
},
});
const permsBeforeSorted = [...permissionsBefore].sort();
const permsAfterSorted = [...permissionsAfter].sort();
const permissionsChanged = JSON.stringify(permsBeforeSorted) !== JSON.stringify(permsAfterSorted);
if (permissionsChanged) {
await auditLogRepository.create({
userId: adminUserId,
action: 'admin_user_permissions_changed',
resourceType: 'user',
resourceId: targetUserId,
metadata: {
changed: ['permissions'],
before: { permissions: permsBeforeSorted },
after: { permissions: permsAfterSorted },
},
});
}
void securityNotificationService.notifyRolesChanged(targetUserId, unique, notifyCtx);
if (permissionsChanged) {
void securityNotificationService.notifyPermissionsChanged(targetUserId, permsAfterSorted, notifyCtx);
}
return { userId: targetUserId, roles: unique };
}
//# sourceMappingURL=fundApprovalService.js.map