Settle spice against read-only native inventory receipts
This commit is contained in:
parent
5611c50ce9
commit
20ac05e66c
5 changed files with 13 additions and 9 deletions
|
|
@ -35,7 +35,7 @@ export const MASTER_KEY_TEMPLATES=[
|
|||
action('progression.pol-funded-rewards','Funded Reputation reward delivery','quest',[],{webIssue:false,recordOnly:true,domainAdapter:'createPOLFundedRewards',executionStatus:'consumed-quest-outbox-only',effect:'Pay only explicitly configured and verified claim rewards from existing website treasury funds to the bound ordinary player bank account. Original QST identity prevents duplicate ledger entries; unfunded or invalid rewards remain queued.'}),
|
||||
action('progression.flight-policy','Elytra Reputation quest policy','progression-policy',[],{version:4,webIssue:false,recordOnly:true,domainAdapter:'ensureElytraQuestPolicy',executionStatus:'recorded-system-policy',effect:'Install the twelve Elytra quest reward configurations through their own policy:POL:S01:v4 instrument. Preserve existing quest settings, season dates and the separate v3 Mentat bonus instrument.'}),
|
||||
action('progression.game-observation','Native quest observation','quest-milestone',[field('eventId','Original native event UUID'),field('uuid','Linked Minecraft UUID'),field('kind','Fixed observation kind'),field('server','Native server'),field('occurredAt','Original event time','number',{min:1}),field('quantity','Native produced quantity','number',{min:1,max:64,required:false}),field('dimension','Native dimension','text',{required:false}),field('source','Fixed Elytra acquisition source','text',{required:false})],{version:4,webIssue:false,recordOnly:true,domainAdapter:'createGameQuestEventsAPI',executionStatus:'authenticated-game-service',effect:'Record confirmed Citizen briefing acknowledgements, real Arrakis visits, active survival minutes, durability-consuming equipment use and native spice drops from successful mining. Spice feeds the existing Personal and repeatable Reputation QSM adapters. Fixed world/dimension flight observations feed the Reputation Elytra branch. A committed paid delivery or natural End-ship acquisition completes only this branch, awarding its remaining rewards once. Preserve source UUID on retries. Creative/spectator gameplay and AFK/lobby movement supply no progress. A deliberate Citizen briefing acknowledgement is allowed in the lobby; other menu clicks never assert gameplay completion.'}),
|
||||
action('commerce.spice-sale','Arrakis spice sale','entity-state',[field('uuid','Linked Minecraft UUID'),field('requestId','Original sale UUID'),field('channel','Buyer','select',{options:['guild','smuggler']}),field('amount','Surrendered spice','number',{min:1,max:2368})],{webIssue:false,recordOnly:true,domainAdapter:'createGameSpiceAPI + ExchangeInventory.sellSpice',executionStatus:'authenticated-arrakis-inventory-receipt',effect:'Arrakis only. Guild and Smuggler have separate server prices; Smuggler requires an active Smuggler quest. Native Core checkpoints all surrendered raw Melange Spice before the central bank pays its personal recipient from fixed P&O, with the existing Trust levy. Original request UUID binds quote, inventory receipt and balanced bank entries. Retry and reconnect recover an unpaid receipt without taking spice or paying twice. No Vault wallet or Exchange listing.'}),
|
||||
action('commerce.spice-sale','Arrakis spice sale','entity-state',[field('uuid','Linked Minecraft UUID'),field('requestId','Original sale UUID'),field('channel','Buyer','select',{options:['guild','smuggler']}),field('amount','Surrendered spice','number',{min:1,max:21312})],{version:2,webIssue:false,recordOnly:true,domainAdapter:'createGameSpiceAPI + ExchangeInventory.sellSpice',executionStatus:'authenticated-arrakis-inventory-receipt',effect:'Arrakis only. Guild and Smuggler have separate server prices; Smuggler requires an active Smuggler quest. Native Core checkpoints all surrendered raw Melange Spice and compressed blocks (nine raw units each), retaining Guild versus contraband identity before the central bank pays its personal recipient from fixed P&O, with the existing Trust levy. Original request UUID binds quote, inventory receipt and balanced bank entries. Retry and reconnect recover an unpaid receipt without taking spice or paying twice. No Vault wallet or Exchange listing.'}),
|
||||
action('progression.spice-refining','NPC spice refinement','quest-milestone',[field('uuid','Linked player UUID'),field('requestId','Original turn-in UUID'),field('definitionId','Fixed refining quest'),field('npcUuid','Nearby Arrakis Smuggler UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createGameQuestsAPI.prepare_refine + SpiceRefiner + ExchangeInventory.refine',executionStatus:'authenticated-native-npc-turn-in',effect:'Revalidate the current player and quest prerequisites, then require the physical Arrakis NPC again before consuming two real raw spice, or two refined spice and two scraps. Core checkpoints inputs, two EI outputs and a recoverable receipt atomically. Existing QSM observations award no reward until verified by the Reputation quest engine.'}),
|
||||
action('progression.earned-dm','Verified earned DM','quest-milestone',[],{webIssue:false,recordOnly:true,domainAdapter:'bankQuestIncome + progressionRuntime.collect',executionStatus:'committed-central-bank-source',effect:'Count posted wages, Exchange sale income, incoming bank transfers and verified quest treasury credits across the player’s personal central-bank accounts during the active season. Count each bank order once and preserve cumulative earnings after spending. Exclude own-account transfers, refunds, pending payments, unrelated system grants and organisation income; never use a legacy game wallet or current balance as an earnings counter.'}),
|
||||
action('progression.exchange-purchase','Committed Exchange quest evidence','quest-milestone',[],{webIssue:false,recordOnly:true,domainAdapter:'createBankQuestActivities',executionStatus:'committed-central-bank-source',effect:'Read the first settled Exchange purchase in the current season into existing Personal activity keys. Pending orders, self transfers, another customer and legacy wallets never count. Reuse the original order UUID without issuing a reward from the reader.'}),
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"schemaVersion": 1,
|
||||
"sourceHash": "8bf70a731d1d5400867f6c5c173913b7baf5ee596bd014295589354c52df055b",
|
||||
"sourceHash": "8ca2be330243474c7ce5643afc36a98db8da5d9bc4c4f8722cae8cc10f9ccf3a",
|
||||
"actions": [
|
||||
{
|
||||
"id": "clan.clear-protected-rosters",
|
||||
|
|
@ -1306,7 +1306,7 @@
|
|||
{
|
||||
"id": "commerce.spice-sale",
|
||||
"label": "Progression & XP · Arrakis spice sale",
|
||||
"version": 1,
|
||||
"version": 2,
|
||||
"keyType": "entity-state",
|
||||
"fields": [
|
||||
{
|
||||
|
|
@ -1344,10 +1344,10 @@
|
|||
"type": "number",
|
||||
"required": true,
|
||||
"min": 1,
|
||||
"max": 2368
|
||||
"max": 21312
|
||||
}
|
||||
],
|
||||
"effect": "Arrakis only. Guild and Smuggler have separate server prices; Smuggler requires an active Smuggler quest. Native Core checkpoints all surrendered raw Melange Spice before the central bank pays its personal recipient from fixed P&O, with the existing Trust levy. Original request UUID binds quote, inventory receipt and balanced bank entries. Retry and reconnect recover an unpaid receipt without taking spice or paying twice. No Vault wallet or Exchange listing.",
|
||||
"effect": "Arrakis only. Guild and Smuggler have separate server prices; Smuggler requires an active Smuggler quest. Native Core checkpoints all surrendered raw Melange Spice and compressed blocks (nine raw units each), retaining Guild versus contraband identity before the central bank pays its personal recipient from fixed P&O, with the existing Trust levy. Original request UUID binds quote, inventory receipt and balanced bank entries. Retry and reconnect recover an unpaid receipt without taking spice or paying twice. No Vault wallet or Exchange listing.",
|
||||
"fixedTargets": [],
|
||||
"webIssue": false,
|
||||
"recordOnly": true
|
||||
|
|
|
|||
|
|
@ -52,7 +52,9 @@ export function createGameSpiceAPI(db,bank,pool,settings,{pol,clock=Date.now,ver
|
|||
return json(await bank.transaction(async tx=>{
|
||||
const sale=await tx.first('SELECT * FROM pb_spice_sales WHERE id=? FOR UPDATE',[input.requestId]);if(!sale||sale.actor_id!==user.id||sale.player_uuid!==input.uuid)throw Error('Spice receipt unavailable.');
|
||||
const quote=spiceQuote(sale.channel,Number(sale.quantity));
|
||||
const receipt=await tx.first('SELECT * FROM `'+schema+'`.dune_exchange_inventory_ops WHERE id=? FOR UPDATE',[sale.id]);
|
||||
// Native receipts are append-only; the sale and bank-order locks serialize payment.
|
||||
// Do not require write/locking privileges on the game's inventory evidence.
|
||||
const receipt=await tx.first('SELECT id,actor_uuid,kind,fingerprint,listing_id,created_at FROM `'+schema+'`.dune_exchange_inventory_ops WHERE id=?',[sale.id]);
|
||||
if(!receipt||receipt.actor_uuid!==input.uuid||receipt.kind!=='spice-'+sale.channel||Number(receipt.listing_id)!==quote.amount||receipt.fingerprint!==sale.fingerprint||Number(receipt.created_at)<Number(sale.created_at)-5000||Number(receipt.created_at)>Number(sale.expires_at))throw Error('Spice has not been surrendered to the inventory checkpoint.');
|
||||
const previous=await tx.first('SELECT * FROM pb_orders WHERE id=? FOR UPDATE',[sale.id]);
|
||||
if(previous){if(previous.state!=='posted'||previous.actor_id!==user.id||previous.fingerprint!==sale.fingerprint||BigInt(previous.amount_minor)!==BigInt(quote.netMinor))throw Error('Spice payment requires review.');return {ok:true,replayed:true,...quote};}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
// Run with the existing production environment. Emits SQL only; no password.
|
||||
import{openDatabase}from'../node/mysql.mjs';import{openPostbankDatabase}from'../node/postbank-db.mjs';import{openGameMysqlPool}from'../node/game-mysql-pool.mjs';
|
||||
const env=process.env,db=await openDatabase(env),bank=await openPostbankDatabase(env),pool=await openGameMysqlPool(env.DUNE_INVENTORY_DATABASE_URL);
|
||||
try{const sql='SELECT @@hostname host,@@port port,@@server_id server_id';const[c,b,g]=await Promise.all([db.query(sql),bank.first(sql),pool.query(sql)]);if(['host','port','server_id'].some(k=>String(c[0][k])!==String(b[k])||String(c[0][k])!==String(g.rows[0][k])))throw Error('One transaction server required');const schema=env.DB_NAME,game=new URL(env.DUNE_INVENTORY_DATABASE_URL).pathname.slice(1),identity=(await bank.first('SELECT CURRENT_USER() identity')).identity.split('@');if(![schema,game].every(s=>/^[a-z][a-z0-9_]{2,63}$/.test(s))||identity.length!==2||!identity.every(s=>/^[a-zA-Z0-9_.%:-]+$/.test(s)))throw Error('Unexpected database identity');const account="'"+identity[0]+"'@'"+identity[1]+"'";for(const table of['jarvis_kitset_listings','jarvis_kitset_versions','organisation_keys'])process.stdout.write('GRANT SELECT ON `'+schema+'`.`'+table+'` TO '+account+';\n');process.stdout.write('GRANT SELECT,INSERT ON `'+schema+'`.`organisation_key_events` TO '+account+';\n');process.stdout.write('GRANT SELECT (id,actor_uuid,kind) ON `'+game+'`.`dune_exchange_inventory_ops` TO '+account+';\n');}finally{await Promise.allSettled([db.close(),bank?.close(),pool.end()]);}
|
||||
try{const sql='SELECT @@hostname host,@@port port,@@server_id server_id';const[c,b,g]=await Promise.all([db.query(sql),bank.first(sql),pool.query(sql)]);if(['host','port','server_id'].some(k=>String(c[0][k])!==String(b[k])||String(c[0][k])!==String(g.rows[0][k])))throw Error('One transaction server required');const schema=env.DB_NAME,game=new URL(env.DUNE_INVENTORY_DATABASE_URL).pathname.slice(1),identity=(await bank.first('SELECT CURRENT_USER() identity')).identity.split('@');if(![schema,game].every(s=>/^[a-z][a-z0-9_]{2,63}$/.test(s))||identity.length!==2||!identity.every(s=>/^[a-zA-Z0-9_.%:-]+$/.test(s)))throw Error('Unexpected database identity');const account="'"+identity[0]+"'@'"+identity[1]+"'";for(const table of['jarvis_kitset_listings','jarvis_kitset_versions','organisation_keys'])process.stdout.write('GRANT SELECT ON `'+schema+'`.`'+table+'` TO '+account+';\n');process.stdout.write('GRANT SELECT,INSERT ON `'+schema+'`.`organisation_key_events` TO '+account+';\n');process.stdout.write('GRANT SELECT (id,actor_uuid,kind,fingerprint,listing_id,created_at) ON `'+game+'`.`dune_exchange_inventory_ops` TO '+account+';\n');}finally{await Promise.allSettled([db.close(),bank?.close(),pool.end()]);}
|
||||
|
|
|
|||
|
|
@ -1,20 +1,22 @@
|
|||
import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto';
|
||||
import {BankFixture} from './postbank-fixture.mjs';import {PostbankService} from '../node/postbank-service.mjs';import {BANK_VERSION} from '../node/postbank-catalogue.mjs';
|
||||
import {createGameSpiceAPI,spiceFingerprint,spiceQuote,activeSmugglerQuest} from '../node/game-spice.mjs';
|
||||
async function fixture(){
|
||||
async function fixture({readOnlyReceipts=false}={}){
|
||||
const bank=new BankFixture(),user={id:randomUUID(),username:'Miner'},uuid=randomUUID(),entity={id:randomUUID(),kind:'person',key:user.id,name:user.username};let active=false,now=100000;
|
||||
await new PostbankService(bank,async()=>({entities:[{...entity,canView:true,canActivate:true,canPay:true}]})).activate(user,{entityId:entity.id,packageKey:'pb_flow',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});
|
||||
const target=await bank.first("SELECT * FROM pb_accounts WHERE type_code='102'");
|
||||
for(const key of ['sys_payroll_po','sys_tax_treasury'])await bank.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,state,created_at) VALUES(?,'979',?,0,'active',1)",[key,key]);
|
||||
bank.sqlite.exec("ATTACH DATABASE ':memory:' AS game;CREATE TABLE game.dune_exchange_inventory_ops(id TEXT PRIMARY KEY,actor_uuid TEXT,kind TEXT,fingerprint TEXT,listing_id INT,created_at INT);CREATE TABLE pb_spice_sales(id TEXT PRIMARY KEY,actor_id TEXT,player_uuid TEXT,channel TEXT,quantity INT,fingerprint TEXT,created_at INT,expires_at INT);");
|
||||
const db={query:async(sql,args)=>args[0]===uuid?[user]:[]},secret='spice-api-test-secret-123456789012345';
|
||||
const api=createGameSpiceAPI(db,bank,null,{GAME_LINK_SECRET:secret},{verifyStorage:async()=> 'game',clock:()=>now,pol:{quests:{list:async()=>({quests:[{id:'POL-SMUGGLERS-02',branch:'smugglers',state:active?'active':'claimed'}]})}}});
|
||||
const receiptReader={query:bank.query.bind(bank),first:bank.first.bind(bank),transaction:work=>bank.transaction(tx=>work({...tx,first(sql,args){if(sql.includes('dune_exchange_inventory_ops')&&/FOR\s+(UPDATE|SHARE)|LOCK\s+IN/i.test(sql))throw Error('Inventory receipts are read-only');return tx.first(sql,args);}}))};
|
||||
const api=createGameSpiceAPI(db,readOnlyReceipts?receiptReader:bank,null,{GAME_LINK_SECRET:secret},{verifyStorage:async()=> 'game',clock:()=>now,pol:{quests:{list:async()=>({quests:[{id:'POL-SMUGGLERS-02',branch:'smugglers',state:active?'active':'claimed'}]})}}});
|
||||
const call=async(input,token=secret)=>{const response=await api(new Request('https://cp.dunerealms.com/internal/game/spice',{method:'POST',headers:{authorization:'Bearer '+token,'content-type':'application/json'},body:JSON.stringify({uuid,server:'arrakis',...input})}));return {status:response.status,body:await response.json()};};
|
||||
const prepare=(channel='guild')=>({action:'prepare',requestId:randomUUID(),channel,amount:64,confirmed:true});
|
||||
async function receipt(input){await bank.query('INSERT INTO game.dune_exchange_inventory_ops VALUES(?,?,?,?,?,?)',[input.requestId,uuid,'spice-'+input.channel,spiceFingerprint(uuid,input.channel,input.amount),input.amount,now+100]);}
|
||||
return {bank,user,uuid,target,call,prepare,receipt,active:()=>{active=true;},expire:()=>{now+=60000;}};
|
||||
}
|
||||
test('quotes are bounded and Smuggler access requires an actually active quest',()=>{assert.throws(()=>spiceQuote('guild',0));assert.throws(()=>spiceQuote('guild',21313));assert.throws(()=>spiceQuote('exchange',1));assert.notEqual(spiceQuote('guild',64).netMinor,spiceQuote('smuggler',64).netMinor);assert.equal(activeSmugglerQuest({quests:[{branch:'smugglers',state:'available'}]}),false);assert.equal(activeSmugglerQuest({quests:[{branch:'smugglers',state:'claimed'}]}),false);assert.equal(activeSmugglerQuest({quests:[{branch:'smugglers',state:'active'}]}),true);});
|
||||
test('an expired committed sale settles once with read-only inventory access',async()=>{const f=await fixture({readOnlyReceipts:true});try{const input=f.prepare();assert.equal((await f.call(input)).status,200);await f.receipt(input);f.expire();assert.equal((await f.call({action:'settle',requestId:input.requestId})).status,200);assert.equal((await f.call({action:'settle',requestId:input.requestId})).body.replayed,true);assert.equal(Number((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n),2);}finally{f.bank.close();}});
|
||||
test('Arrakis-only and authenticated; locked Smuggler cannot prepare and quotes do not pay',async()=>{const f=await fixture();try{assert.equal((await f.call({action:'read'},'bad')).status,401);assert.equal((await f.call({action:'read',server:'caladan'})).status,400);assert.equal((await f.call(f.prepare('smuggler'))).status,403);f.active();assert.equal((await f.call(f.prepare('smuggler'))).status,200);assert.equal((await f.bank.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,0);}finally{f.bank.close();}});
|
||||
test('only a committed exact inventory receipt pays; retry posts once with balanced P&O and tax entries',async()=>{const f=await fixture();try{const input=f.prepare();assert.equal((await f.call(input)).status,200);assert.equal((await f.call({action:'settle',requestId:input.requestId})).status,409);await f.receipt(input);const paid=await f.call({action:'settle',requestId:input.requestId});assert.equal(paid.status,200,JSON.stringify(paid.body));assert.equal((await f.call({action:'settle',requestId:input.requestId})).body.replayed,true);assert.equal(Number((await f.bank.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor),spiceQuote('guild',64).netMinor);assert.equal(Number((await f.bank.first('SELECT SUM(amount_minor) n FROM pb_entries')).n),0);assert.equal(Number((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n),2);}finally{f.bank.close();}});
|
||||
test('recoverable receipt remains payable after quote expiry; forged quantity or actor earns nothing',async()=>{const f=await fixture();try{const input=f.prepare();await f.call(input);await f.receipt(input);f.expire();assert.deepEqual((await f.call({action:'pending'})).body.pending,[input.requestId]);assert.equal((await f.call({action:'settle',requestId:input.requestId,uuid:randomUUID()})).status,403);await f.bank.query('UPDATE game.dune_exchange_inventory_ops SET listing_id=65');assert.equal((await f.call({action:'settle',requestId:input.requestId})).status,409);await f.bank.query('UPDATE game.dune_exchange_inventory_ops SET listing_id=64');assert.equal((await f.call({action:'settle',requestId:input.requestId})).status,200);}finally{f.bank.close();}});
|
||||
|
|
|
|||
Loading…
Reference in a new issue

Staff