77 lines
11 KiB
JavaScript
77 lines
11 KiB
JavaScript
import {createHash} from 'node:crypto';
|
|
import {prepareKitsetGrant,signKitsetDelivery,kitGrantReceipt} from './kitset-grants.mjs';
|
|
import {validateKitset} from '../control-panel/public/kitset-model.mjs';
|
|
import {PUBLIC_OFFICES} from './public-government.mjs';
|
|
import {createPostbankAuthority} from './postbank-authority.mjs';
|
|
import {canDebitAccount} from './postbank-authorisations.mjs';
|
|
import {ordinaryPaymentAccount} from './postbank-recipient-policy.mjs';
|
|
import {PostbankPayments} from './postbank-payments.mjs';
|
|
import {BankError} from './postbank-service.mjs';
|
|
import {can} from './permissions.mjs';
|
|
const hash=value=>createHash('sha256').update(value).digest('hex');
|
|
const uuid=value=>typeof value==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value);
|
|
const accountSQL='SELECT a.*,c.entity_id,e.kind,e.external_key,e.active AS entity_active,p.state AS package_state FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number JOIN pb_entities e ON e.id=c.entity_id JOIN pb_packages p ON p.id=a.package_id';
|
|
export function kitsetSellerSubject(owner){
|
|
if(['clan','company'].includes(owner?.kind)&&uuid(owner.id))return {kind:owner.kind,key:owner.id};
|
|
if(['office','politics'].includes(owner?.kind)){
|
|
const office=PUBLIC_OFFICES.find(o=>o.key===owner.id);if(office?.office==='emperor')return {kind:'office',key:'emperor'};
|
|
if(office&&['house_leader','reverent_mother','doci'].includes(office.office))return {kind:'office',key:'leader:'+office.faction};
|
|
}
|
|
throw new BankError('This kit owner does not have a supported banking identity.',409);
|
|
}
|
|
export const kitPurchaseFingerprint=({requestId,actorId,player,kitsetId,keyId,definitionHash,priceMinor})=>hash(JSON.stringify(['kitset-purchase-v1',requestId,actorId,player,kitsetId,keyId,definitionHash,Number(priceMinor)]));
|
|
// The journal is the delivery obligation. It commits with the existing bank
|
|
// payment on ONE verified MySQL connection; no second wallet or website queue.
|
|
export function createKitsetCommerce(db,bank,settings,{gamePool,clock=Date.now,authority=createPostbankAuthority(db,{bank}),allowed=actor=>can(db,actor,'web.menu.inventory'),prepare=prepareKitsetGrant,verifyStorage}={}){
|
|
const schema=settings.DB_NAME,gameSchema=(()=>{try{return new URL(settings.DUNE_INVENTORY_DATABASE_URL).pathname.slice(1);}catch{return '';}})();
|
|
if(!/^[a-z][a-z0-9_]{2,63}$/.test(schema||'')||!/^[a-z][a-z0-9_]{2,63}$/.test(gameSchema))throw Error('Verified central and game schema names are required.');
|
|
const central=name=>'`'+schema+'`.`'+name+'`',events=central('organisation_key_events'),versions=central('jarvis_kitset_versions'),listings=central('jarvis_kitset_listings'),keys=central('organisation_keys');
|
|
const payments=bank?new PostbankPayments(bank,authority,{clock}):null;let storage;
|
|
async function ready(){if(!storage)storage=(async()=>{
|
|
if(!bank)throw new BankError('The central bank is unavailable.',503);
|
|
if(verifyStorage){await verifyStorage();return;}
|
|
const sql='SELECT @@hostname host,@@port port,@@server_id server_id';const[b,c,g]=await Promise.all([bank.first(sql),db.query(sql),gamePool.query(sql)]);
|
|
if(!c[0]||!g.rows[0]||['host','port','server_id'].some(k=>String(b[k])!==String(c[0][k])||String(b[k])!==String(g.rows[0][k])))throw Error('Kit payment and delivery require one transaction server');
|
|
const rows=await bank.query('SELECT TABLE_NAME name,ENGINE engine FROM information_schema.TABLES WHERE TABLE_SCHEMA=? AND TABLE_NAME IN (?,?,?,?)',[schema,'organisation_key_events','jarvis_kitset_versions','jarvis_kitset_listings','organisation_keys']);
|
|
if(rows.length!==4||rows.some(r=>r.engine!=='InnoDB'))throw Error('Transactional kit registers are required');
|
|
})().catch(e=>{storage=null;throw e;});await storage;}
|
|
const targets=(store,subject)=>store.query(accountSQL+' WHERE e.kind=? AND e.external_key=? ORDER BY a.id',[subject.kind,subject.key]);
|
|
const sources=(store,actor)=>store.query(accountSQL+" WHERE e.kind='person' AND e.external_key=? AND a.type_code IN ('102','103','104','108') ORDER BY a.id",[actor.id]);
|
|
const receipt=(order,kitsetId,replayed)=>({requestId:order.id,kitsetId,state:'paid',delivery:'queued',totalMinor:Number(order.amount_minor),replayed});
|
|
return Object.freeze({
|
|
async available(owner){try{await ready();return (await targets(bank,kitsetSellerSubject(owner))).some(ordinaryPaymentAccount);}catch{return false;}},
|
|
async buy(actor,player,input){
|
|
if(!uuid(actor?.id)||!uuid(player)||!uuid(input?.requestId)||!uuid(input.kitsetId)||!Number.isSafeInteger(input.priceMinor)||input.priceMinor<1||input.priceMinor>100000000||!Number.isSafeInteger(input.listingVersion)||input.listingVersion<1||input.confirmed!==true)throw new BankError('Review the published kit, price and confirmation.',400);
|
|
player=player.toLowerCase();input={...input,requestId:input.requestId.toLowerCase(),kitsetId:input.kitsetId.toLowerCase()};
|
|
await ready();if(!await allowed(actor))throw new BankError('Exchange access is required.',403);
|
|
return bank.transaction(async tx=>{
|
|
const prior=await tx.first('SELECT * FROM pb_orders WHERE id=? FOR UPDATE',[input.requestId]);
|
|
if(prior){const grant=await tx.first('SELECT e.*,v.kitset_id,v.fingerprint FROM '+events+' e JOIN '+versions+' v ON v.key_id=e.key_id WHERE e.id=? FOR SHARE',[input.requestId]);const expected=grant&&kitPurchaseFingerprint({requestId:input.requestId,actorId:actor.id,player,kitsetId:input.kitsetId,keyId:grant.key_id,definitionHash:grant.fingerprint,priceMinor:input.priceMinor});if(!grant||grant.event_type!=='kit-purchase'||grant.account_id!==actor.id||grant.target_id!==actor.id||grant.kitset_id!==input.kitsetId||prior.actor_id!==actor.id||prior.fingerprint!==expected||Number(prior.amount_minor)!==input.priceMinor||prior.state!=='posted')throw new BankError('This purchase reference was already used or requires reconciliation.',409);return receipt(prior,input.kitsetId,true);}
|
|
const prepared=await prepare(db,{actorId:actor.id,kitsetId:input.kitsetId,requestId:input.requestId,recipients:[player],serverKey:'lobby'},settings,{clock,allowed});
|
|
if(prepared.audit.recipients?.length!==1||prepared.audit.recipients[0].accountId!==actor.id||prepared.audit.recipients[0].uuid!==player)throw new BankError('Your current linked Minecraft account changed.',409);
|
|
const version=await tx.first('SELECT l.revision listing_revision,l.price_minor,v.*,k.key_type,k.revoked_at,k.expires_at FROM '+listings+' l JOIN '+versions+' v ON v.key_id=l.key_id AND v.kitset_id=l.kitset_id JOIN '+keys+' k ON k.id=v.key_id WHERE l.kitset_id=? FOR SHARE',[input.kitsetId]);
|
|
if(!version||version.key_id!==prepared.audit.keyId||version.fingerprint!==prepared.audit.definitionHash||hash(version.design_json)!==version.fingerprint||version.key_type!=='kit-definition'||version.revoked_at!==null||version.expires_at!==null&&Number(version.expires_at)<=clock()||Number(version.price_minor)!==input.priceMinor||Number(version.listing_revision)!==input.listingVersion)throw new BankError('This published kit or its price changed. Refresh before buying.',409);
|
|
const design=validateKitset(JSON.parse(version.design_json)),subject=kitsetSellerSubject(design.owner),candidates=await sources(tx,actor),recipients=await targets(tx,subject);
|
|
const ids=[...new Set([...candidates,...recipients].map(a=>a.entity_id))].sort();for(const id of ids)await tx.first('SELECT id FROM pb_entities WHERE id=? FOR UPDATE',[id]);
|
|
const accountIds=[...new Set([...candidates,...recipients].map(a=>String(a.id)))];if(!accountIds.length)throw new BankError('Active buyer and organisation payment accounts are required.',409);
|
|
const rows=await tx.query(accountSQL+' WHERE a.id IN ('+accountIds.map(()=>'?').join(',')+') ORDER BY a.id FOR UPDATE',accountIds),context=await authority(actor,{bank:tx}),amount=BigInt(input.priceMinor);
|
|
if(!await allowed(actor))throw new BankError('Your Exchange authority changed.',403);
|
|
const source=rows.find(a=>a.kind==='person'&&a.external_key===actor.id&&ordinaryPaymentAccount(a)&&canDebitAccount(context,a.entity_id,a.id)&&BigInt(a.balance_minor)-BigInt(a.reserved_minor)>=amount),target=rows.find(a=>a.kind===subject.kind&&a.external_key===subject.key&&ordinaryPaymentAccount(a)&&BigInt(a.balance_minor)+amount<=9223372036854775807n);
|
|
if(!source||!target||String(source.id)===String(target.id))throw new BankError('Available funds or the organisation account are unavailable.',409);
|
|
const fingerprint=kitPurchaseFingerprint({requestId:input.requestId,actorId:actor.id,player,kitsetId:input.kitsetId,keyId:version.key_id,definitionHash:version.fingerprint,priceMinor:input.priceMinor});
|
|
await tx.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'exchange','queued',?)",[input.requestId,actor.id,source.id,target.id,fingerprint,amount.toString(),('Kit · '+design.name).slice(0,140),clock()]);
|
|
await payments.post(tx,{id:input.requestId,actor_id:actor.id,amount_minor:amount.toString()},source,target,false);
|
|
await tx.query('INSERT INTO '+events+'(id,key_id,account_id,event_type,target_id,created_at) VALUES(?,?,?,?,?,?)',[input.requestId,version.key_id,actor.id,'kit-purchase',actor.id,clock()]);
|
|
return receipt({id:input.requestId,amount_minor:amount.toString()},input.kitsetId,false);
|
|
});
|
|
},
|
|
async pending(actorId,player,serverKey){
|
|
await ready();if(!uuid(actorId)||!uuid(player))throw Error('Current linked buyer required');
|
|
// Filter durable native receipts BEFORE limiting, so delivered newer orders
|
|
// cannot hide an older unpaid delivery obligation.
|
|
const h="SHA2(CONCAT(e.id,CHAR(10),?),256)",nativeId="CONCAT(SUBSTR("+h+",1,8),'-',SUBSTR("+h+",9,4),'-5',SUBSTR("+h+",14,3),'-8',SUBSTR("+h+",18,3),'-',SUBSTR("+h+",21,12))";
|
|
const rows=await bank.query('SELECT e.id request_id,e.account_id,v.*,o.amount_minor,o.fingerprint order_fingerprint FROM '+events+' e JOIN '+versions+" v ON v.key_id=e.key_id JOIN pb_orders o ON o.id=e.id AND o.actor_id=e.account_id AND o.state='posted' LEFT JOIN `"+gameSchema+"`.dune_exchange_inventory_ops n ON n.id="+nativeId+" AND n.actor_uuid=? AND n.kind='kit-grant' WHERE e.event_type='kit-purchase' AND e.account_id=? AND e.target_id=? AND n.id IS NULL ORDER BY e.created_at,e.id LIMIT 16",[player,player,player,player,player,player,actorId,actorId]);
|
|
const result=[];let bytes=0;for(const row of rows){const priceMinor=Number(row.amount_minor);if(!Number.isSafeInteger(priceMinor)||priceMinor<1||row.fingerprint!==hash(row.design_json)||row.order_fingerprint!==kitPurchaseFingerprint({requestId:row.request_id,actorId,player,kitsetId:row.kitset_id,keyId:row.key_id,definitionHash:row.fingerprint,priceMinor}))throw Error('Paid kit source requires reconciliation');const kit=validateKitset(JSON.parse(row.design_json)),envelope=signKitsetDelivery(row,kit,{actorId,kitsetId:row.kitset_id,requestId:row.request_id,serverKey,action:'items.kitset-purchase',linked:[{uuid:player,accountId:actorId,receiptId:kitGrantReceipt(row.request_id,player)}]},settings,clock()).envelope;bytes+=Buffer.byteLength(JSON.stringify(envelope));if(bytes>750000)break;result.push(envelope);}return result;
|
|
}
|
|
});
|
|
}
|

Staff