116 lines
17 KiB
JavaScript
116 lines
17 KiB
JavaScript
import {setEntityParent} from './entity-relations.mjs';
|
|
import {createHash} from 'node:crypto';
|
|
import {JarvisError} from './jarvis-listings.mjs';
|
|
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
|
|
const action='relations.transfer',scopeFor=(kind,id,request)=>'deed-sale:'+kind+':'+id+':'+request;
|
|
const first=(db,sql,args)=>db.first?db.first(sql,args):db.prepare(sql).bind(...args).first();
|
|
export function deedPriceMinor(value){if(typeof value!=='string'||!/^\d{1,12}(?:\.\d{1,2})?$/.test(value))throw new JarvisError('Enter a positive deed price with at most two decimals.');const [whole,fraction='']=value.split('.'),amount=BigInt(whole)*100n+BigInt(fraction.padEnd(2,'0'));if(amount<1n||amount>BigInt(Number.MAX_SAFE_INTEGER))throw new JarvisError('Deed price is outside the supported range.');return Number(amount);}
|
|
async function snapshot(db,kind,id,lock=false){
|
|
if(!['clan','company'].includes(kind)||!uuid(id))throw new JarvisError('Choose an ordinary clan or company deed.');
|
|
const sql=kind==='clan'?"SELECT c.id,c.name,c.owner_id AS ownerId,c.version AS entityVersion,d.version AS deedVersion,i.institution_key AS institution FROM site_clans c JOIN site_clan_deeds d ON d.clan_id=c.id LEFT JOIN site_clan_institutions i ON i.clan_id=c.id WHERE c.id=? AND c.active=1":"SELECT c.id,c.name,d.owner_account_id AS ownerId,d.version AS entityVersion,d.version AS deedVersion,i.institution_key AS institution FROM corrino_companies c JOIN site_company_deeds d ON d.company_id=c.id LEFT JOIN site_company_institutions i ON i.company_id=c.id WHERE c.id=? AND c.status='active'";
|
|
const row=await first(db,sql+(lock?' FOR UPDATE':''),[id]);
|
|
if(!row||row.institution)throw new JarvisError('Only ordinary active clan/company deeds can be offered.',403);
|
|
const member=await first(db,kind==='clan'?"SELECT m.user_id FROM site_clan_members m JOIN site_accounts a ON a.id=m.user_id AND a.password_hash NOT LIKE '!%' JOIN site_game_links l ON l.user_id=m.user_id AND l.minecraft_uuid=m.minecraft_uuid WHERE m.clan_id=? AND m.user_id=? AND m.clan_role='owner'":"SELECT m.user_id FROM site_company_members m JOIN site_accounts a ON a.id=m.user_id AND a.password_hash NOT LIKE '!%' JOIN site_game_links l ON l.user_id=m.user_id WHERE m.company_id=? AND m.user_id=?",[id,row.ownerId]);
|
|
if(!member)throw new JarvisError('The current deed owner could not be verified.',409);
|
|
return {kind,id:row.id,name:row.name,ownerId:row.ownerId,entityVersion:Number(row.entityVersion),deedVersion:Number(row.deedVersion)};
|
|
}
|
|
// Sale fields belong to the existing XFR dossier. No second key store or financial
|
|
// engine is introduced. Buyer is deliberately unbound until verified purchase.
|
|
export function createDeedSaleKeys(central,keys,{clock=Date.now,verifyPurchaseIntent=async()=>false,verifyPurchaseFunding=async()=>false}={}){
|
|
async function readOffer(keyId){return first(central,'SELECT i.*,k.account_id AS key_owner,k.key_type,k.scope_id,k.revoked_at,k.used_at FROM jarvis_generated_instructions i JOIN organisation_keys k ON k.id=i.key_id WHERE i.key_id=? AND i.action_id=?',[keyId,action]);}
|
|
async function currentOffer(keyId){
|
|
const row=await readOffer(keyId);if(!row||row.state!=='issued'||row.key_type!=='entity-transfer'||row.revoked_at!=null||row.used_at!=null)return null;
|
|
let manifest,fields;try{manifest=JSON.parse(row.manifest_json);fields=JSON.parse(row.fields_json);}catch{return null;}
|
|
if(!manifest.deed||!fields||!Number.isSafeInteger(manifest.priceMinor)||manifest.priceMinor<1||fields.priceMinor!==manifest.priceMinor||fields.entityId!==manifest.deed.id||fields.kind!==manifest.deed.kind||fields.version!==manifest.deed.entityVersion||fields.reference!==manifest.message||fields.recipient!==null)return null;
|
|
if(manifest.operation!=='deed-sale'||manifest.recipient!==null||row.key_owner!==row.account_id||row.scope_id!==scopeFor(manifest.deed.kind,manifest.deed.id,row.request_id))return null;
|
|
try{const current=await snapshot(central,manifest.deed.kind,manifest.deed.id);if(JSON.stringify(current)!==JSON.stringify(manifest.deed)||current.ownerId!==row.account_id)return null;}catch{return null;}
|
|
return {row,manifest};
|
|
}
|
|
return Object.freeze({
|
|
async issue(actor,input){
|
|
if(!keys)throw new JarvisError('The key service is unavailable.',503);
|
|
if(!uuid(actor?.id)||!input||Object.keys(input).some(k=>!['kind','entityId','version','price','message','requestId','confirmed'].includes(k))||!uuid(input.requestId)||!uuid(input.entityId)||!['clan','company'].includes(input.kind)||input.confirmed!==true||!Number.isSafeInteger(input.version)||input.version<1||typeof input.message!=='string'||input.message.length>240||/[\x00-\x1f\x7f]/.test(input.message))throw new JarvisError('Review the current deed, price and sale message.');
|
|
const priceMinor=deedPriceMinor(input.price),fields={entityId:input.entityId,recipient:null,reference:input.message.trim(),kind:input.kind,version:input.version,priceMinor},encoded=JSON.stringify(fields);
|
|
const grant=await keys.issue({accountId:actor.id,keyType:'entity-transfer',scopeId:scopeFor(input.kind,input.entityId,input.requestId),authorize:async(tx,{keyId})=>{
|
|
const deed=await snapshot(tx,input.kind,input.entityId,true);
|
|
if(deed.ownerId!==actor.id)throw new JarvisError('Only the current deed owner may offer this organisation.',403);
|
|
if(deed.entityVersion!==input.version)throw new JarvisError('The deed changed. Refresh before offering it.',409);
|
|
const prior=await tx.first('SELECT key_id,account_id,fields_json FROM jarvis_generated_instructions WHERE request_id=? AND action_id=?',[input.requestId,action]);
|
|
if(prior){if(prior.account_id!==actor.id||prior.fields_json!==encoded)throw new JarvisError('Sale instruction reference conflict.',409);return;}
|
|
const pending=await tx.first("SELECT k.id FROM organisation_keys k JOIN jarvis_generated_instructions i ON i.key_id=k.id WHERE k.key_type='entity-transfer' AND k.scope_id LIKE ? AND k.revoked_at IS NULL AND k.used_at IS NULL AND i.state IN ('issued','reserved')",['deed-sale:'+input.kind+':'+input.entityId+':%']);
|
|
if(pending)throw new JarvisError('This deed already has an outstanding sale instruction.',409);
|
|
const manifest={operation:'deed-sale',deed,priceMinor,message:fields.reference,recipient:null,listingId:input.requestId};
|
|
await tx.query("INSERT INTO jarvis_generated_instructions(key_id,request_id,account_id,action_id,template_version,fields_json,manifest_json,state,created_at) VALUES(?,?,?,?,1,?,?,'issued',?)",[keyId,input.requestId,actor.id,action,encoded,JSON.stringify(manifest),clock()]);
|
|
}});
|
|
const offer=await currentOffer(grant.id);if(!offer||offer.row.account_id!==actor.id||offer.row.request_id!==input.requestId||offer.row.fields_json!==encoded)throw new JarvisError('The sale instruction changed. Refresh before retrying.',409);
|
|
return {keyId:grant.id,listingId:input.requestId,kind:input.kind,entityId:input.entityId,title:offer.manifest.deed.name+' · deed',message:fields.reference,priceMinor,created:grant.created};
|
|
},
|
|
|
|
async purchaseOffer(listingId){
|
|
if(!uuid(listingId))throw new JarvisError('Choose a deed offer.');const row=await first(central,'SELECT key_id FROM jarvis_generated_instructions WHERE request_id=? AND action_id=?',[listingId,action]);const offer=row&&await currentOffer(row.key_id);if(!offer)throw new JarvisError('Current deed offer unavailable.',409);return {keyId:row.key_id,listingId,sellerId:offer.manifest.deed.ownerId,kind:offer.manifest.deed.kind,entityId:offer.manifest.deed.id,name:offer.manifest.deed.name,priceMinor:offer.manifest.priceMinor};
|
|
},
|
|
async purchaseState(keyId){
|
|
if(!uuid(keyId))throw new JarvisError('Choose a purchase key.');const row=await readOffer(keyId);if(!row)return null;const purchase=JSON.parse(row.manifest_json).purchase;const used=await first(central,'SELECT target_id,request_id FROM organisation_keys WHERE id=?',[keyId]);return {state:row.state,keyUsed:row.used_at!=null,keyRevoked:row.revoked_at!=null,requestId:purchase?.requestId||null,buyerId:purchase?.buyerId||null,applied:row.state==='applied'&&row.used_at!=null&&used?.request_id===purchase?.requestId&&used?.target_id===purchase?.parent?.id};
|
|
},
|
|
async reservePurchase(actor,input){
|
|
if(!uuid(actor?.id)||!input||Object.keys(input).some(k=>!['keyId','requestId','parentKind','parentId','sourceAccount','recipientAccount'].includes(k))||!uuid(input.keyId)||!uuid(input.requestId)||!uuid(input.parentId)||!['clan','company'].includes(input.parentKind)||!/^\d{1,12}$/.test(input.sourceAccount)||!/^\d{1,12}$/.test(input.recipientAccount))throw new JarvisError('Review the purchase and its payment accounts.');
|
|
return central.transaction(async tx=>{
|
|
const key=await tx.first('SELECT * FROM organisation_keys WHERE id=? FOR UPDATE',[input.keyId]);
|
|
const row=await tx.first('SELECT * FROM jarvis_generated_instructions WHERE key_id=? AND action_id=? FOR UPDATE',[input.keyId,action]);
|
|
if(!key||!row||key.key_type!=='entity-transfer'||key.revoked_at!=null||key.used_at!=null)throw new JarvisError('The sale key is unavailable.',409);
|
|
const manifest=JSON.parse(row.manifest_json),fingerprint=createHash('sha256').update(JSON.stringify([actor.id,input.keyId,input.requestId,input.parentKind,input.parentId,input.sourceAccount,input.recipientAccount])).digest('hex');
|
|
if(input.parentKind!==manifest.deed?.kind)throw new JarvisError('Ordinary deed purchases require the same organisation type.',409);
|
|
if(row.state==='reserved'){if(manifest.purchase?.fingerprint!==fingerprint)throw new JarvisError('This deed is reserved for another purchase.',409);return manifest.purchase;}
|
|
if(row.state!=='issued'||manifest.operation!=='deed-sale'||manifest.deed?.ownerId===actor.id)throw new JarvisError('Choose an available deed belonging to another owner.',409);
|
|
const current=await snapshot(tx,manifest.deed.kind,manifest.deed.id,true);if(JSON.stringify(current)!==JSON.stringify(manifest.deed)||key.account_id!==current.ownerId||key.scope_id!==scopeFor(current.kind,current.id,row.request_id))throw new JarvisError('The offered deed changed.',409);
|
|
const parent=await snapshot(tx,input.parentKind,input.parentId,true),charter=await tx.first(input.parentKind==='company'?'SELECT charter_kind FROM site_company_deeds WHERE company_id=?':'SELECT charter_kind FROM site_clan_charters WHERE clan_id=?',[input.parentId]);
|
|
if(parent.ownerId!==actor.id||!['original','royal'].includes(charter?.charter_kind))throw new JarvisError('The purchasing organisation needs your current original or Royal deed.',403);
|
|
const purchase={requestId:input.requestId,buyerId:actor.id,keyId:input.keyId,parent,sourceAccount:input.sourceAccount,recipientAccount:input.recipientAccount,priceMinor:manifest.priceMinor,fingerprint};
|
|
if(await verifyPurchaseIntent(actor,{...purchase,sellerId:current.ownerId,listingId:manifest.listingId})!==true)throw new JarvisError('A confirmed matching purchase intent is required.',409);
|
|
manifest.purchase=purchase;await tx.query("UPDATE jarvis_generated_instructions SET state='reserved',manifest_json=? WHERE key_id=?",[JSON.stringify(manifest),input.keyId]);return purchase;
|
|
});
|
|
},
|
|
async applyPurchase(actor,{keyId,requestId}){
|
|
if(!uuid(actor?.id)||!uuid(keyId)||!uuid(requestId))throw new JarvisError('Choose a verified purchase.');
|
|
const instruction=await readOffer(keyId);if(!instruction)throw new JarvisError('Purchase instruction unavailable.',409);const manifest=JSON.parse(instruction.manifest_json),purchase=manifest.purchase;
|
|
if(!purchase||purchase.requestId!==requestId||purchase.buyerId!==actor.id)throw new JarvisError('Purchase scope changed.',409);
|
|
if(instruction.state==='applied'){const used=await first(central,'SELECT used_at,target_id,request_id FROM organisation_keys WHERE id=?',[keyId]);if(!used?.used_at||used.request_id!==requestId||used.target_id!==purchase.parent.id)throw new JarvisError('Purchase receipt requires review.',409);return {keyId,requestId,replayed:true};}
|
|
if(purchase.parent.kind!==manifest.deed.kind)throw new JarvisError('Ordinary deed purchases require the same organisation type.',409);
|
|
if(instruction.state!=='reserved'||await verifyPurchaseFunding(actor,{...purchase,sellerId:manifest.deed.ownerId,listingId:manifest.listingId})!==true)throw new JarvisError('Verified reserved purchase funds are required.',409);
|
|
const key=(await keys.list(instruction.account_id)).find(k=>k.id===keyId);if(!key||key.status!=='available')throw new JarvisError('Sale key unavailable.',409);
|
|
const result=await keys.consume({accountId:instruction.account_id,keyType:'entity-transfer',code:key.code,targetId:purchase.parent.id,requestId,apply:async(tx,context)=>{
|
|
const row=await tx.first('SELECT state,manifest_json FROM jarvis_generated_instructions WHERE key_id=? FOR UPDATE',[keyId]),saved=JSON.parse(row?.manifest_json||'null');
|
|
if(row?.state!=='reserved'||saved?.purchase?.fingerprint!==purchase.fingerprint||context.keyId!==keyId)throw new JarvisError('Purchase reservation changed.',409);
|
|
const current=await snapshot(tx,manifest.deed.kind,manifest.deed.id,true),parent=await snapshot(tx,purchase.parent.kind,purchase.parent.id,true);
|
|
if(JSON.stringify(current)!==JSON.stringify(manifest.deed)||JSON.stringify(parent)!==JSON.stringify(purchase.parent)||parent.ownerId!==actor.id)throw new JarvisError('A purchase deed changed before transfer.',409);
|
|
if(await verifyPurchaseFunding(actor,{...purchase,sellerId:current.ownerId,listingId:manifest.listingId})!==true)throw new JarvisError('Purchase funding changed.',409);
|
|
try{await setEntityParent(tx,{childKind:current.kind,childId:current.id,parentKind:parent.kind,parentId:parent.id,origin:'purchase',keyId,requestId,actorId:actor.id,now:clock()});}catch(error){if(['Parent deed would create a cycle','Parent deed unavailable','Parent hierarchy too deep'].includes(error.message))throw new JarvisError(error.message,409);throw error;}
|
|
await tx.query("UPDATE jarvis_generated_instructions SET state='applied' WHERE key_id=?",[keyId]);
|
|
}});return {keyId,requestId,replayed:result.replayed};
|
|
},
|
|
async releasePurchase(actor,{keyId,requestId}){
|
|
if(!uuid(actor?.id)||!uuid(keyId)||!uuid(requestId))throw new JarvisError('Choose a current purchase reservation.');
|
|
return central.transaction(async tx=>{
|
|
const key=await tx.first('SELECT used_at FROM organisation_keys WHERE id=? FOR UPDATE',[keyId]),row=await tx.first('SELECT state,manifest_json FROM jarvis_generated_instructions WHERE key_id=? FOR UPDATE',[keyId]);
|
|
if(!key||!row||key.used_at!=null||row.state==='applied')throw new JarvisError('An applied purchase cannot be released.',409);
|
|
const manifest=JSON.parse(row.manifest_json);if(row.state!=='reserved'||manifest.purchase?.requestId!==requestId||manifest.purchase?.buyerId!==actor.id)throw new JarvisError('Purchase reservation scope changed.',409);
|
|
// The payment adapter may release only a terminal failed/cancelled intent,
|
|
// never an outstanding escrow. Live funded state keeps the key locked.
|
|
if(await verifyPurchaseIntent(actor,{...manifest.purchase,releasing:true,sellerId:manifest.deed.ownerId,listingId:manifest.listingId})!==true)throw new JarvisError('Purchase funds must be reconciled before releasing the key.',409);
|
|
delete manifest.purchase;await tx.query("UPDATE jarvis_generated_instructions SET state='issued',manifest_json=? WHERE key_id=?",[JSON.stringify(manifest),keyId]);return {released:true};
|
|
});
|
|
},
|
|
async listing(actor,keyId){const offer=await currentOffer(keyId);if(!offer||offer.row.account_id!==actor.id)throw new JarvisError('Current sale-key authority is required.',403);const m=offer.manifest;return {id:m.listingId,keyId,kind:m.deed.kind,entityId:m.deed.id,title:m.deed.name+' · deed',message:m.message,organisationName:m.deed.name,priceMinor:m.priceMinor,fingerprint:createHash('sha256').update(offer.row.fields_json+':'+actor.id+':'+keyId).digest('hex')};},
|
|
async cancel(actor,listingId){
|
|
if(!uuid(actor?.id)||!uuid(listingId))throw new JarvisError('Choose a current sale listing.');
|
|
const entry=await first(central,'SELECT key_id FROM jarvis_generated_instructions WHERE request_id=? AND action_id=?',[listingId,action]);if(!entry)throw new JarvisError('Sale instruction not found.',404);
|
|
const row=await readOffer(entry.key_id);if(!row)throw new JarvisError('Sale instruction unavailable.',409);const manifest=JSON.parse(row.manifest_json);if(row.account_id!==actor.id||manifest.operation!=='deed-sale'||!['issued','cancelled'].includes(row.state))throw new JarvisError('Sale-key owner authority required.',403);
|
|
return keys.revoke({accountId:actor.id,keyId:entry.key_id,authorize:async(tx,context)=>{const current=await snapshot(tx,manifest.deed.kind,manifest.deed.id,true);if(current.ownerId!==actor.id||context.keyType!=='entity-transfer'||context.scopeId!==scopeFor(current.kind,current.id,row.request_id))throw new JarvisError('Deed authority changed.',403);await tx.query("UPDATE jarvis_generated_instructions SET state='cancelled' WHERE key_id=?",[entry.key_id]);return true;}});
|
|
},
|
|
async describe(listing){
|
|
const row=await first(central,'SELECT key_id FROM jarvis_generated_instructions WHERE request_id=? AND action_id=?',[listing.id,action]);if(!row)return null;
|
|
const offer=await currentOffer(row.key_id);if(!offer||offer.manifest.listingId!==listing.id||offer.manifest.deed.id!==listing.organisationId||offer.manifest.deed.kind!==listing.organisationKind)return null;
|
|
const m=offer.manifest;return {...listing,category:'deeds',type:'deeds',price:m.priceMinor/100,quantity:1,emblem:'https://cp.dunerealms.com/api/'+(m.deed.kind==='clan'?'clan':'company')+'-emblems/'+m.deed.id,purchaseAvailable:false,description:m.message};
|
|
}
|
|
});
|
|
}
|

Staff