games_app/backend/dist-test-faq/scripts/smokeApprovalPolicies.js

262 lines
9.5 KiB
JavaScript

"use strict";
/**
* Smoke check for the approval-policy engine — no on-chain transfers.
*
* Verifies:
* - approval_* / fund_operation_votes tables exist
* - default policies can be seeded / listed
* - evaluate() returns a decision for key operation types
* - N-of-M helpers behave on a synthetic quorum
*
* Does NOT create fund requests, approve, or broadcast transactions.
*
* Local:
* npx ts-node --transpile-only src/scripts/smokeApprovalPolicies.ts
*
* VPS:
* sudo docker compose run --rm --no-deps --build backend \
* node dist/scripts/smokeApprovalPolicies.js
*/
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 });
require("./loadEnv");
const connection_1 = require("../db/connection");
const approvalPolicyRepository = __importStar(require("../repositories/approvalPolicyRepository"));
const approvalPolicyEngine_1 = require("../services/approvalPolicyEngine");
async function tableExists(name) {
const rows = await (0, connection_1.query)(`SELECT EXISTS (
SELECT 1 FROM information_schema.tables
WHERE table_schema = 'public' AND table_name = $1
) AS exists`, [name]);
return Boolean(rows[0]?.exists);
}
async function columnExists(table, column) {
const rows = await (0, connection_1.query)(`SELECT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema = 'public' AND table_name = $1 AND column_name = $2
) AS exists`, [table, column]);
return Boolean(rows[0]?.exists);
}
async function main() {
const checks = [];
console.log('=== smokeApprovalPolicies (read-mostly, no on-chain) ===\n');
for (const table of [
'approval_policies',
'approval_policy_revisions',
'fund_operation_votes',
'fund_operation_requests',
]) {
const ok = await tableExists(table);
checks.push({ name: `table ${table}`, ok, detail: ok ? 'present' : 'MISSING — run migrations' });
}
const schemaOk = checks.every((c) => c.ok);
if (!schemaOk) {
console.log('Results (schema incomplete — skipping seed/evaluate):');
for (const c of checks) {
console.log(` [${c.ok ? 'OK ' : 'FAIL'}] ${c.name}${c.detail ? ` — ${c.detail}` : ''}`);
}
console.error('\nSmoke FAILED: run DB migrations first, then re-run this script.');
process.exit(1);
}
for (const col of [
'policy_id',
'policy_snapshot',
'required_quorum',
'amount_raw',
'network',
'from_address',
'to_address',
]) {
const ok = await columnExists('fund_operation_requests', col);
checks.push({
name: `fund_operation_requests.${col}`,
ok,
detail: ok ? 'present' : 'MISSING — run migrations',
});
}
if (checks.some((c) => !c.ok)) {
console.log('Results (columns incomplete — skipping seed/evaluate):');
for (const c of checks) {
console.log(` [${c.ok ? 'OK ' : 'FAIL'}] ${c.name}${c.detail ? ` — ${c.detail}` : ''}`);
}
console.error('\nSmoke FAILED: run DB migrations first, then re-run this script.');
process.exit(1);
}
// May insert default seed if empty (safe, no chain)
await approvalPolicyRepository.ensureDefaultPoliciesSeeded();
const policies = await approvalPolicyRepository.listAllPolicies();
checks.push({
name: 'default policies seeded',
ok: policies.length > 0,
detail: `${policies.length} policy(ies)`,
});
const hasPolicyChange = policies.some((p) => p.operation_type === 'approval_policy_change');
const hasCatchAll = policies.some((p) => p.operation_type == null && p.enabled);
checks.push({
name: 'seed includes approval_policy_change rule',
ok: hasPolicyChange,
});
checks.push({
name: 'seed includes catch-all / wildcard rule',
ok: hasCatchAll,
});
const sampleOps = [
'treasury_hot_to_cold',
'treasury_cold_to_hot',
'treasury_hot_to_cold_gas',
'sweep_batch',
'user_withdrawal',
'approval_policy_change',
'ledger_credit',
];
for (const op of sampleOps) {
const result = await (0, approvalPolicyEngine_1.evaluate)({
operationType: op,
amountRaw: op === 'user_withdrawal' ? '50000000' : '1000000',
network: 'BSC',
sourceKind: op.includes('hot_to_cold') ? 'hot' : op.includes('cold_to_hot') ? 'cold' : 'any',
destKind: op.includes('hot_to_cold') ? 'cold' : op.includes('cold_to_hot') ? 'hot' : 'any',
});
const ok = result.decision.mode === 'require_approvals' || result.decision.mode === 'auto_execute';
checks.push({
name: `evaluate(${op})`,
ok,
detail: `${result.matchedBy} → ${result.decision.mode} quorum=${JSON.stringify(result.decision.quorum)} forbid_self=${result.decision.forbid_self_approve !== false}`,
});
}
// Pure N-of-M sanity (no DB)
const quorum = [
{ role: 'admin', count: 1 },
{ role: 'super_admin', count: 1 },
];
const incomplete = (0, approvalPolicyEngine_1.isQuorumComplete)(quorum, [
{
id: '1',
request_id: 'r',
voter_id: 'a',
decision: 'approve',
reason: null,
voter_roles: ['admin'],
created_at: new Date(),
},
]);
const complete = (0, approvalPolicyEngine_1.isQuorumComplete)(quorum, [
{
id: '1',
request_id: 'r',
voter_id: 'a',
decision: 'approve',
reason: null,
voter_roles: ['admin'],
created_at: new Date(),
},
{
id: '2',
request_id: 'r',
voter_id: 's',
decision: 'approve',
reason: null,
voter_roles: ['super_admin'],
created_at: new Date(),
},
]);
const progress = (0, approvalPolicyEngine_1.countQuorumProgress)(quorum, [
{
id: '1',
request_id: 'r',
voter_id: 'a',
decision: 'approve',
reason: null,
voter_roles: ['admin'],
created_at: new Date(),
},
]);
checks.push({
name: 'N-of-M incomplete until both slots filled',
ok: incomplete === false && complete === true && progress.approved === 1,
detail: `progress ${progress.approved}/${progress.required}`,
});
// Priority: more specific policy wins when evaluating first match — verify match ordering logic
const specific = {
id: 's',
name: 'specific',
enabled: true,
priority: 10,
operation_type: 'treasury_hot_to_cold',
wallet_type_id: null,
network: null,
amount_min_raw: null,
amount_max_raw: null,
source_wallet_kind: 'any',
dest_wallet_kind: 'any',
decision: {
mode: 'auto_execute',
quorum: [],
forbid_self_approve: true,
},
version: 1,
updated_by: null,
created_at: new Date(),
updated_at: new Date(),
};
checks.push({
name: 'policyMatches specific hot→cold',
ok: (0, approvalPolicyEngine_1.policyMatches)(specific, { operationType: 'treasury_hot_to_cold' }),
});
checks.push({
name: 'policyMatches specific rejects other ops',
ok: !(0, approvalPolicyEngine_1.policyMatches)(specific, { operationType: 'ledger_credit' }),
});
console.log('Results:');
let failed = 0;
for (const c of checks) {
const mark = c.ok ? 'OK ' : 'FAIL';
if (!c.ok)
failed += 1;
console.log(` [${mark}] ${c.name}${c.detail ? ` — ${c.detail}` : ''}`);
}
console.log(`\n${checks.length - failed}/${checks.length} checks passed.`);
if (failed > 0) {
console.error('\nSmoke FAILED. Fix migrations / seed before relying on Approvals in prod.');
process.exit(1);
}
console.log('\nSmoke OK. No on-chain transactions were sent.');
process.exit(0);
}
main().catch((e) => {
console.error('Smoke crashed:', e instanceof Error ? e.message : e);
process.exit(1);
});
//# sourceMappingURL=smokeApprovalPolicies.js.map