836 lines
30 KiB
TypeScript
836 lines
30 KiB
TypeScript
/**
|
|
* Approval workflow for sensitive platform fund operations (N-of-M + auto-execute).
|
|
*/
|
|
|
|
import * as fundOperationRequestRepository from '../repositories/fundOperationRequestRepository';
|
|
import type {
|
|
FundOperationRequestRow,
|
|
FundOperationStatus,
|
|
FundOperationType,
|
|
} from '../repositories/fundOperationRequestRepository';
|
|
import * as fundOperationVoteRepository from '../repositories/fundOperationVoteRepository';
|
|
import * as approvalPolicyRepository from '../repositories/approvalPolicyRepository';
|
|
import type { PolicyDecision, PolicyInput, QuorumSlot } from '../repositories/approvalPolicyRepository';
|
|
import * as roleRepository from '../repositories/roleRepository';
|
|
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 approvalPolicyEngine from './approvalPolicyEngine';
|
|
import type { WalletKind } from '../repositories/approvalPolicyRepository';
|
|
import type { RoleName } from '../models';
|
|
|
|
export class FundApprovalError extends Error {
|
|
constructor(message: string) {
|
|
super(message);
|
|
this.name = 'FundApprovalError';
|
|
}
|
|
}
|
|
|
|
export type FundRequestVoteDto = {
|
|
voterId: string;
|
|
decision: 'approve' | 'reject';
|
|
reason: string | null;
|
|
voterRoles: string[];
|
|
createdAt: string;
|
|
};
|
|
|
|
export type FundRequestDto = {
|
|
id: string;
|
|
operationType: FundOperationType;
|
|
status: FundOperationStatus;
|
|
payload: Record<string, unknown>;
|
|
requestedBy: string;
|
|
approvedBy: string | null;
|
|
rejectionReason: string | null;
|
|
executionResult: Record<string, unknown> | null;
|
|
createdAt: string;
|
|
approvedAt: string | null;
|
|
executedAt: string | null;
|
|
policyId: string | null;
|
|
policyName: string | null;
|
|
requiredQuorum: QuorumSlot[];
|
|
forbidSelfApprove: boolean;
|
|
amountRaw: string | null;
|
|
assetCode: string | null;
|
|
network: string | null;
|
|
fromAddress: string | null;
|
|
toAddress: string | null;
|
|
votes: FundRequestVoteDto[];
|
|
quorumProgress: { required: number; approved: number };
|
|
canVote: boolean;
|
|
};
|
|
|
|
async function toDto(
|
|
row: FundOperationRequestRow,
|
|
viewerId?: string | null
|
|
): Promise<FundRequestDto> {
|
|
const votes = await fundOperationVoteRepository.listByRequest(row.id);
|
|
const decision = (row.policy_snapshot as PolicyDecision | null) ?? {
|
|
mode: 'require_approvals' as const,
|
|
quorum: (row.required_quorum as QuorumSlot[]) ?? [{ 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: string | null = 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: FundOperationType, payload: Record<string, unknown>) {
|
|
const amountRaw =
|
|
(payload.amountRaw as string | undefined) ??
|
|
(payload.amount as string | undefined) ??
|
|
null;
|
|
const walletTypeId =
|
|
typeof payload.walletTypeId === 'number'
|
|
? payload.walletTypeId
|
|
: payload.walletTypeId != null
|
|
? Number(payload.walletTypeId)
|
|
: null;
|
|
const network = (payload.network as string | undefined) ?? null;
|
|
const assetCode = (payload.assetCode as string | undefined) ?? (payload.walletCode as string | undefined) ?? null;
|
|
const fromAddress = (payload.fromAddress as string | undefined) ?? null;
|
|
const toAddress = (payload.toAddress as string | undefined) ?? null;
|
|
|
|
let sourceKind: WalletKind = 'any';
|
|
let destKind: WalletKind = '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 };
|
|
}
|
|
|
|
export async function executeApprovedRequest(
|
|
request: FundOperationRequestRow,
|
|
approverId: string
|
|
): Promise<Record<string, unknown>> {
|
|
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;
|
|
};
|
|
return adminCreditService.grantLedgerCredit({
|
|
userId,
|
|
walletTypeId,
|
|
adjustmentType,
|
|
amountRaw,
|
|
reason,
|
|
approvedBy,
|
|
requestedBy: request.requested_by,
|
|
});
|
|
}
|
|
case 'treasury_cold_to_hot': {
|
|
const { walletTypeId, amountRaw, notes } = request.payload as {
|
|
walletTypeId: number;
|
|
amountRaw: string;
|
|
notes?: string;
|
|
};
|
|
return treasuryService.requestColdToHotFunding(request.requested_by, {
|
|
walletTypeId,
|
|
amountRaw: BigInt(amountRaw),
|
|
notes,
|
|
approvedBy,
|
|
});
|
|
}
|
|
case 'bonus_pool_fund': {
|
|
const { amountRaw } = request.payload as {
|
|
walletTypeId?: number;
|
|
amountRaw: string;
|
|
};
|
|
const amount = BigInt(amountRaw);
|
|
// Always credit the locked USDT_TRC20 ledger pool (ignore payload walletTypeId).
|
|
const { walletTypeId } = await bonusPoolRepository.lockCommissionLedgerPool();
|
|
const referralRepository = await import('../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 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_hot_to_cold': {
|
|
const { walletTypeId, amountRaw, notes } = request.payload as {
|
|
walletTypeId: number;
|
|
amountRaw: string;
|
|
notes?: string;
|
|
};
|
|
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 as {
|
|
walletTypeId: number;
|
|
amountRaw: string;
|
|
notes?: string;
|
|
};
|
|
return treasuryService.requestColdToHotGasFunding(request.requested_by, {
|
|
walletTypeId,
|
|
amountRaw: BigInt(amountRaw),
|
|
notes,
|
|
approvedBy,
|
|
});
|
|
}
|
|
case 'user_withdrawal': {
|
|
const { processApprovedWithdrawal } = await import('./withdrawalService');
|
|
const { transactionId } = request.payload as { transactionId: string };
|
|
return processApprovedWithdrawal(transactionId, approvedBy);
|
|
}
|
|
case 'approval_policy_change': {
|
|
return applyPolicyChangeFromRequest(request, approvedBy);
|
|
}
|
|
default:
|
|
throw new FundApprovalError(`Unknown operation type: ${(request as FundOperationRequestRow).operation_type}`);
|
|
}
|
|
}
|
|
|
|
async function applyPolicyChangeFromRequest(
|
|
request: FundOperationRequestRow,
|
|
actorId: string
|
|
): Promise<Record<string, unknown>> {
|
|
const { after, note } = request.payload as {
|
|
after: PolicyInput[];
|
|
note?: string;
|
|
};
|
|
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 };
|
|
}
|
|
|
|
export async function createFundRequest(input: {
|
|
operationType: FundOperationType;
|
|
payload: Record<string, unknown>;
|
|
requestedBy: string;
|
|
/** Skip fund_operation.request check (e.g. user withdrawal). */
|
|
skipRequestPermission?: boolean;
|
|
/** Force queue even if policy says auto (unused reserved). */
|
|
forceQueue?: boolean;
|
|
}): Promise<FundRequestDto & { autoExecuted?: boolean }> {
|
|
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 as unknown as Record<string, unknown>,
|
|
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: FundOperationRequestRow;
|
|
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: FundOperationRequestRow;
|
|
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);
|
|
}
|
|
|
|
export async function castVote(
|
|
requestId: string,
|
|
voterId: string,
|
|
decision: 'approve' | 'reject',
|
|
reason?: string
|
|
): Promise<FundRequestDto> {
|
|
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 as PolicyDecision | null) ?? {
|
|
mode: 'require_approvals' as const,
|
|
quorum: (existing.required_quorum as QuorumSlot[]) ?? [{ 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 as { transactionId?: string };
|
|
if (transactionId) {
|
|
const { rejectWithdrawal } = await import('./withdrawalService');
|
|
await rejectWithdrawal(transactionId, {
|
|
actorId: voterId,
|
|
reason: trimmed,
|
|
source: 'approval',
|
|
}).catch((e) => console.error('[fund-approval] withdrawal rejection/refund failed:', e));
|
|
}
|
|
}
|
|
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 as { txHash?: string; blockchainTxId?: string }).txHash ??
|
|
(executionResult as { blockchainTxId?: string }).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);
|
|
}
|
|
}
|
|
|
|
export async function approveFundRequest(
|
|
requestId: string,
|
|
approverId: string
|
|
): Promise<FundRequestDto> {
|
|
return castVote(requestId, approverId, 'approve');
|
|
}
|
|
|
|
export async function rejectFundRequest(
|
|
requestId: string,
|
|
approverId: string,
|
|
reason: string
|
|
): Promise<FundRequestDto> {
|
|
return castVote(requestId, approverId, 'reject', reason);
|
|
}
|
|
|
|
export async function cancelFundRequest(
|
|
requestId: string,
|
|
actorId: string
|
|
): Promise<FundRequestDto> {
|
|
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 as { transactionId?: string };
|
|
if (transactionId) {
|
|
const { cancelWithdrawalFromApproval } = await import('./withdrawalService');
|
|
await cancelWithdrawalFromApproval(transactionId, actorId);
|
|
}
|
|
}
|
|
|
|
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);
|
|
}
|
|
|
|
export async function getFundRequest(
|
|
requestId: string,
|
|
viewerId?: string
|
|
): Promise<FundRequestDto | null> {
|
|
const row = await fundOperationRequestRepository.findById(requestId);
|
|
return row ? toDto(row, viewerId) : null;
|
|
}
|
|
|
|
export async function listFundRequests(
|
|
filters: {
|
|
status?: FundOperationStatus;
|
|
operationType?: FundOperationType;
|
|
limit?: number;
|
|
offset?: number;
|
|
},
|
|
viewerId?: string
|
|
): Promise<{ items: FundRequestDto[]; total: number }> {
|
|
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). */
|
|
export async function draftPolicyChange(input: {
|
|
after: PolicyInput[];
|
|
note?: string;
|
|
requestedBy: string;
|
|
}): Promise<FundRequestDto> {
|
|
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,
|
|
});
|
|
}
|
|
|
|
export async function listApprovalPolicies(actorId: string) {
|
|
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();
|
|
}
|
|
|
|
export async function listPolicyRevisions(actorId: string, limit?: number) {
|
|
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);
|
|
}
|
|
|
|
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 };
|
|
}
|