71 lines
8.3 KiB
JavaScript
71 lines
8.3 KiB
JavaScript
// Ordinary staff action, prepared server-side from a published immutable key.
|
|
// Does not charge a bank, publish an API, or accept native commands from a design.
|
|
import {createHash,createHmac} from 'node:crypto';
|
|
import {validateKitset} from '../control-panel/public/kitset-model.mjs';
|
|
import {itemDesignTemplate} from '../control-panel/public/item-design-model.mjs';
|
|
import {can} from './permissions.mjs';
|
|
const hash=s=>createHash('sha256').update(s).digest('hex');
|
|
const uuid=s=>typeof s==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(s);
|
|
function currentDefinition(row,now){if(!row||row.key_type!=='kit-definition'||row.revoked_at!==null||row.expires_at!==null&&Number(row.expires_at)<=now||hash(row.design_json)!==row.fingerprint)throw Error('Published kit definition unavailable or changed.');return validateKitset(JSON.parse(row.design_json));}
|
|
export function kitGrantReceipt(request,recipient){const h=hash(request+'\n'+recipient).slice(0,32).split('');h[12]='5';h[16]='8';return [h.slice(0,8).join(''),h.slice(8,12).join(''),h.slice(12,16).join(''),h.slice(16,20).join(''),h.slice(20).join('')].join('-');}
|
|
export async function prepareKitsetGrant(db,{actorId,kitsetId,requestId,recipients,serverKey},settings,{clock=Date.now,allowed=(actor)=>can(db,actor,'web.items.manage')}={}){
|
|
if(!uuid(actorId)||!uuid(kitsetId)||!uuid(requestId)||!Array.isArray(recipients)||recipients.length<1||recipients.length>2||recipients.some(r=>!uuid(r))||new Set(recipients).size!==recipients.length||!/^[-a-z0-9_]{1,48}$/.test(serverKey)||typeof settings.GAME_LINK_SECRET!=='string'||settings.GAME_LINK_SECRET.length<32)throw TypeError('Use one published kit and up to two exact linked recipients.');
|
|
const actors=await db.query("SELECT id,username,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%' AND role NOT IN ('system_account','official_account','memorial')",[actorId]);
|
|
if(actors.length!==1||!await allowed(actors[0]))throw Error('Current item-management authority required.');
|
|
const rows=await db.query("SELECT v.key_id,v.revision,v.design_json,v.fingerprint,k.revoked_at,k.expires_at,k.key_type FROM jarvis_kitset_listings l JOIN jarvis_kitset_versions v ON v.key_id=l.key_id AND v.kitset_id=l.kitset_id JOIN organisation_keys k ON k.id=v.key_id WHERE l.kitset_id=?",[kitsetId]);
|
|
const row=rows[0],now=clock();if(rows.length!==1)throw Error('Published kit definition unavailable or changed.');
|
|
const kit=currentDefinition(row,now);if(!kit.items.length)throw Error('The published kit is empty.');
|
|
const linked=[];
|
|
for(const player of recipients){
|
|
const found=await db.query("SELECT a.id,a.username FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id WHERE LOWER(l.minecraft_uuid)=? AND a.password_hash NOT LIKE '!%' AND a.role NOT IN ('system_account','official_account','memorial')",[player.toLowerCase()]);
|
|
if(found.length!==1)throw Error('Each recipient needs one current linked personal account.');
|
|
linked.push({uuid:player.toLowerCase(),accountId:found[0].id,receiptId:kitGrantReceipt(requestId,player.toLowerCase())});
|
|
}
|
|
return signKitsetDelivery(row,kit,{actorId:actors[0].id,kitsetId,requestId,serverKey,linked},settings,now);
|
|
}
|
|
export function signKitsetDelivery(row,kit,{actorId,kitsetId,requestId,serverKey,linked,action="items.kitset-grant"},settings,now){
|
|
if(!["items.kitset-grant","items.kitset-purchase"].includes(action))throw Error("Unsupported delivery action");
|
|
const items=kitsetDeliveryItems(kit);
|
|
const grantFingerprint=hash(JSON.stringify({requestId,keyId:row.key_id,definitionHash:row.fingerprint,recipients:linked.map(r=>r.uuid)}));
|
|
const data={action,requestId,serverKey,actorId,kitsetId,kitKeyId:row.key_id,kitRevision:Number(row.revision),kitName:kit.name,definitionHash:row.fingerprint,grantFingerprint,issuedAt:now,expiresAt:now+900000,recipients:linked,items};
|
|
const payload=Buffer.from(JSON.stringify(data)).toString('base64');if(payload.length>350000)throw Error('Kit delivery exceeds its native bound.');
|
|
return {envelope:{schema:1,payload,signature:createHmac('sha256',settings.GAME_LINK_SECRET).update(payload).digest('hex')},audit:{requestId,action:data.action,actorId,kitsetId,keyId:row.key_id,definitionHash:row.fingerprint,grantFingerprint,recipients:linked,items:items.reduce((n,i)=>n+i.quantity,0),chargedMinor:action==='items.kitset-grant'?0:null,expiresAt:data.expiresAt,state:action==='items.kitset-grant'?'prepared':'delivery-proof'}};
|
|
}
|
|
|
|
/** Reserve the gift once in the existing key-event journal. No wallet writes. */
|
|
export async function issueKitsetGrant(db,input,settings,dependencies={}){
|
|
const prepared=await prepareKitsetGrant(db,input,settings,dependencies),now=(dependencies.clock||Date.now)();
|
|
return db.transaction(async tx=>{
|
|
const actors=await tx.query("SELECT id,username,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%' FOR UPDATE",[input.actorId]);
|
|
const allowed=dependencies.allowed||(actor=>can(db,actor,'web.items.manage'));if(actors.length!==1||!await allowed(actors[0]))throw Error('Current item-management authority required.');
|
|
const versions=await tx.query('SELECT v.*,k.key_type,k.revoked_at,k.expires_at FROM jarvis_kitset_versions v JOIN organisation_keys k ON k.id=v.key_id WHERE v.key_id=? FOR UPDATE',[prepared.audit.keyId]);
|
|
if(versions.length!==1||versions[0].fingerprint!==prepared.audit.definitionHash)throw Error('Kit definition changed.');currentDefinition(versions[0],now);
|
|
const gifts=[];
|
|
for(const recipient of prepared.audit.recipients){
|
|
const id=kitGrantReceipt(input.requestId,recipient.uuid),prior=(await tx.query('SELECT * FROM organisation_key_events WHERE id=? FOR UPDATE',[id]))[0];
|
|
if(prior){if(prior.key_id!==prepared.audit.keyId||prior.account_id!==input.actorId||prior.target_id!==recipient.accountId||prior.event_type!=='kit-grant')throw Error('Gift request reference already used.');}
|
|
else await tx.query('INSERT INTO organisation_key_events(id,key_id,account_id,event_type,target_id,created_at) VALUES(?,?,?,?,?,?)',[id,prepared.audit.keyId,input.actorId,'kit-grant',recipient.accountId,now]);
|
|
gifts.push({grantId:id,uuid:recipient.uuid,accountId:recipient.accountId,replayed:!!prior});
|
|
}
|
|
return {action:'items.kitset-grant',requestId:input.requestId,keyId:prepared.audit.keyId,gifts,chargedMinor:0,state:'issued'};
|
|
});
|
|
}
|
|
|
|
/** Existing gifts remain owed after the issuer changes role. This never issues one. */
|
|
export async function pendingKitsetGrants(db,player,serverKey,settings,{clock=Date.now}={}){
|
|
if(!uuid(player)||!/^[-a-z0-9_]{1,48}$/.test(serverKey))throw TypeError('Current game identity required.');
|
|
const people=await db.query("SELECT a.id FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id WHERE LOWER(l.minecraft_uuid)=? AND a.password_hash NOT LIKE '!%' AND a.role NOT IN ('system_account','official_account','memorial')",[player.toLowerCase()]);
|
|
if(people.length!==1)throw Error('Current linked personal account required.');
|
|
const rows=await db.query("SELECT e.id grant_id,e.account_id actor_id,v.*,k.key_type,k.revoked_at,k.expires_at FROM organisation_key_events e JOIN jarvis_kitset_versions v ON v.key_id=e.key_id JOIN organisation_keys k ON k.id=v.key_id WHERE e.event_type='kit-grant' AND e.target_id=? ORDER BY e.created_at DESC,e.id LIMIT 16",[people[0].id]);
|
|
const grants=[];let bytes=0;for(const row of rows){try{
|
|
const kit=currentDefinition(row,clock());
|
|
const envelope=signKitsetDelivery(row,kit,{actorId:row.actor_id,kitsetId:row.kitset_id,requestId:row.grant_id,serverKey,linked:[{uuid:player.toLowerCase(),accountId:people[0].id,receiptId:kitGrantReceipt(row.grant_id,player.toLowerCase())}]},settings,clock()).envelope;
|
|
bytes+=Buffer.byteLength(JSON.stringify(envelope));if(bytes>750000)break;grants.push(envelope);
|
|
}catch{/* Revoked or malformed source keys are retained, never silently replaced. */}}
|
|
return grants;
|
|
}
|
|
|
|
export function kitsetDeliveryItems(kit){
|
|
let slots=0;const items=kit.items.map(({design,quantity})=>{const rocket=['dr_s1_spice_rocket_mk1','dr_s1_refined_rocket_mk2','dr_s1_polluted_rocket_mk3'].includes(design.templateId);if(!['equipment','mining-tool','weapon','flight-equipment'].includes(design.itemClass)&&!rocket)throw Error('This kit requires its native consumable adapter.');const template=itemDesignTemplate(design.templateId);slots+=Math.ceil(quantity/(rocket?64:1));return {design,template,quantity};});
|
|
if(slots>36)throw Error('This kit needs more than 36 inventory slots. Reduce its quantities before publishing.');return items;
|
|
}
|

Staff