Prepare bounded complimentary published kit grants through Jarvis

This commit is contained in:
unimatrixgit 2026-11-22 23:20:29 +01:00
commit 6029952f3b
4 changed files with 86 additions and 2 deletions

View file

@ -52,7 +52,7 @@ export const MASTER_KEY_TEMPLATES=[
{id:'items',label:'Items & kits',actions:[
action('equipment.starter-policy','Q0 starter and four-part repair policy','progression-policy',[field('season','Season'),field('policyVersion','Policy version','number',{min:2})],{webIssue:false,recordOnly:true,domainAdapter:'ensureStarterKitRewardPolicy',executionStatus:'recorded-system-policy',effect:'Describe half-durability Q0 faction kits and four repair parts. Configure one intact replacement through the existing quest reward outbox; no item or DM is issued by installing the policy.'}),
action('equipment.starter-event','Verified Q0 acquisition or repair','quest-milestone',[field('eventId','Verified game event'),field('kind','Acquired or repaired'),field('uuid','Linked Minecraft UUID'),field('kitInstanceId','Original Q0 kit instance')],{webIssue:false,recordOnly:true,domainAdapter:'starterKitEvents.record',executionStatus:'trusted-equipment-producer-only',effect:'Record actual faction-kit acquisition or surrender plus all four consumed repair parts. Source keys bind the original kit and season. Minecraft producer is future work; the browser cannot assert inventory events.'})]},
{id:'items',label:'Items & blueprints',actions:[action('items.kitset','Saved kitset definition','kit-definition',[field('kitsetId','Saved kitset'),field('revision','Saved revision','number',{min:1})],{webIssue:false,recordOnly:true,domainAdapter:'kitsets.generate',executionStatus:'authorised-kitset-definition',effect:'Freeze one saved kitset revision into a single definition key. Draft changes create no item keys. This record does not publish or deliver inventory.'}),action('items.definition','Versioned item definition','item-definition',[field('designId','Item design'),field('revision','Design revision','number',{min:1})],{webIssue:false,recordOnly:true,domainAdapter:'itemDesigns.save',executionStatus:'authorised-item-editor-draft',effect:'Save a complete MK and quality-bound item design with immutable versions. Reuse the same item contract for kit pieces and native generation. This record alone cannot publish a native definition, issue inventory or unlock a rarity.'})]},
{id:'items',label:'Items & blueprints',actions:[action('items.kitset-grant','Complimentary published stillsuit kit','kit-definition',[field('kitsetId','Published kit UUID'),field('requestId','Delivery request UUID'),field('recipientUuid','Linked recipient UUID')],{webIssue:false,recordOnly:true,domainAdapter:'prepareKitsetGrant/NativeKitGrant',executionStatus:'console-native-inventory',effect:'Current item-management authority prepares a short-lived signed grant from an immutable published kit key. The native console delivers the whole kit with a shared-profile transaction and a recipient-bound receipt. No bank charge, arbitrary native command or end-user issuance.'}),action('items.kitset','Saved kitset definition','kit-definition',[field('kitsetId','Saved kitset'),field('revision','Saved revision','number',{min:1})],{webIssue:false,recordOnly:true,domainAdapter:'kitsets.generate',executionStatus:'authorised-kitset-definition',effect:'Freeze one saved kitset revision into a single definition key. Draft changes create no item keys. This record does not publish or deliver inventory.'}),action('items.definition','Versioned item definition','item-definition',[field('designId','Item design'),field('revision','Design revision','number',{min:1})],{webIssue:false,recordOnly:true,domainAdapter:'itemDesigns.save',executionStatus:'authorised-item-editor-draft',effect:'Save a complete MK and quality-bound item design with immutable versions. Reuse the same item contract for kit pieces and native generation. This record alone cannot publish a native definition, issue inventory or unlock a rarity.'})]},
{id:'events',label:'Events',actions:[]},
{id:'game-exchange',label:'Ingame Exchange',actions:[action('exchange.native-sale','Publish held item','organisation-action',[field('uuid','Linked player UUID'),field('requestId','Inventory instruction UUID'),field('amount','Quantity','number',{min:1}),field('priceMinor','Unit price in minor units','number',{min:1})],{webIssue:false,recordOnly:true,domainAdapter:'createGameExchangeAPI + ExchangeInventory.publish',executionStatus:'authenticated-game-service',effect:'Resolve the current personal bank account centrally, then checkpoint the exact held item and native listing in one shared inventory transaction.'}),action('exchange.native-buy','Buy listed goods','organisation-action',[field('uuid','Linked player UUID'),field('requestId','Purchase UUID'),field('listingId','Native listing'),field('amount','Quantity','number',{min:1}),field('priceMinor','Confirmed unit price','number',{min:1})],{webIssue:false,recordOnly:true,domainAdapter:'createGameExchangeService.buy',executionStatus:'authenticated-game-service',effect:'Revalidate stock, price and debit authority. Commit balanced central bank entries, consumed stock and exact paid item delivery together. Native delivery remains queued when offline or full.'}),action('exchange.native-withdraw','Withdraw unsold goods','organisation-action',[field('uuid','Linked player UUID'),field('requestId','Inventory instruction UUID'),field('listingId','Own listing')],{webIssue:false,recordOnly:true,domainAdapter:'createGameExchangeAPI + ExchangeInventory.cancel',executionStatus:'authenticated-game-service',effect:'Return unsold stock only to its seller and only when the full quantity fits; commit native stock removal and player inventory checkpoint together.'})]},
{id:'rihla',label:'Rihla',actions:[]}

View file

@ -1,6 +1,6 @@
{
"schemaVersion": 1,
"sourceHash": "c87a920ac225790a1148d61ab2ea5ed5e76199ccfc36b5ff3f2cb4958dd7a5af",
"sourceHash": "a2d4f1ecee25ff46584a78cfa07001223ad0c70cdb6dec553805e06769b9c5fe",
"actions": [
{
"id": "clan.clear-protected-rosters",
@ -1732,6 +1732,43 @@
"webIssue": false,
"recordOnly": true
},
{
"id": "items.kitset-grant",
"label": "Items & blueprints · Complimentary published stillsuit kit",
"version": 1,
"keyType": "kit-definition",
"fields": [
{
"name": "ticketId",
"label": "Ban / support ticket ID",
"type": "text",
"required": true,
"maxLength": 80
},
{
"name": "kitsetId",
"label": "Published kit UUID",
"type": "text",
"required": true
},
{
"name": "requestId",
"label": "Delivery request UUID",
"type": "text",
"required": true
},
{
"name": "recipientUuid",
"label": "Linked recipient UUID",
"type": "text",
"required": true
}
],
"effect": "Current item-management authority prepares a short-lived signed grant from an immutable published kit key. The native console delivers the whole kit with a shared-profile transaction and a recipient-bound receipt. No bank charge, arbitrary native command or end-user issuance.",
"fixedTargets": [],
"webIssue": false,
"recordOnly": true
},
{
"id": "items.kitset",
"label": "Items & blueprints · Saved kitset definition",

View file

@ -0,0 +1,28 @@
// 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);
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||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.');
const kit=validateKitset(JSON.parse(row.design_json));if(!kit.items.length)throw Error('The published kit is empty.');
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.');return {design,template:itemDesignTemplate(design.templateId),quantity};});
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())});
}
const grantFingerprint=hash(JSON.stringify({requestId,keyId:row.key_id,definitionHash:row.fingerprint,recipients:linked.map(r=>r.uuid)}));
const data={action:'items.kitset-grant',requestId,serverKey,actorId:actors[0].id,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:0,expiresAt:data.expiresAt,state:'prepared'}};
}

View file

@ -0,0 +1,19 @@
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {createHash,createHmac} from 'node:crypto';
import {prepareKitsetGrant,kitGrantReceipt} from '../node/kitset-grants.mjs';
import {defaultItemDesign} from '../control-panel/public/item-design-model.mjs';
const actorId='f3ffda37-01e4-41ea-b89d-fbeda82e453e',kitsetId='f8f7f370-de8d-4f48-bf7b-ee15310f3a81',requestId='1fa03954-62cf-440a-b762-8b45924c3061',player='49d2fe76-7977-4d49-bd39-e48fc8c648b8',secret='b'.repeat(64);
function fixture(){
const design={version:1,name:'Test',owner:{kind:'office',id:'emperor'},items:[{id:'8d38f674-2155-44ba-b5dd-d1430f5c584a',quantity:1,design:defaultItemDesign('dr_s1_legendary_mk14_helmet')}]},raw=JSON.stringify(design);
const row={key_id:'8d38f674-2155-44ba-b5dd-d1430f5c584b',revision:1,design_json:raw,fingerprint:createHash('sha256').update(raw).digest('hex'),revoked_at:null,expires_at:null,key_type:'kit-definition'};
const db={async query(sql){assert.match(sql,/^SELECT /);if(sql.includes('jarvis_kitset_listings'))return [row];return [{id:actorId,username:'unimatrix999',role:'owner'}];}};
return {db,row,input:{actorId,kitsetId,requestId,recipients:[player],serverKey:'lobby'},settings:{GAME_LINK_SECRET:secret},options:{clock:()=>1000,allowed:async()=>true}};
}
test('prepares only a signed immutable definition, without writes or a bank charge',async()=>{const f=fixture(),r=await prepareKitsetGrant(f.db,f.input,f.settings,f.options);assert.equal(r.audit.chargedMinor,0);assert.equal(r.audit.state,'prepared');const d=JSON.parse(Buffer.from(r.envelope.payload,'base64'));assert.equal(d.kitName,'Test');assert.equal(d.items[0].design.equipmentMark,14);assert.equal(d.recipients[0].receiptId,kitGrantReceipt(requestId,player));assert.equal(r.envelope.signature,createHmac('sha256',secret).update(r.envelope.payload).digest('hex'));});
test('rejects missing current authority',async()=>{const f=fixture();await assert.rejects(prepareKitsetGrant(f.db,f.input,f.settings,{...f.options,allowed:async()=>false}),/authority/);});
test('rejects revoked definitions',async()=>{const f=fixture();f.row.revoked_at=1;await assert.rejects(prepareKitsetGrant(f.db,f.input,f.settings,f.options),/unavailable/);});
test('rejects edited published snapshots',async()=>{const f=fixture();f.row.design_json=f.row.design_json.replace('Test','Changed');await assert.rejects(prepareKitsetGrant(f.db,f.input,f.settings,f.options),/changed/);});
test('rejects duplicate or too many recipients',async()=>{const f=fixture();for(const recipients of [[player,player],[player,player,player]])await assert.rejects(prepareKitsetGrant(f.db,{...f.input,recipients},f.settings,f.options),/recipients/);});
test('rejects missing or ambiguous game links',async()=>{const f=fixture(),query=f.db.query;f.db.query=sql=>sql.includes('site_game_links')?Promise.resolve([]):query(sql);await assert.rejects(prepareKitsetGrant(f.db,f.input,f.settings,f.options),/linked personal/);});
test('receipt identities are stable and recipient-bound',()=>{assert.equal(kitGrantReceipt(requestId,player),kitGrantReceipt(requestId,player));assert.notEqual(kitGrantReceipt(requestId,player),kitGrantReceipt(requestId,actorId));});