import {fileURLToPath} from 'node:url'; import {resolve} from 'node:path'; import {execFileSync} from 'node:child_process'; import {openDatabase} from '../node/mysql.mjs'; import {openPostbankDatabase} from '../node/postbank-db.mjs'; export async function tradeGrantPlan(db,bank){ const sql='SELECT DATABASE() db,@@hostname host,@@port port,@@server_id server_id',a=(await db.query(sql))[0],b=await bank.first(sql); if(!a||!b||['host','port','server_id'].some(k=>String(a[k])!==String(b[k]))||!/^[a-z][a-z0-9_]{2,63}$/.test(a.db||''))throw Error('One transactional MySQL server required'); const identity=(await bank.first('SELECT CURRENT_USER() identity')).identity.split('@');if(identity.length!==2||!identity.every(v=>/^[a-zA-Z0-9_.%:-]+$/.test(v)))throw Error('Unexpected bank identity'); const account="'"+identity[0]+"'@'"+identity[1]+"'"; return['jarvis_trade_rules','jarvis_trade_governance','organisation_keys'].map(table=>'GRANT SELECT ON `'+a.db+'`.`'+table+'` TO '+account+';').join('\n')+'\n'; } if(process.argv[1]&&resolve(process.argv[1])===fileURLToPath(import.meta.url)){ const apply=process.argv.slice(2).join(' ')==='--apply';if(process.argv.length>2&&!apply)throw Error('Use no arguments to review, or --apply'); const db=await openDatabase(process.env),bank=await openPostbankDatabase(process.env);try{const sql=await tradeGrantPlan(db,bank);if(apply){if(process.getuid?.()!==0)throw Error('Apply through the privileged deployment operator');execFileSync('mysql',['--batch'],{input:sql,stdio:['pipe','pipe','pipe']});console.log('Applied three SELECT-only trade grants. No business records or balances changed.');}else process.stdout.write(sql);}finally{await Promise.allSettled([db.close(),bank?.close()]);} }