/** * Evaluates configurable approval policies (N-of-M / auto-execute). */ import * as approvalPolicyRepository from '../repositories/approvalPolicyRepository'; import type { ApprovalPolicyRow, PolicyDecision, QuorumSlot, WalletKind, } from '../repositories/approvalPolicyRepository'; import type { FundOperationType } from '../repositories/fundOperationRequestRepository'; import type { FundOperationVoteRow } from '../repositories/fundOperationVoteRepository'; export type EvaluateInput = { operationType: FundOperationType | string; amountRaw?: string | null; walletTypeId?: number | null; network?: string | null; sourceKind?: WalletKind; destKind?: WalletKind; }; export type EvaluateResult = { policy: ApprovalPolicyRow | null; decision: PolicyDecision; matchedBy: 'policy' | 'fail_closed_default'; }; const FAIL_CLOSED: PolicyDecision = { mode: 'require_approvals', quorum: [{ role: 'super_admin', count: 1 }], forbid_self_approve: true, require_distinct_users: true, }; function kindMatches(rule: WalletKind, actual: WalletKind | undefined): boolean { if (rule === 'any') return true; if (!actual || actual === 'any') return true; return rule === actual; } function amountInRange( amountRaw: string | null | undefined, minRaw: string | null, maxRaw: string | null ): boolean { if (amountRaw == null || amountRaw === '') { return minRaw == null && maxRaw == null; } let amount: bigint; try { amount = BigInt(amountRaw); } catch { return false; } if (minRaw != null && minRaw !== '') { try { if (amount < BigInt(minRaw)) return false; } catch { return false; } } if (maxRaw != null && maxRaw !== '') { try { if (amount > BigInt(maxRaw)) return false; } catch { return false; } } return true; } export function policyMatches(policy: ApprovalPolicyRow, input: EvaluateInput): boolean { if (!policy.enabled) return false; if (policy.operation_type && policy.operation_type !== input.operationType) return false; if (policy.wallet_type_id != null && policy.wallet_type_id !== input.walletTypeId) return false; if (policy.network && policy.network !== input.network) return false; if (!kindMatches(policy.source_wallet_kind, input.sourceKind)) return false; if (!kindMatches(policy.dest_wallet_kind, input.destKind)) return false; if (!amountInRange(input.amountRaw, policy.amount_min_raw, policy.amount_max_raw)) return false; return true; } export async function evaluate(input: EvaluateInput): Promise { await approvalPolicyRepository.ensureDefaultPoliciesSeeded(); const policies = await approvalPolicyRepository.listEnabledPolicies(); for (const policy of policies) { if (policyMatches(policy, input)) { return { policy, decision: policy.decision, matchedBy: 'policy', }; } } return { policy: null, decision: FAIL_CLOSED, matchedBy: 'fail_closed_default', }; } /** True if approve votes satisfy every quorum slot. */ export function quorumSatisfied( quorum: QuorumSlot[], approveVotes: FundOperationVoteRow[], voterHasRole: (voterId: string, role: string) => boolean, voterHasPermission: (voterId: string, permission: string) => boolean ): boolean { if (!quorum.length) return false; const used = new Set(); for (const slot of quorum) { let filled = 0; for (const vote of approveVotes) { if (used.has(vote.voter_id)) continue; const roleOk = slot.role ? voterHasRole(vote.voter_id, slot.role) || vote.voter_roles.includes(slot.role) : false; const permOk = slot.permission ? voterHasPermission(vote.voter_id, slot.permission) : false; // Prefer roles recorded on the vote; async permission checked by caller via cache map const ok = slot.role ? vote.voter_roles.includes(slot.role) || roleOk : permOk; if (!ok && slot.permission) { // permission checked externally — caller passes precomputed eligibility continue; } if (slot.role && !vote.voter_roles.includes(slot.role)) continue; if (!slot.role && slot.permission) { // handled below with permission set on vote metadata — skip if only permission and not in roles continue; } filled += 1; used.add(vote.voter_id); if (filled >= slot.count) break; } if (filled < slot.count) return false; } return true; } /** * Count how many approve votes fill each slot (role-based; permission slots need prefilter). */ export function countQuorumProgress( quorum: QuorumSlot[], approveVotes: FundOperationVoteRow[] ): { required: number; approved: number; slots: Array<{ slot: QuorumSlot; filled: number; needed: number }> } { const used = new Set(); const onlyApproves = approveVotes.filter((v) => v.decision === 'approve'); const slots = quorum.map((slot) => { let filled = 0; for (const vote of onlyApproves) { if (used.has(vote.voter_id)) continue; const matchesRole = slot.role ? vote.voter_roles.includes(slot.role) : false; const matchesPerm = slot.permission && !slot.role ? vote.voter_roles.includes(`perm:${slot.permission}`) || vote.voter_roles.includes(slot.permission) : false; if (!matchesRole && !matchesPerm) continue; filled += 1; used.add(vote.voter_id); if (filled >= slot.count) break; } return { slot, filled, needed: slot.count }; }); const required = slots.reduce((s, x) => s + x.needed, 0); const approved = slots.reduce((s, x) => s + Math.min(x.filled, x.needed), 0); return { required, approved, slots }; } export function isQuorumComplete( quorum: QuorumSlot[], approveVotes: FundOperationVoteRow[] ): boolean { const progress = countQuorumProgress(quorum, approveVotes); return progress.slots.every((s) => s.filled >= s.needed); } /** Whether voter can contribute to any unfilled quorum slot. */ export function voterFillsOpenSlot( quorum: QuorumSlot[], approveVotes: FundOperationVoteRow[], voterRoles: string[], voterPermissions: string[] ): boolean { const progress = countQuorumProgress(quorum, approveVotes); for (const { slot, filled, needed } of progress.slots) { if (filled >= needed) continue; if (slot.role && voterRoles.includes(slot.role)) return true; if (slot.permission && voterPermissions.includes(slot.permission)) return true; if (slot.permission && voterPermissions.includes(`admin.${slot.permission}`)) return true; } return false; } export function annotateVoterRolesForQuorum( roles: string[], permissions: string[], quorum: QuorumSlot[] ): string[] { const out = [...roles]; for (const slot of quorum) { if (slot.permission && permissions.includes(slot.permission)) { out.push(`perm:${slot.permission}`); } } return Array.from(new Set(out)); }