/** * Super-admin approval workflow for sensitive platform fund operations. */ import * as fundOperationRequestRepository from '../repositories/fundOperationRequestRepository'; import type { FundOperationRequestRow, FundOperationStatus, FundOperationType, } from '../repositories/fundOperationRequestRepository'; import * as roleRepository from '../repositories/roleRepository'; import * as userRepository from '../repositories/userRepository'; import { bumpUserTokenOnRoleChange } from './rbacService'; import * as auditLogRepository from '../repositories/auditLogRepository'; import * as securityNotificationService from './securityNotificationService'; import * as adminCreditService from './adminCreditService'; import * as treasuryService from './treasuryService'; import * as bonusPoolRepository from '../repositories/bonusPoolRepository'; import * as sweepService from './sweepService'; import * as depositSweepBatchRepository from '../repositories/depositSweepBatchRepository'; import type { RoleName } from '../models'; export class FundApprovalError extends Error { constructor(message: string) { super(message); this.name = 'FundApprovalError'; } } export type FundRequestDto = { id: string; operationType: FundOperationType; status: FundOperationStatus; payload: Record; requestedBy: string; approvedBy: string | null; rejectionReason: string | null; executionResult: Record | null; createdAt: string; approvedAt: string | null; executedAt: string | null; }; function toDto(row: FundOperationRequestRow): FundRequestDto { 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, }; } export async function createFundRequest(input: { operationType: FundOperationType; payload: Record; requestedBy: string; }): Promise { const canRequest = await roleRepository.userHasPermission( input.requestedBy, 'fund_operation.request' ); if (!canRequest) throw new FundApprovalError('Permission denied: fund_operation.request'); let row; try { row = await fundOperationRequestRepository.createRequest({ operationType: input.operationType, payload: input.payload, requestedBy: input.requestedBy, }); } 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 }, }); return toDto(row); } async function executeApprovedRequest( request: FundOperationRequestRow, approverId: string ): Promise> { const approvedBy = approverId; switch (request.operation_type) { case 'ledger_credit': { const { userId, walletTypeId, adjustmentType, amountRaw, reason } = request.payload as { userId: string; walletTypeId: number; adjustmentType: 'bonus' | 'admin_adjustment'; amountRaw: string; reason: string; }; const result = await adminCreditService.grantLedgerCredit({ userId, walletTypeId, adjustmentType, amountRaw, reason, approvedBy, requestedBy: request.requested_by, }); return result; } case 'treasury_cold_to_hot': { const { walletTypeId, amountRaw, notes } = request.payload as { walletTypeId: number; amountRaw: string; notes?: string; }; const result = await treasuryService.requestColdToHotFunding(request.requested_by, { walletTypeId, amountRaw: BigInt(amountRaw), notes, approvedBy, }); return result; } case 'bonus_pool_fund': { const { walletTypeId, amountRaw } = request.payload as { walletTypeId: number; amountRaw: string; }; const amount = BigInt(amountRaw); await bonusPoolRepository.fundPool(walletTypeId, amount); const pools = await bonusPoolRepository.listPools(); return { message: 'Pool funded', pools }; } case 'sweep_manual': { // Legacy: promote open batches to Approvals; also run any rare unbatched pending rows. const { createSweepBatchApprovalRequests } = await import('./sweepBatchService'); const batchesSubmitted = await createSweepBatchApprovalRequests(); const processedUnbatched = await sweepService.processPendingSweeps({ unbatchedOnly: true }); return { batchesSubmitted, processedUnbatched }; } case 'sweep_batch': { const { batchId } = request.payload as { batchId: string }; const processed = await sweepService.executeApprovedBatch(batchId); return { batchId, processed }; } case 'treasury_hot_to_cold_gas': { const { walletTypeId, amountRaw, notes } = request.payload as { walletTypeId: number; amountRaw: string; notes?: string; }; return treasuryService.executeHotToColdGas({ walletTypeId, amountRaw: BigInt(amountRaw), notes, requestedBy: request.requested_by, approvedBy, }); } case 'treasury_cold_to_hot_gas': { const { walletTypeId, amountRaw, notes } = request.payload as { walletTypeId: number; amountRaw: string; notes?: string; }; return treasuryService.requestColdToHotGasFunding(request.requested_by, { walletTypeId, amountRaw: BigInt(amountRaw), notes, approvedBy, }); } default: throw new FundApprovalError(`Unknown operation type: ${request.operation_type}`); } } export async function approveFundRequest( requestId: string, approverId: string ): Promise { const canApprove = await roleRepository.userHasPermission(approverId, '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 approved = await fundOperationRequestRepository.markApproved(requestId, approverId); if (!approved) throw new FundApprovalError('Failed to approve request'); try { const executionResult = await executeApprovedRequest(approved, approverId); await fundOperationRequestRepository.markExecuted(requestId, executionResult); await auditLogRepository.create({ userId: approverId, action: 'fund_operation_approved', resourceType: 'fund_operation_request', resourceId: requestId, metadata: { operation_type: approved.operation_type, execution_result: executionResult }, }); const final = await fundOperationRequestRepository.findById(requestId); return toDto(final!); } catch (e) { const msg = e instanceof Error ? e.message : 'Execution failed'; await fundOperationRequestRepository.markFailed(requestId, msg); await auditLogRepository.create({ userId: approverId, action: 'fund_operation_failed', resourceType: 'fund_operation_request', resourceId: requestId, metadata: { error: msg }, }); throw new FundApprovalError(msg); } } export async function rejectFundRequest( requestId: string, approverId: string, reason: string ): Promise { const canApprove = await roleRepository.userHasPermission(approverId, 'fund_operation.approve'); if (!canApprove) throw new FundApprovalError('Permission denied: fund_operation.approve'); const trimmed = reason?.trim(); if (!trimmed) throw new FundApprovalError('Rejection reason is required'); const rejected = await fundOperationRequestRepository.markRejected(requestId, approverId, trimmed); if (!rejected) throw new FundApprovalError('Request not found or not pending'); await auditLogRepository.create({ userId: approverId, action: 'fund_operation_rejected', resourceType: 'fund_operation_request', resourceId: requestId, metadata: { reason: trimmed }, }); return toDto(rejected); } export async function cancelFundRequest( requestId: string, actorId: string ): Promise { 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'); return toDto(cancelled); } export async function getFundRequest(requestId: string): Promise { const row = await fundOperationRequestRepository.findById(requestId); return row ? toDto(row) : null; } export async function listFundRequests(filters: { status?: FundOperationStatus; operationType?: FundOperationType; limit?: number; offset?: number; }): Promise<{ items: FundRequestDto[]; total: number }> { const result = await fundOperationRequestRepository.listRequests(filters); return { items: result.items.map(toDto), total: result.total }; } export type UserRoleName = RoleName; export async function updateUserRoles( targetUserId: string, roleNames: string[], adminUserId: string, notifyCtx: { ipAddress?: string; userAgent?: string } = {} ): Promise<{ userId: string; roles: string[] }> { 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 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 }; }