Merge pull request 'Add ESK event records and bank estate freeze / Unlock' (#428) from feature/entity-state-key-20261120 into main
All checks were successful
DuneRealms Web CI / web (push) Successful in 2m19s

This commit is contained in:
unimatrix 2026-11-20 18:21:47 +00:00
commit fcbe87c6c3
19 changed files with 447 additions and 12 deletions

View file

@ -0,0 +1,32 @@
# Entity State Keys — backend batch
Owner scope: ESK keys and website/backend consumers only. No Minecraft event producer,
plugin deployment, ban migration or succession-rule changes are included.
- Existing organisation key policy registers `entity-state` / ESK as a system record.
- `createEntityStateKeys` requires explicit event/read/evidence authority adapters.
There is no public arbitrary-event issuance endpoint. Future verified services use
`record(actor, payload)`; bank routes cannot fabricate death evidence.
- Typed dossiers cover player/mob death, respawn, ban and unban. Event IDs are unique
per verified source. A changed replay is rejected. References and scalar attributes
carry verified mission/contract/deed facts, not executable code or a replacement
inventory. Current inventory remains in its existing store.
- Independent consumer receipts permit one event to support multiple legitimate
quests/deeds/contracts. The same consumer/reference executes once in the central
transaction. Recording an ESK does not itself pay a reward or transfer ownership.
- The existing JARVIS management page has an Entity state tab, without secret codes.
- The existing bank Operations Dashboard gains an ESK estates tab. Bank managers can
apply an existing verified player lore-death key and Unlock it with a reason and
current revision. Ordinary in-game deaths and mob deaths cannot freeze accounts.
- The bank uses its existing `blocked` account state and existing audit. ESK estate
metadata records only affected previously active personal accounts. Existing
collateral/closed/dormant restrictions are not removed. Unlock rejects changed
account/package states. Balances and reservations are never edited.
- Bank state and its audit commit together. Deterministic bank receipts make retry
safe if the central evidence-receipt commit fails after the bank commit. The death
event remains unchanged; the bank-specific effect advances frozen -> unlocked.
- Production event creation and real freezes are not tests. Only isolated fixtures
are used in this batch. The approved icon is `website/web/assets/esk-key-v1.png`.
Related owner XP ticket: DR_DEV-000009H / support ticket 412. Full XP/POL work stays
open; this foundation does not claim completed quests, live NPC links or game events.

View file

@ -1,6 +1,6 @@
// Shared syntax only: a readable edition is never proof of ownership or authority.
const legacy=/^(ACC-TEST|CLAN-ADM|PRJ|PRG|NEWS|XPC|XPX|ECO-SNAP|STAFF-LINK|STAFF-COM|STAFF-POL|XFR|CLAN-SUB|COM-SUB|POL-CLAN|QST|QSM|CLAN|COM|POL)-([A-F0-9]{48})$/;
const versioned=/^(ACC-TEST|CLAN-ADM|PRJ|PRG|NEWS|XPC|XPX|ECO-SNAP|STAFF-LINK|STAFF-COM|STAFF-POL|XFR|CLAN-SUB|COM-SUB|POL-CLAN|QST|QSM|CLAN|COM|POL)-(ALPHA|BETA|LIVE)-((?:0|[1-9]\d{0,2})(?:\.(?:0|[1-9]\d{0,2})){3})-(S\d{2,4})-([A-F0-9]{8}(?:-[A-F0-9]{8}){5})$/;
const legacy=/^(ESK|ACC-TEST|CLAN-ADM|PRJ|PRG|NEWS|XPC|XPX|ECO-SNAP|STAFF-LINK|STAFF-COM|STAFF-POL|XFR|CLAN-SUB|COM-SUB|POL-CLAN|QST|QSM|CLAN|COM|POL)-([A-F0-9]{48})$/;
const versioned=/^(ESK|ACC-TEST|CLAN-ADM|PRJ|PRG|NEWS|XPC|XPX|ECO-SNAP|STAFF-LINK|STAFF-COM|STAFF-POL|XFR|CLAN-SUB|COM-SUB|POL-CLAN|QST|QSM|CLAN|COM|POL)-(ALPHA|BETA|LIVE)-((?:0|[1-9]\d{0,2})(?:\.(?:0|[1-9]\d{0,2})){3})-(S\d{2,4})-([A-F0-9]{8}(?:-[A-F0-9]{8}){5})$/;
export function parseOrganisationCode(value){
if(typeof value!=='string'||value.length>128)throw new TypeError('Invalid organisation code');
const code=value.trim().toUpperCase(),old=code.match(legacy);

View file

@ -29,5 +29,6 @@ export function mountCodexManagement(host,{initial='keys',fetcher=fetch}={}){
const seasons=box('Seasons & signing keys','Each season or isolated test run has its own signing-key version. Existing deeds and historical items retain their origin.');seasons.append(table(['Policy','Behaviour'],[['Origin','Season, Alpha/Beta/Live stage, release version and issue date stay attached to the instance.'],['Historical originals','Staff regeneration creates a new current-version instance; it never relabels the historical original.'],['Quality','Common, Uncommon, Rare, Very Rare and Legendary describe quality independently from edition age and actual scarcity.'],['Carry-over','Deeds persist. Unused older-season keys and rare items remain valid and transferable when their type permits.'],['Key rotation','New issues use the active signing key; historical signatures remain verifiable.'],['Test isolation','Test-run instances belong to their own namespace and cannot be redeemed in production.'],['Duplicate protection','Validate on use, redemption or transfer; atomic processing accepts an instance only once.']]),locked('Rotate active signing key'),locked('Create isolated test run'));groups.push({id:'seasons',title:'Seasons',content:seasons});
const progression=box('Missions, decisions & progression','Design catalogue · definitions are not executable yet.'),progressionHost=make('div');progression.append(progressionHost);disposers.push(mountProgressionDesign(progressionHost,{manage:true,context:'politics'}));groups.push({id:'progression',title:'Missions & decisions',content:progression});
const validator=box('Check a key','Read-only inspection. Checking never activates or consumes a key.'),checkForm=make('form'),checkInput=make('input'),checkButton=make('button','Check key'),checkResult=make('div');checkInput.type='password';checkInput.autocomplete='off';checkInput.maxLength=300;checkInput.required=true;checkInput.setAttribute('aria-label','Private key to validate');checkButton.type='submit';checkForm.append(checkInput,checkButton);validator.classList.add('codex-header-validator');validator.append(checkForm);hero.append(validator);checkResult.className='codex-header-validation-result';checkResult.setAttribute('role','status');hero.after(checkResult);checkForm.onsubmit=async event=>{event.preventDefault();if(checkButton.disabled)return;checkButton.disabled=true;try{const r=await fetcher('/api/jarvis/validate',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify({code:checkInput.value,staff:true})}),data=await r.json();if(!r.ok)throw Error(data.message||'Validation unavailable');if(data.state==='invalid')showInvalidKey(checkResult,'Key rejected. Dev support: '+(data.ticketNumber||data.caseId||'pending'));else checkResult.textContent=data.valid?'Recognised · '+data.state+' · no key consumed.':'This key type cannot be checked by the connected service.';}catch(e){checkResult.textContent=e.message;}finally{checkInput.value='';checkButton.disabled=false;}};
const registers=new Map();for(const [tab,section] of [['keys','keys'],['keys','deeds'],['listings','listings'],['history','history'],['delivery','delivery'],['seasons','seasons']]){const register=createJarvisRegister(section,{fetcher}),group=groups.find(g=>g.id===tab);if(['listings','history','delivery'].includes(tab))group.content.querySelector('.codex-table-scroll')?.remove();if(tab==='history')group.content.querySelector('.codex-field')?.remove();if(tab==='delivery'){const filter=group.content.querySelector('select');if(filter)filter.disabled=true;}const frame=box(section==='deeds'?'Office deeds':'Live '+section+' register');frame.classList.add('codex-register-frame');frame.append(register.root);group.content.append(frame);if(!registers.has(tab))registers.set(tab,[]);registers.get(tab).push(register);disposers.push(register.dispose);}const tabs=organisationTabs(groups,{label:'J.A.R.V.I.S. Management sections',initial});tabs.addEventListener('organisation-tab-change',event=>{for(const item of registers.get(event.detail.id)||[])item.load();});root.append(tabs);for(const item of registers.get(initial)||[])item.load();host.replaceChildren(root);return()=>{mounted=false;for(const dispose of disposers)if(typeof dispose==='function')dispose();root.remove();};
const states=box('Entity State Keys','Verified entity events. One ESK can support independent quests, contracts and deed actions; recording an event never grants a reward or changes ownership by itself.');const stateArt=image('esk-key-v1.png');stateArt.width=stateArt.height=64;stateArt.style.objectFit='contain';states.prepend(stateArt);groups.push({id:'states',title:'Entity state',content:states});
const registers=new Map();for(const [tab,section] of [['states','states'],['keys','keys'],['keys','deeds'],['listings','listings'],['history','history'],['delivery','delivery'],['seasons','seasons']]){const register=createJarvisRegister(section,{fetcher}),group=groups.find(g=>g.id===tab);if(['listings','history','delivery'].includes(tab))group.content.querySelector('.codex-table-scroll')?.remove();if(tab==='history')group.content.querySelector('.codex-field')?.remove();if(tab==='delivery'){const filter=group.content.querySelector('select');if(filter)filter.disabled=true;}const frame=box(section==='deeds'?'Office deeds':'Live '+section+' register');frame.classList.add('codex-register-frame');frame.append(register.root);group.content.append(frame);if(!registers.has(tab))registers.set(tab,[]);registers.get(tab).push(register);disposers.push(register.dispose);}const tabs=organisationTabs(groups,{label:'J.A.R.V.I.S. Management sections',initial});tabs.addEventListener('organisation-tab-change',event=>{for(const item of registers.get(event.detail.id)||[])item.load();});root.append(tabs);for(const item of registers.get(initial)||[])item.load();host.replaceChildren(root);return()=>{mounted=false;for(const dispose of disposers)if(typeof dispose==='function')dispose();root.remove();};
}

View file

@ -1,14 +1,14 @@
import {createUserAPI} from './cp-v2-user-api.mjs';
const el=(tag,text)=>{const node=document.createElement(tag);if(text!==undefined)node.textContent=text;return node;};
const date=value=>value?new Date(Number(value)).toLocaleString('en-GB'):'—';
const columns={keys:[['Reference','id'],['Type','type'],['Family','family'],['Operation','operation'],['Recipient','recipient'],['Issued','created_at'],['State',row=>row.revoked_at?'Revoked':row.used_at?'Used':row.expires_at&&Number(row.expires_at)<=Date.now()?'Expired':'Available']],deeds:[['Reference','id'],['Office','type'],['Holder','holder'],['Starts','starts_at'],['Expires','expires_at'],['State','state']],listings:[['Listing','title'],['Type','type'],['Organisation','owner'],['State','state'],['Created','created_at']],delivery:[['Listing','listing'],['Channel','channel'],['State','state'],['Attempts','attempts'],['Next attempt','next_attempt']],history:[['Time','created_at'],['Instrument','instrument'],['Action','action'],['Account','actor'],['Target','target_id']]};
const columns={states:[['Reference','id'],['Action','action'],['Entity UUID','target_id'],['Scope','scope'],['Recorded','occurred_at'],['Event data','details']],keys:[['Reference','id'],['Type','type'],['Family','family'],['Operation','operation'],['Recipient','recipient'],['Issued','created_at'],['State',row=>row.revoked_at?'Revoked':row.used_at?'Used':row.expires_at&&Number(row.expires_at)<=Date.now()?'Expired':'Available']],deeds:[['Reference','id'],['Office','type'],['Holder','holder'],['Starts','starts_at'],['Expires','expires_at'],['State','state']],listings:[['Listing','title'],['Type','type'],['Organisation','owner'],['State','state'],['Created','created_at']],delivery:[['Listing','listing'],['Channel','channel'],['State','state'],['Attempts','attempts'],['Next attempt','next_attempt']],history:[['Time','created_at'],['Instrument','instrument'],['Action','action'],['Account','actor'],['Target','target_id']]};
export function createJarvisRegister(section,{fetcher=fetch}={}){
const controller=new AbortController(),api=createUserAPI(fetcher,controller.signal),root=el('section'),status=el('p'),records=el('div'),nav=el('nav');root.className='codex-live-register';status.setAttribute('role','status');let active=true,loaded=false,busy=false,page=1;
const previous=el('button','← Previous'),next=el('button','Next →'),refresh=el('button','Refresh'),pageLabel=el('span');for(const button of [previous,next,refresh])button.type='button';nav.append(previous,pageLabel,next,refresh);root.append(status,records,nav);
async function load(){if(!active||busy)return;loaded=true;busy=true;previous.disabled=next.disabled=refresh.disabled=true;status.textContent='Opening the J.A.R.V.I.S. register…';try{
const data=await api.request('/api/jarvis/management?section='+encodeURIComponent(section)+'&page='+page);if(!active)return;records.replaceChildren();
if(section==='seasons'){records.append(el('p',data.edition.stage+' · '+data.edition.version+' · '+data.edition.season));previous.hidden=next.hidden=pageLabel.hidden=true;}
else{const wrap=el('div'),table=el('table'),head=el('thead'),headers=el('tr'),body=el('tbody');wrap.className='codex-table-scroll';for(const [title]of columns[section]){const th=el('th',title);th.scope='col';headers.append(th);}head.append(headers);for(const row of data.records){const tr=el('tr');for(const [,key]of columns[section]){const value=typeof key==='function'?key(row):key.endsWith('_at')||key==='next_attempt'?date(row[key]):row[key];const cell=el('td');if((key==='id'||key==='target_id')&&typeof value==='string'&&value){const button=el('button');const icon=el('span','🔑');icon.setAttribute('aria-hidden','true');button.append(icon);button.type='button';button.className='jarvis-copy-reference';button.title='Copy ID';button.setAttribute('aria-label','Copy '+section+' reference');button.onclick=()=>navigator.clipboard.writeText(value).then(()=>{if(active)status.textContent='Reference copied.';}).catch(()=>{if(active)status.textContent='The reference could not be copied. Check clipboard access.';});cell.append(button);}else cell.textContent=value===null||value===undefined?'—':String(value);tr.append(cell);}body.append(tr);}table.append(head,body);wrap.append(table);records.append(wrap);if(!data.records.length)records.append(el('p','No records in this register.'));pageLabel.textContent='Page '+page;previous.disabled=page<=1;next.disabled=!data.hasMore;}
else{const wrap=el('div'),table=el('table'),head=el('thead'),headers=el('tr'),body=el('tbody');wrap.className='codex-table-scroll';for(const [title]of columns[section]){const th=el('th',title);th.scope='col';headers.append(th);}head.append(headers);for(const row of data.records){const tr=el('tr');for(const [,key]of columns[section]){const value=typeof key==='function'?key(row):key.endsWith('_at')||key==='next_attempt'?date(row[key]):row[key];const cell=el('td');if((key==='id'||key==='target_id')&&typeof value==='string'&&value){const button=el('button');const icon=el('span','🔑');icon.setAttribute('aria-hidden','true');button.append(icon);button.type='button';button.className='jarvis-copy-reference';button.title='Copy ID';button.setAttribute('aria-label','Copy '+section+' reference');button.onclick=()=>navigator.clipboard.writeText(value).then(()=>{if(active)status.textContent='Reference copied.';}).catch(()=>{if(active)status.textContent='The reference could not be copied. Check clipboard access.';});cell.append(button);}else if(value&&typeof value==='object'){const details=el('details');details.append(el('summary','Event fields'));const pre=el('pre',JSON.stringify(value,null,2));pre.style.cssText='white-space:pre-wrap;overflow-wrap:anywhere;max-width:420px;font-size:11px';details.append(pre);cell.append(details);}else cell.textContent=value===null||value===undefined?'—':String(value);tr.append(cell);}body.append(tr);}table.append(head,body);wrap.append(table);records.append(wrap);if(!data.records.length)records.append(el('p','No records in this register.'));pageLabel.textContent='Page '+page;previous.disabled=page<=1;next.disabled=!data.hasMore;}
status.textContent='Live register · private codes and signing material are not displayed.';
}catch(error){if(active){records.replaceChildren();status.textContent=error.message;}}finally{busy=false;if(active)refresh.disabled=false;}}
previous.onclick=()=>{if(page>1){page--;void load();}};next.onclick=()=>{page++;void load();};refresh.onclick=()=>void load();

View file

@ -1,3 +1,4 @@
import {renderEstates} from './cp-v2-postbank-estates.mjs';
import {renderPayroll} from './cp-v2-postbank-payroll.mjs';
import {renderServiceCompensation} from './cp-v2-postbank-compensation.mjs';
import {renderClientManagement} from './cp-v2-postbank-client.mjs';
@ -15,8 +16,8 @@ export function mountPostbankAdmin(host,id,{fetcher=fetch}={}){
const message=text=>{frame.status.hidden=false;frame.status.textContent=text;};
async function load(){if(busy)return;busy=true;frame.reloadButton.disabled=true;message('Loading bank administration…');try{
const stats=await api.request('/api/bank/admin/overview');if(!active)return;frame.content.replaceChildren();canCompensate=!!stats.permissions.canCompensate;
if(id==='bank-dashboard'){const metrics=el('div',undefined,'pb-admin-metrics');for(const [name,value]of [['Clients',stats.clients],['Accounts',stats.accounts],['Customer balances',stats.balances+' DM'],['Pending payments',stats.pendingPayments]]){const card=el('section');card.append(el('small',name),el('strong',String(value)));metrics.append(card);}frame.content.append(metrics);if(stats.permissions.canRunScheduler){const run=el('button','Run due scheduled tasks');run.type='button';run.onclick=async()=>{if(busy||!confirm('Check every bank ticker now, including loans, standing instructions, payroll and statements? Payment due dates remain unchanged.'))return;busy=true;run.disabled=true;try{const result=await api.request('/api/bank/admin/scheduler/run',{confirmed:true});message('Scheduler finished: '+result.tasks.filter(t=>t.state==='completed').length+' completed · '+result.tasks.filter(t=>t.state==='retry_pending').length+' need attention. Every bank ticker was checked, including loans. Tickers already running were skipped.');}catch(e){message(e.message);}finally{busy=false;if(active)run.disabled=false;}};frame.content.append(run,el('p','Rechecks every bank ticker: transfers and loans, credit support, standing instructions, monthly payroll, tariff publications and statements. Transfers and loan repayments keep their scheduled settlement dates.','pb-muted'));}const nav=el('nav',undefined,'pb-admin-tabs');for(const [key,label]of [['clients','Clients & Accounts'],['pending','Payment Control'],...(stats.permissions.canRunScheduler?[['payroll','P&O Payroll']]:[]),...(canCompensate?[['compensation','Service Compensation']]:[])]){const button=el('button',label);button.type='button';button.setAttribute('aria-pressed',String(mode===key));button.onclick=()=>{mode=key;page=1;query='';kind='';void load();};nav.append(button);}frame.content.append(nav);}
if(mode==='payroll'){const pane=el('section');frame.content.append(pane);await renderPayroll(pane,{api,isActive:()=>active&&mode==='payroll'});frame.status.hidden=true;return;}if(mode==='compensation'){const pane=el('section');frame.content.append(pane);await renderServiceCompensation(pane,{api,original:selectedPayment,canManage:stats.permissions.canManage,isActive:()=>active&&mode==='compensation'});frame.status.hidden=true;return;}const tools=el('form',undefined,'pb-admin-tools'),search=el('input');search.type='search';search.value=query;search.placeholder=mode==='audit'?'Action or entity name':'Name or client number';search.maxLength=80;const type=el('select');selectOption(type,'All entity types','');for(const value of mode==='corporate'?['clan','company']:['person','clan','company','house','office','staff'])selectOption(type,human(value),value);type.value=kind;const apply=el('button','Search');apply.type='submit';
if(id==='bank-dashboard'){const metrics=el('div',undefined,'pb-admin-metrics');for(const [name,value]of [['Clients',stats.clients],['Accounts',stats.accounts],['Customer balances',stats.balances+' DM'],['Pending payments',stats.pendingPayments]]){const card=el('section');card.append(el('small',name),el('strong',String(value)));metrics.append(card);}frame.content.append(metrics);if(stats.permissions.canRunScheduler){const run=el('button','Run due scheduled tasks');run.type='button';run.onclick=async()=>{if(busy||!confirm('Check every bank ticker now, including loans, standing instructions, payroll and statements? Payment due dates remain unchanged.'))return;busy=true;run.disabled=true;try{const result=await api.request('/api/bank/admin/scheduler/run',{confirmed:true});message('Scheduler finished: '+result.tasks.filter(t=>t.state==='completed').length+' completed · '+result.tasks.filter(t=>t.state==='retry_pending').length+' need attention. Every bank ticker was checked, including loans. Tickers already running were skipped.');}catch(e){message(e.message);}finally{busy=false;if(active)run.disabled=false;}};frame.content.append(run,el('p','Rechecks every bank ticker: transfers and loans, credit support, standing instructions, monthly payroll, tariff publications and statements. Transfers and loan repayments keep their scheduled settlement dates.','pb-muted'));}const nav=el('nav',undefined,'pb-admin-tabs');for(const [key,label]of [['clients','Clients & Accounts'],['pending','Payment Control'],['estates','ESK estates'],...(stats.permissions.canRunScheduler?[['payroll','P&O Payroll']]:[]),...(canCompensate?[['compensation','Service Compensation']]:[])]){const button=el('button',label);button.type='button';button.setAttribute('aria-pressed',String(mode===key));button.onclick=()=>{mode=key;page=1;query='';kind='';void load();};nav.append(button);}frame.content.append(nav);}
if(mode==='estates'){const pane=el('section');frame.content.append(pane);await renderEstates(pane,{api,isActive:()=>active&&mode==='estates'});frame.status.hidden=true;return;}if(mode==='payroll'){const pane=el('section');frame.content.append(pane);await renderPayroll(pane,{api,isActive:()=>active&&mode==='payroll'});frame.status.hidden=true;return;}if(mode==='compensation'){const pane=el('section');frame.content.append(pane);await renderServiceCompensation(pane,{api,original:selectedPayment,canManage:stats.permissions.canManage,isActive:()=>active&&mode==='compensation'});frame.status.hidden=true;return;}const tools=el('form',undefined,'pb-admin-tools'),search=el('input');search.type='search';search.value=query;search.placeholder=mode==='audit'?'Action or entity name':'Name or client number';search.maxLength=80;const type=el('select');selectOption(type,'All entity types','');for(const value of mode==='corporate'?['clan','company']:['person','clan','company','house','office','staff'])selectOption(type,human(value),value);type.value=kind;const apply=el('button','Search');apply.type='submit';
if(mode!=='pending'){tools.append(field('Search',search));if(!['audit','treasuries'].includes(mode))tools.append(field('Entity type',type));tools.append(apply);tools.onsubmit=e=>{e.preventDefault();query=search.value;kind=type.value;page=1;void load();};frame.content.append(tools);}
const endpoint=mode==='treasuries'?'treasuries':mode==='pending'?'pending':mode==='audit'?'audit':mode==='corporate'?'corporate':'entities',data=await api.request('/api/bank/admin/'+endpoint+'?page='+page+(query?'&q='+encodeURIComponent(query):'')+(kind?'&kind='+encodeURIComponent(kind):''));if(!active)return;
if(mode==='pending'){renderPending(data);renderPendingCredit(data.creditRecords||[]);}else if(!data.records.length)frame.content.append(el('p',mode==='pending'?'No standard payments are awaiting settlement.':mode==='corporate'?'No matching business entities. Companies appear only after registration; no example companies are created.':'No matching bank records.'));

View file

@ -0,0 +1,15 @@
import {element as el} from './cp-v2-page-template.mjs';
export async function renderEstates(host,{api,isActive}){
const data=await api.request('/api/bank/admin/estates');if(!isActive())return;
host.append(el('h3','ESK estate restrictions'),el('p','A verified lore-death ESK can restrict existing personal bank accounts. Unlock restores only the accounts restricted by that ESK; it does not erase the death record.','pb-muted'));
const status=el('p');status.setAttribute('role','status');host.append(status);
const field=(form,title,type='text')=>{const label=el('label',title,'pb-transfer-field'),input=el('input');input.type=type;input.required=true;label.append(input);form.append(label);return input;};
const apply=async(button,path,input)=>{button.disabled=true;try{const result=await api.request(path,input);if(isActive())status.textContent='ESK bank state: '+(result.result?.state||'updated')+'. Reload this tab to see the current record.';}catch(error){if(isActive())status.textContent=error.message;button.disabled=false;}};
if(data.canManage){const form=el('form',undefined,'pb-admin-tools'),key=field(form,'Lore-death ESK reference'),reason=field(form,'Freeze reason');reason.minLength=5;reason.maxLength=500;const confirm=field(form,'Confirm the estate restriction','checkbox'),button=el('button','Apply ESK freeze');button.type='submit';form.append(button);form.onsubmit=e=>{e.preventDefault();if(form.reportValidity())void apply(button,'/api/bank/admin/estates/freeze',{keyId:key.value.trim(),reason:reason.value.trim(),confirmed:confirm.checked});};host.append(form);}
const wrap=el('div',undefined,'pb-ledger-scroll'),table=el('table',undefined,'pb-ledger'),head=el('thead'),header=el('tr'),body=el('tbody');for(const title of ['Client','ESK','Bank state','Action'])header.append(el('th',title));head.append(header);
for(const row of data.records){const tr=el('tr'),name=el('td',row.name),reference=el('td'),details=el('details');details.append(el('summary','ESK reference'),el('code',row.keyId));reference.append(details);const state=el('td',row.state==='frozen'?'Frozen by ESK':'Unlocked'),action=el('td');
if(data.canManage&&row.state==='frozen'){const open=el('button','Unlock');open.type='button';const form=el('form');form.hidden=true;const reason=field(form,'Unlock reason');reason.minLength=5;reason.maxLength=500;const confirmed=field(form,'Confirm unlock','checkbox'),submit=el('button','Confirm unlock');submit.type='submit';form.append(submit);open.onclick=()=>{form.hidden=!form.hidden;open.setAttribute('aria-expanded',String(!form.hidden));};const requestId=crypto.randomUUID();form.onsubmit=e=>{e.preventDefault();if(form.reportValidity())void apply(submit,'/api/bank/admin/estates/unlock',{keyId:row.keyId,revision:row.revision,requestId,reason:reason.value.trim(),confirmed:confirmed.checked});};action.append(open,form);}
tr.append(name,reference,state,action);body.append(tr);
}
table.append(head,body);wrap.append(table);host.append(wrap);if(!data.records.length)host.append(el('p','No ESK estate restrictions recorded.'));
}

View file

@ -21,6 +21,7 @@ export const MASTER_KEY_TEMPLATES=[
action('relations.parent','Protected parent relation','staff-parent-link',[field('childId','Child organisation'),field('parentId','Mother organisation'),reference]),
action('relations.transfer','Entity transfer','entity-transfer',[field('entityId','Organisation'),field('recipient','New controller'),reference])]},
{id:'economy',label:'Economy',actions:[action('economy.snapshot','Sealed economic snapshot','economy-snapshot',[field('snapshotId','Verified snapshot'),reference],{recordOnly:true})]},
{id:'state',label:'Entity state',actions:[action('state.estate-freeze','Freeze estate from lore-death ESK','entity-state',[field('keyId','Verified lore-death ESK'),reference],{domainAdapter:'PostbankEstates.freeze',executionStatus:'bank-staff-consumer',effect:'Restrict existing personal accounts using a verified lore-death ESK; no balance changes.'}),action('state.estate-unlock','Unlock ESK estate','entity-state',[field('keyId','Existing ESK'),field('revision','Current bank effect revision','number',{min:1}),reference],{domainAdapter:'PostbankEstates.unlock',executionStatus:'bank-staff-consumer',effect:'Bank staff restore only the accounts held by the named ESK. Original death evidence remains unchanged.'}),action('state.record','Entity State Key','entity-state',[field('eventId','Unique source event ID'),field('action','State event'),field('targetUuid','Target entity UUID'),field('targetKind','Player or mob'),field('entityType','Entity type'),field('actorUuid','Killer / actor UUID','text',{required:false}),field('cause','Cause / reason'),field('scope','Server / lore scope'),field('world','World'),field('occurredAt','Event timestamp','number',{min:0}),reference],{recordOnly:true,domainAdapter:'entityStateKeys',executionStatus:'verified-service-record',artwork:'esk-key-v1.png',effect:'Record a verified death, respawn, ban or unban. Shared quest/contract/deed evidence with separate once-only consumer receipts. No Minecraft producer or ban migration in this batch.'})]},
{id:'progression',label:'Progression & XP',actions:[
action('xp.correct','Approved XP correction','xp-correction',[field('recipient','Recipient'),field('amountXP','XP amount','number',{min:1}),field('caseReference','Approved support case')]),
action('xp.transfer','Season XP transfer','xp-transfer',[field('recipient','Recipient'),field('fromSeason','Source season'),field('toSeason','Target season')]),

View file

@ -1,3 +1,4 @@
import {initializeEntityState} from '../node/entity-state-keys.mjs';
import {createDMPaint} from './dmpaint.mjs';
import {initializePassiveOrders} from '../node/political-passive-orders.mjs';
import {createMasterKeyGeneratorAPI} from '../node/jarvis-master-generator-api.mjs';
@ -234,7 +235,7 @@ export function createPanel(db,settings={},dependencies={}){
const managedTransfers=createManagedTransfers(db,settings,dependencies.managedTransfers);
const bankTransfers=createBankTransfers(db,settings,dependencies.bankTransfers);
const banking=createBanking(db,settings,dependencies.banking);
const postbank=createPostbankApi(db,dependencies.bankDatabase||null,settings,dependencies.postbank);
const postbank=createPostbankApi(db,dependencies.bankDatabase||null,settings,{...dependencies.postbank,organisationKeys:dependencies.organisationKeys});
const bankClient=createBankClientApi(db,dependencies.bankClient);
const v1PersonalBank=createV1PersonalBank(banking,{enabled:process.env.DUNE_API_V1_BANK_STAGING==='true'});
const quests=createQuests(db,settings,dependencies.quests),clanShop=createClanShop(db,settings,dependencies.clanShop);
@ -440,7 +441,7 @@ export async function startPanel(settings=process.env){
inventoryPool.on('error',()=>console.error('Inventory database connection unavailable.'));
}
const bankDatabase=await openPostbankDatabase(settings);
const db=await openDatabase(settings);await db.query(ECONOMIC_SNAPSHOT_SCHEMA);await initializeCodexEquipment(db);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await db.prepare(CHARACTER_PREFERENCE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await db.prepare(CHARACTER_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await applyRoyalClanRollout(db);const organisationKeys=await openOrganisationKeyService(db,settings);await ensurePoliticalOfficeCharters(db,organisationKeys);const keyGrants=await grantCurrentAccountKeys(db,organisationKeys);console.log('Original founding key grants reconciled',JSON.stringify(keyGrants));await resetOwnerTestClaims(db,bankDatabase);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeLifeStatus(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await initializePassiveOrders(db);await initializeJarvisGenerator(db);await applyUnicorpRoyalMailbox(db,organisationKeys,{apply:true}).catch(error=>console.error('Unicorp Royal mailbox rollout pending:',error.message));await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;await ensureJarvisIdentity(db);await db.query(VALIDATION_CASE_SCHEMA);await reconcileCrysknifeCompany(db,organisationKeys); /* Passive POL conversion waits for scoped adapters instead of company management. */await provisionRihlaAccounts(db,bankDatabase);await initializeOfficeAuctionRuntime(db,bankDatabase);for(const sql of [...POLITICAL_JOB_SCHEMA,...NAIB_COUNCIL_SCHEMA])await db.query(sql);db.naibCouncilEnabled=true;await initializeProgression(db);await initializeServerProjects(db);if(bankDatabase)await bankDatabase.query(PROJECT_BANK_SCHEMA);await db.query(GAZETTE_SCHEMA);await ensureProgressionPolicy(db,organisationKeys);const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const handle=createPanel(db,settings,{inventoryPool,bankDatabase,organisationKeys,officeAuctionRuntime,promotionDelivery,progressionRuntime}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com';
const db=await openDatabase(settings);await db.query(ECONOMIC_SNAPSHOT_SCHEMA);await initializeCodexEquipment(db);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await db.prepare(CHARACTER_PREFERENCE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await db.prepare(CHARACTER_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await applyRoyalClanRollout(db);const organisationKeys=await openOrganisationKeyService(db,settings);await ensurePoliticalOfficeCharters(db,organisationKeys);const keyGrants=await grantCurrentAccountKeys(db,organisationKeys);console.log('Original founding key grants reconciled',JSON.stringify(keyGrants));await resetOwnerTestClaims(db,bankDatabase);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeLifeStatus(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await initializePassiveOrders(db);await initializeJarvisGenerator(db);await initializeEntityState(db);await applyUnicorpRoyalMailbox(db,organisationKeys,{apply:true}).catch(error=>console.error('Unicorp Royal mailbox rollout pending:',error.message));await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;await ensureJarvisIdentity(db);await db.query(VALIDATION_CASE_SCHEMA);await reconcileCrysknifeCompany(db,organisationKeys); /* Passive POL conversion waits for scoped adapters instead of company management. */await provisionRihlaAccounts(db,bankDatabase);await initializeOfficeAuctionRuntime(db,bankDatabase);for(const sql of [...POLITICAL_JOB_SCHEMA,...NAIB_COUNCIL_SCHEMA])await db.query(sql);db.naibCouncilEnabled=true;await initializeProgression(db);await initializeServerProjects(db);if(bankDatabase)await bankDatabase.query(PROJECT_BANK_SCHEMA);await db.query(GAZETTE_SCHEMA);await ensureProgressionPolicy(db,organisationKeys);const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const handle=createPanel(db,settings,{inventoryPool,bankDatabase,organisationKeys,officeAuctionRuntime,promotionDelivery,progressionRuntime}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com';
await initializeInternalMailAccess(db);const stopElectionClock=startElectionClock(db);const stopOfficeLedger=startOfficeLedger(db);
const stopBanSync=startModerationSync(db,settings),stopInternalMail=startInternalMailSync(db,{jarvisStore:bankDatabase}),stopCentralScheduler=startCentralScheduler(db,bankDatabase,settings,{extraTasks:bankDatabase?[{key:'server_projects',slot:now=>Math.floor(now/60000)*60000,run:()=>createServerProjectRuntime(db,bankDatabase,organisationKeys).drain()},{key:'progression_completion',slot:now=>Math.floor(now/60000)*60000,run:async()=>{const completed=await progressionRuntime.quests.processCompletions();const news=await progressionRuntime.announcements.drain();return {completed,news};}},{key:'naib_council',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await reconcileNaibChairs(db);return createNaibCouncil(db).reconcile();}},{key:'jarvis_promotions',slot:now=>Math.floor(now/15000)*15000,run:()=>promotionDelivery.drain()},{key:'political_jobs',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await createPoliticalJobs(db,bankDatabase).reconcile();return drainPoliticalJobNotifications(db,{broker:internalMailBroker,eligible:internalMailEligible});}},{key:'order_membership',slot:now=>Math.floor(now/60000)*60000,run:()=>reconcileCrysknifeCompany(db,organisationKeys)},{key:'office_auctions',slot:now=>Math.floor(now/60000)*60000,run:()=>officeAuctionRuntime.process()},{key:'jarvis_settlement',slot:now=>standardCycle(now).cutoff,async run(cutoff){const payments=createJarvisPayments(bankDatabase,createPostbankAuthority(db,{bank:bankDatabase}));for(let i=0;i<40;i++){const result=await payments.settle(cutoff);if(result.failed)return result;if(result.attempted<100)return result;}return {failed:1};}}]:[]});
const security={'X-Robots-Tag':'noindex, nofollow, noarchive','X-Content-Type-Options':'nosniff','Referrer-Policy':'no-referrer','Cache-Control':'no-store','Content-Security-Policy':"default-src 'self'; script-src 'self' https://www.dunerealms.com; style-src 'self' https://www.dunerealms.com https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; connect-src 'self' https://www.dunerealms.com; img-src 'self' data: https://www.dunerealms.com https://support.dunerealms.com; frame-src 'self' https://luckperms.net https://www.dunerealms.com https://support.dunerealms.com https://forums.dunerealms.com https://clans.dunerealms.com https://corp.dunerealms.com https://wiki.dunerealms.com; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'self' https://www.dunerealms.com https://dunerealms.com https://clans.dunerealms.com"};

View file

@ -1,6 +1,6 @@
{
"schemaVersion": 1,
"sourceHash": "d7c582ae87d5bb36de2621ad0ba757613cc6caf87a479bbae6ba8d5ec13e1062",
"sourceHash": "22f083da2e3c92ec81993866e764b3dd97021d34b2877dea70d92e877913910c",
"actions": [
{
"id": "clan.clear-protected-rosters",
@ -405,6 +405,161 @@
"webIssue": false,
"recordOnly": true
},
{
"id": "state.estate-freeze",
"label": "Entity state · Freeze estate from lore-death ESK",
"version": 1,
"keyType": "entity-state",
"fields": [
{
"name": "ticketId",
"label": "Ban / support ticket ID",
"type": "text",
"required": true,
"maxLength": 80
},
{
"name": "keyId",
"label": "Verified lore-death ESK",
"type": "text",
"required": true
},
{
"name": "reference",
"label": "Reason / decision reference",
"type": "text",
"required": false
}
],
"effect": "Restrict existing personal accounts using a verified lore-death ESK; no balance changes.",
"fixedTargets": [],
"webIssue": false,
"recordOnly": false
},
{
"id": "state.estate-unlock",
"label": "Entity state · Unlock ESK estate",
"version": 1,
"keyType": "entity-state",
"fields": [
{
"name": "ticketId",
"label": "Ban / support ticket ID",
"type": "text",
"required": true,
"maxLength": 80
},
{
"name": "keyId",
"label": "Existing ESK",
"type": "text",
"required": true
},
{
"name": "revision",
"label": "Current bank effect revision",
"type": "number",
"required": true,
"min": 1
},
{
"name": "reference",
"label": "Reason / decision reference",
"type": "text",
"required": false
}
],
"effect": "Bank staff restore only the accounts held by the named ESK. Original death evidence remains unchanged.",
"fixedTargets": [],
"webIssue": false,
"recordOnly": false
},
{
"id": "state.record",
"label": "Entity state · Entity State Key",
"version": 1,
"keyType": "entity-state",
"fields": [
{
"name": "ticketId",
"label": "Ban / support ticket ID",
"type": "text",
"required": true,
"maxLength": 80
},
{
"name": "eventId",
"label": "Unique source event ID",
"type": "text",
"required": true
},
{
"name": "action",
"label": "State event",
"type": "text",
"required": true
},
{
"name": "targetUuid",
"label": "Target entity UUID",
"type": "text",
"required": true
},
{
"name": "targetKind",
"label": "Player or mob",
"type": "text",
"required": true
},
{
"name": "entityType",
"label": "Entity type",
"type": "text",
"required": true
},
{
"name": "actorUuid",
"label": "Killer / actor UUID",
"type": "text",
"required": false
},
{
"name": "cause",
"label": "Cause / reason",
"type": "text",
"required": true
},
{
"name": "scope",
"label": "Server / lore scope",
"type": "text",
"required": true
},
{
"name": "world",
"label": "World",
"type": "text",
"required": true
},
{
"name": "occurredAt",
"label": "Event timestamp",
"type": "number",
"required": true,
"min": 0
},
{
"name": "reference",
"label": "Reason / decision reference",
"type": "text",
"required": false
}
],
"effect": "Record a verified death, respawn, ban or unban. Shared quest/contract/deed evidence with separate once-only consumer receipts. No Minecraft producer or ban migration in this batch.",
"fixedTargets": [],
"webIssue": false,
"recordOnly": true
},
{
"id": "xp.correct",
"label": "Progression & XP · Approved XP correction",

View file

@ -0,0 +1,85 @@
import {createHash,randomUUID} from 'node:crypto';
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
const hash=v=>createHash('sha256').update(JSON.stringify(v)).digest('hex');
const fail=message=>{throw Object.assign(new Error(message),{status:409});};
const text=(v,max)=>typeof v==='string'&&v.length>0&&v.length<=max&&!/[\x00-\x1f\x7f]/.test(v);
export const ENTITY_STATE_SCHEMA=Object.freeze([
`CREATE TABLE IF NOT EXISTS jarvis_entity_state_events(key_id CHAR(36) PRIMARY KEY,source VARCHAR(32) NOT NULL,event_id CHAR(36) NOT NULL,issuer_id CHAR(36) NOT NULL,target_uuid CHAR(36) NOT NULL,action VARCHAR(16) NOT NULL,scope VARCHAR(64) NOT NULL,occurred_at BIGINT NOT NULL,fingerprint CHAR(64) NOT NULL,payload_json TEXT NOT NULL,created_at BIGINT NOT NULL,UNIQUE KEY esk_source_event(source,event_id),INDEX esk_target(target_uuid,scope,occurred_at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
`CREATE TABLE IF NOT EXISTS jarvis_entity_state_receipts(key_id CHAR(36) NOT NULL,consumer VARCHAR(64) NOT NULL,reference_id VARCHAR(96) NOT NULL,actor_id CHAR(36) NOT NULL,fingerprint CHAR(64) NOT NULL,result_json TEXT NOT NULL,created_at BIGINT NOT NULL,PRIMARY KEY(key_id,consumer,reference_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`
]);
export async function initializeEntityState(db){for(const sql of ENTITY_STATE_SCHEMA)await db.query(sql);}
export function validateEntityState(input,{now=Date.now()}={}){
const allowed=['eventId','source','action','targetUuid','targetKind','entityType','actorUuid','cause','scope','world','occurredAt','expiresAt','previousKeyId','references','attributes'];
if(!input||typeof input!=='object'||Array.isArray(input)||Object.keys(input).some(k=>!allowed.includes(k)))throw TypeError('Invalid entity state fields');
if(!uuid(input.eventId)||!uuid(input.targetUuid)||!text(input.source,32)||!/^[a-z0-9_-]+$/.test(input.source)||!['death','respawn','ban','unban'].includes(input.action)||!['player','mob'].includes(input.targetKind)||!text(input.entityType,64)||!/^[a-z0-9_:]+$/.test(input.entityType)||!text(input.cause,160)||!text(input.scope,64)||!text(input.world,96)||!Number.isSafeInteger(input.occurredAt)||input.occurredAt<0||input.occurredAt>now+60000)throw TypeError('Invalid entity state event');
if(input.targetKind==='player'&&input.entityType!=='minecraft:player'||input.targetKind==='mob'&&['ban','unban'].includes(input.action))throw TypeError('Invalid entity state target');
const actorUuid=input.actorUuid??null,expiresAt=input.expiresAt??null,previousKeyId=input.previousKeyId??null;
if(actorUuid!==null&&!uuid(actorUuid)||previousKeyId!==null&&!uuid(previousKeyId)||expiresAt!==null&&(input.action!=='ban'||!Number.isSafeInteger(expiresAt)||expiresAt<=input.occurredAt))throw TypeError('Invalid entity state timing or identity');
const references={},attributes={};
for(const [name,value]of Object.entries(input.references||{})){if(!['questId','missionId','contractId','deedId','deedVersion','ticketId'].includes(name)||!(typeof value==='string'&&text(value,96)||name==='deedVersion'&&Number.isSafeInteger(value)&&value>0))throw TypeError('Invalid entity state reference');references[name]=value;}
if(input.references!==undefined&&(!input.references||typeof input.references!=='object'||Array.isArray(input.references)))throw TypeError('Invalid entity state references');
if(input.attributes!==undefined&&(!input.attributes||typeof input.attributes!=='object'||Array.isArray(input.attributes)||Object.keys(input.attributes).length>24))throw TypeError('Invalid entity state attributes');
for(const name of Object.keys(input.attributes||{}).sort()){const value=input.attributes[name];if(!/^[a-z][a-zA-Z0-9]{0,39}$/.test(name)||!['string','boolean','number'].includes(typeof value)||typeof value==='string'&&!text(value,160)||typeof value==='number'&&!Number.isSafeInteger(value))throw TypeError('Invalid entity state attribute');attributes[name]=value;}
const sorted=Object.fromEntries(Object.entries(references).sort(([a],[b])=>a.localeCompare(b)));
return {version:1,eventId:input.eventId.toLowerCase(),source:input.source,action:input.action,targetUuid:input.targetUuid.toLowerCase(),targetKind:input.targetKind,entityType:input.entityType,actorUuid:actorUuid?.toLowerCase()||null,cause:input.cause,scope:input.scope,world:input.world,occurredAt:input.occurredAt,expiresAt,previousKeyId:previousKeyId?.toLowerCase()||null,references:sorted,attributes};
}
export function entityStateMatches(event,conditions){
const direct=['action','targetUuid','targetKind','entityType','actorUuid','cause','scope','world'];
if(Object.keys(conditions).some(k=>![...direct,'references','attributes','occurredAfter','occurredBefore'].includes(k)))throw TypeError('Invalid entity state conditions');
for(const [field,value]of Object.entries(conditions)){
if(field==='references'||field==='attributes'){if(!value||typeof value!=='object'||Array.isArray(value))throw TypeError('Invalid entity state conditions');if(Object.entries(value).some(([k,v])=>event[field]?.[k]!==v))return false;}
else if(field==='occurredAfter'||field==='occurredBefore'){if(!Number.isSafeInteger(value))throw TypeError('Invalid entity state condition time');if(field==='occurredAfter'?event.occurredAt<value:event.occurredAt>value)return false;}
else if(event[field]!==value)return false;
}
return true;
}
// The existing organisation key is the instrument. This table is its typed event
// dossier; consumers keep independent receipts instead of globally consuming it.
export function createEntityStateKeys(db,keys,{authorizeEvent,authorizeRead,authorizeEvidence,clock=Date.now}={}){
if(![authorizeEvent,authorizeRead,authorizeEvidence].every(f=>typeof f==='function'))throw TypeError('Entity state authority adapters required');
const first=async(store,sql,args=[])=>store.first?store.first(sql,args):(await store.query(sql,args))[0]||null;
const read=async(store,keyId)=>{
if(!uuid(keyId))throw TypeError('Choose an entity state key');
const row=await first(store,"SELECT e.*,k.scope_id,k.key_type,k.account_id,k.revoked_at FROM jarvis_entity_state_events e JOIN organisation_keys k ON k.id=e.key_id WHERE e.key_id=?",[keyId]);
if(!row||row.key_type!=='entity-state'||row.account_id!==STAFF_OFFICE_ACCOUNT_ID||row.revoked_at!==null)fail('Entity state evidence is unavailable');
const payload=JSON.parse(row.payload_json);
if(hash(payload)!==row.fingerprint||row.scope_id!=='state:'+payload.source+':'+payload.eventId||row.target_uuid!==payload.targetUuid||row.action!==payload.action)fail('Entity state evidence changed');
return {keyId:row.key_id,issuerId:row.issuer_id,...payload};
};
return Object.freeze({
async record(actor,input){
const payload=validateEntityState(input,{now:clock()});
if(!uuid(actor?.id)||await authorizeEvent(actor,payload,db)!==true)fail('Verified entity state issuer required');
const fingerprint=hash(payload);
const grant=await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'entity-state',scopeId:'state:'+payload.source+':'+payload.eventId,authorize:async(tx,{keyId})=>{
if(await authorizeEvent(actor,payload,tx)!==true)fail('Entity state issuer authority changed');
if(payload.previousKeyId){const previous=await read(tx,payload.previousKeyId);if(previous.targetUuid!==payload.targetUuid||previous.scope!==payload.scope||previous.occurredAt>payload.occurredAt)fail('Entity state predecessor does not match');if(payload.action==='unban'&&previous.action!=='ban'||payload.action==='respawn'&&previous.action!=='death')fail('Entity state transition does not match');}
const prior=await first(tx,'SELECT key_id,fingerprint,issuer_id FROM jarvis_entity_state_events WHERE source=? AND event_id=? FOR UPDATE',[payload.source,payload.eventId]);
if(prior){if(prior.fingerprint!==fingerprint||prior.issuer_id!==actor.id)fail('Entity state event reference conflict');return;}
await tx.query('INSERT INTO jarvis_entity_state_events(key_id,source,event_id,issuer_id,target_uuid,action,scope,occurred_at,fingerprint,payload_json,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?)',[keyId,payload.source,payload.eventId,actor.id,payload.targetUuid,payload.action,payload.scope,payload.occurredAt,fingerprint,JSON.stringify(payload),clock()]);
}});
const record=await read(db,grant.id);if(hash((({keyId,issuerId,...p})=>p)(record))!==fingerprint||record.issuerId!==actor.id)fail('Entity state event reference conflict');
return {keyId:grant.id,created:grant.created};
},
async get(actor,keyId){const event=await read(db,keyId);if(await authorizeRead(actor,event,db)!==true)fail('Entity state read authority required');return event;},
async useEvidence(actor,{keyId,consumer,referenceId,conditions,intent=null},apply){
if(!uuid(actor?.id)||!text(consumer,64)||!/^[a-z][a-z0-9_.-]+$/.test(consumer)||!text(referenceId,96)||typeof apply!=='function'||!conditions||typeof conditions!=='object'||Array.isArray(conditions)||!Object.keys(conditions).length)throw TypeError('Scoped entity state consumer required');
entityStateMatches({},conditions);
if(intent!==null&&!text(intent,1000))throw TypeError('Invalid entity state consumer intent');
const fingerprint=hash({conditions:Object.fromEntries(Object.entries(conditions).sort(([a],[b])=>a.localeCompare(b))),intent});
return db.transaction(async tx=>{
const event=await read(tx,keyId);
if(await authorizeEvidence(actor,{event,consumer,referenceId,conditions},tx)!==true)fail('Entity state consumer authority required');
if(!entityStateMatches(event,conditions))fail('Entity state evidence does not satisfy the objective');
// Lock the instrument to serialize consumers; the key remains reusable by
// DIFFERENT quest/contract/deed references, never twice by the same one.
const key=await first(tx,'SELECT id,revoked_at FROM organisation_keys WHERE id=? FOR UPDATE',[keyId]);if(!key||key.revoked_at!==null)fail('Entity state evidence is unavailable');
const prior=await first(tx,'SELECT actor_id,fingerprint,result_json FROM jarvis_entity_state_receipts WHERE key_id=? AND consumer=? AND reference_id=?',[keyId,consumer,referenceId]);
if(prior){if(prior.actor_id!==actor.id||prior.fingerprint!==fingerprint)fail('Entity state receipt reference conflict');return {replayed:true,result:JSON.parse(prior.result_json)};}
const result=await apply(tx,event);
await tx.query('INSERT INTO jarvis_entity_state_receipts(key_id,consumer,reference_id,actor_id,fingerprint,result_json,created_at) VALUES(?,?,?,?,?,?,?)',[keyId,consumer,referenceId,actor.id,fingerprint,JSON.stringify(result??null),clock()]);return {replayed:false,result:result??null};
});
}
});
}

View file

@ -4,6 +4,7 @@ import {KEY_TYPES} from './organisation-key-policy.mjs';
import {currentCodexEdition} from './organisation-key-service.mjs';
const reply=(body,status=200)=>Response.json(body,{status,headers:{'Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}});
const SECTIONS={
states:{store:'central',sql:'SELECT e.key_id AS id,e.action,e.target_uuid AS target_id,e.source,e.scope,e.occurred_at,e.payload_json,k.revoked_at FROM jarvis_entity_state_events e JOIN organisation_keys k ON k.id=e.key_id ORDER BY e.occurred_at DESC,e.key_id DESC'},
keys:{store:'central',sql:'SELECT k.id,k.key_type AS type,a.username AS recipient,k.created_at,k.expires_at,k.used_at,k.revoked_at FROM organisation_keys k LEFT JOIN site_accounts a ON a.id=k.account_id ORDER BY k.created_at DESC,k.id DESC'},
history:{store:'central',sql:'SELECT e.id,e.key_id AS instrument,e.event_type AS action,a.username AS actor,e.target_id,e.created_at FROM organisation_key_events e LEFT JOIN site_accounts a ON a.id=e.account_id ORDER BY e.created_at DESC,e.id DESC'},
listings:{store:'bank',sql:'SELECT id,title,definition_id AS type,organisation_name AS owner,state,created_at FROM jarvis_listings ORDER BY created_at DESC,id DESC'},
@ -25,7 +26,7 @@ export function createJarvisManagement(central,bank,settings={},deps={}){
const db=definition.store==='central'?central:bank;if(!db)return reply({message:'Register temporarily unavailable.'},503);
try{
const args=[26,(page-1)*25],sql=definition.sql+' LIMIT ? OFFSET ?',rows=definition.store==='central'?(await db.prepare(sql).bind(...args).all()).results:await db.query(sql,args);
const records=rows.slice(0,25).map(row=>section==='keys'?{...row,family:KEY_TYPES[row.type]?.family||'unclassified',operation:KEY_TYPES[row.type]?.operation||'restricted',playerRedeemable:KEY_TYPES[row.type]?.playerRedeemable===true}:row);
const records=rows.slice(0,25).map(row=>section==='keys'?{...row,family:KEY_TYPES[row.type]?.family||'unclassified',operation:KEY_TYPES[row.type]?.operation||'restricted',playerRedeemable:KEY_TYPES[row.type]?.playerRedeemable===true}:section==='states'?(({payload_json,...metadata})=>({...metadata,details:JSON.parse(payload_json)}))(row):row);
return reply({section,page,hasMore:rows.length>25,records});
}catch(error){if(/doesn't exist|no such table|unknown column/i.test(error.message||''))return reply({message:'This register is not installed yet.'},503);throw error;}
};

View file

@ -13,6 +13,7 @@ export const KEY_TYPES=Object.freeze({
'economy-snapshot':system('ECO-SNAP','immutable-economic-record','record'),
'staff-parent-link':system('STAFF-LINK','protected-parent-link'),
'entity-transfer':system('XFR','entity-transfer'),
'entity-state':system('ESK','entity-state-event','record'),
'quest':system('QST','persistent-quest'),
'quest-milestone':system('QSM','progression-milestone','record'),
'staff-office-royal':system('STAFF-POL','protected-office-royal'),

View file

@ -46,6 +46,7 @@ export function createOrganisationKeys(db,{secret,editions=null}={}){
if(keyType==='clan-administration'&&(typeof authorize!=='function'||!/^protected-roster:[a-f0-9-]{36}$/i.test(scopeId)||expiresAt===null))throw TypeError('Clan administration requires a bound dossier and authority adapter');
if(keyType==='project-action'&&(expiresAt!==null||typeof authorize!=='function'||!/^project:[a-f0-9-]{36}:[a-f0-9-]{36}$/i.test(scopeId)))throw new TypeError('Projects require a domain authority adapter');
if(keyType==='progression-policy'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||typeof authorize!=='function'||!/^policy:S\d{2,4}:v[1-9]\d{0,5}$/.test(scopeId)))throw new TypeError('Progression policies require the system configuration adapter');
if(keyType==='entity-state'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||typeof authorize!=='function'||!/^state:[a-z0-9_-]{1,32}:[a-f0-9-]{36}$/i.test(scopeId)))throw TypeError('Entity state requires a verified system event adapter');
if(keyType==='gazette-news'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||typeof authorize!=='function'||!/^news:[a-f0-9-]{36}:v[1-9]\d{0,5}$/i.test(scopeId)))throw new TypeError('Gazette instruments require a confirmed system publication adapter');
if(['xp-correction','xp-transfer'].includes(keyType)&&(expiresAt!==null||typeof authorize!=='function'))throw new TypeError('XP instruments require a domain authority adapter');
if(keyType==='economy-snapshot'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||!/^snapshot:[a-f0-9-]{36}$/i.test(scopeId)||typeof authorize!=='function'))throw new TypeError('Economic snapshots require a system record and authority adapter');
@ -63,6 +64,7 @@ export function createOrganisationKeys(db,{secret,editions=null}={}){
if(['clan-administration','account-test-identity'].includes(keyType))await authorize(tx,{accountId,keyType,scopeId,keyId:id});
if(keyType==='project-action')await authorize(tx,{accountId,keyType,scopeId,keyId:id});
if(keyType==='progression-policy')await authorize(tx,{accountId,keyType,scopeId,keyId:id});
if(keyType==='entity-state')await authorize(tx,{accountId,keyType,scopeId,keyId:id});
if(keyType==='gazette-news')await authorize(tx,{accountId,keyType,scopeId,keyId:id});
if(['xp-correction','xp-transfer'].includes(keyType))await authorize(tx,{accountId,keyType,scopeId,keyId:id});
if(keyType==='economy-snapshot')await authorize(tx,{accountId,keyType,scopeId,keyId:id});

View file

@ -1,3 +1,5 @@
import {createEntityStateKeys} from './entity-state-keys.mjs';
import {PostbankEstates} from './postbank-estates.mjs';
import {createEconomyHistory} from './jarvis-economy-public.mjs';
import {canInspectAllBankAccounts} from './postbank-recipient-policy.mjs';
import {randomUUID} from 'node:crypto';
@ -35,6 +37,8 @@ export function createPostbankApi(central,bank,settings={},deps={}){
const payrollCycle=bank?new PostbankPayrollCycle(central,bank,deps):null;
const transferSecurity=bank?new PostbankTransferSecurity(bank,central,deps):null;
const admin=bank?new PostbankAdmin(bank,central,authority,deps):null;
const stateKeys=deps.entityStateKeys||(deps.organisationKeys?createEntityStateKeys(central,deps.organisationKeys,{authorizeEvent:async()=>false,authorizeRead:async actor=>!!(await authority(actor)).readAdmin,authorizeEvidence:async actor=>!!(await authority(actor)).manageAdmin}):null);
const estates=bank&&stateKeys?new PostbankEstates(bank,central,stateKeys,authority,deps):null;
const clients=bank?new PostbankClientManagement(bank,authority,deps):null;
const compensation=bank?new PostbankCompensation(bank,authority,deps):null,standing=bank?new PostbankStandingInstructions(bank,authority,deps):null;
const beneficiaries=bank?new PostbankBeneficiaries(bank,{...deps,canInspectAll:deps.canInspectAll||(user=>canInspectAllBankAccounts(central,user))}):null;
@ -187,6 +191,19 @@ export function createPostbankApi(central,bank,settings={},deps={}){
let input;try{input=JSON.parse(raw);}catch{return reply({message:'Complete the client management form.'},400);}
return reply(await clients.change(user,input,path.endsWith('/package')?'package':'options',{revalidate:()=>auth(request)}));
}
if(['/api/bank/admin/estates','/api/bank/admin/estates/freeze','/api/bank/admin/estates/unlock'].includes(path)){
if(!estates)return reply({message:'The ESK estate adapter is unavailable.'},503);
if(url.search)return reply({message:'Account overrides are not accepted.'},400);
const fresh=await auth(request);if(fresh?.id!==user.id)return reply({message:'Your session changed.'},403);
if(path==='/api/bank/admin/estates')return request.method==='GET'?reply(await estates.list(fresh)):reply({message:'Method not allowed.'},405);
if(request.method!=='POST')return reply({message:'Method not allowed.'},405);
if(request.headers.get('origin')!==origin)return reply({message:'Origin rejected.'},403);
if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415);
const raw=await request.text();if(raw.length>2000)return reply({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return reply({message:'Complete the ESK estate form.'},400);}
const allowed=path.endsWith('/unlock')?['keyId','revision','requestId','reason','confirmed']:['keyId','reason','confirmed'];
if(!input||Array.isArray(input)||Object.keys(input).some(k=>!allowed.includes(k)))return reply({message:'Review the ESK estate fields.'},400);
return reply(await (path.endsWith('/unlock')?estates.unlock(fresh,input):estates.freeze(fresh,input)));
}
if(['/api/bank/admin/transfers/cancel','/api/bank/admin/treasuries/transfer','/api/bank/admin/reserve/grants','/api/bank/admin/taxes/payments'].includes(path)){
if(request.method!=='POST')return reply({message:'Method not allowed.'},405);
if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403);

View file

@ -1,3 +1,4 @@
import {ESTATE_SCHEMA} from './postbank-estates.mjs';
import {PROMOTION_DELIVERY_SCHEMA} from './jarvis-promotions.mjs';
import {POLITICAL_JOB_BANK_SCHEMA} from './political-jobs.mjs';
import {EVENT_SCHEMA} from './jarvis-events.mjs';
@ -18,7 +19,7 @@ export async function openPostbankDatabase(settings){
const pool=mysql.createPool({host:settings.BANK_DB_HOST||'127.0.0.1',port:Number(settings.BANK_DB_PORT||3306),database:name,user:settings.BANK_DB_USER,password:settings.BANK_DB_PASSWORD,connectionLimit:4,supportBigNumbers:true,bigNumberStrings:true,charset:'utf8mb4',connectTimeout:8000});
const api=c=>({async query(sql,args=[]){return(await c.execute(sql,args))[0];},async first(sql,args=[]){return(await c.execute(sql,args))[0][0]||null;}});
const db={async query(sql,args=[]){return(await pool.execute(sql,args))[0];},async first(sql,args=[]){return(await pool.execute(sql,args))[0][0]||null;},async transaction(work){const c=await pool.getConnection();try{await c.beginTransaction();const result=await work(api(c));await c.commit();return result;}catch(error){await c.rollback();throw error;}finally{c.release();}},async close(){await pool.end();}};
try{for(const sql of(await readFile(new URL('./postbank-schema.sql',import.meta.url),'utf8')).split(';').map(s=>s.trim()).filter(Boolean))await db.query(sql);for(const sql of [...CLAIM_PRODUCT_SCHEMA,CLAIM_RESET_SCHEMA])await db.query(sql+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');await db.query(NETWORTH_SCHEMA);for(const sql of [...RIHLA_SCHEMA,...EVENT_SCHEMA,...CAMPAIGN_SCHEMA])await db.query(sql);await initializeJarvisListings(db);await db.query(PROMOTION_DELIVERY_SCHEMA);for(const sql of POLITICAL_JOB_BANK_SCHEMA)await db.query(sql);await db.query(JARVIS_CHARGE_SCHEMA);await ensureClaimBatchColumns(db);await ensureCreditColumns(db);await ensurePostbankIndexes(db);}catch(error){await pool.end();throw error;}
try{for(const sql of(await readFile(new URL('./postbank-schema.sql',import.meta.url),'utf8')).split(';').map(s=>s.trim()).filter(Boolean))await db.query(sql);for(const sql of [...CLAIM_PRODUCT_SCHEMA,CLAIM_RESET_SCHEMA])await db.query(sql+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');await db.query(NETWORTH_SCHEMA);for(const sql of [...RIHLA_SCHEMA,...EVENT_SCHEMA,...CAMPAIGN_SCHEMA])await db.query(sql);await initializeJarvisListings(db);await db.query(ESTATE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');await db.query(PROMOTION_DELIVERY_SCHEMA);for(const sql of POLITICAL_JOB_BANK_SCHEMA)await db.query(sql);await db.query(JARVIS_CHARGE_SCHEMA);await ensureClaimBatchColumns(db);await ensureCreditColumns(db);await ensurePostbankIndexes(db);}catch(error){await pool.end();throw error;}
return db;
}

View file

@ -0,0 +1,46 @@
import {createHash} from 'node:crypto';
import {BankError} from './postbank-service.mjs';
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
const receipt=(key,purpose)=>{const h=createHash('sha256').update('esk:'+key+':'+purpose).digest('hex');return h.slice(0,8)+'-'+h.slice(8,12)+'-5'+h.slice(13,16)+'-8'+h.slice(17,20)+'-'+h.slice(20,32);};
export const ESTATE_SCHEMA=`CREATE TABLE IF NOT EXISTS pb_esk_estates(entity_id CHAR(36) PRIMARY KEY,key_id CHAR(36) NOT NULL UNIQUE,state VARCHAR(16) NOT NULL,revision INT NOT NULL,accounts_json TEXT NOT NULL,frozen_by CHAR(36) NOT NULL,frozen_at BIGINT NOT NULL,unlocked_by CHAR(36) NULL,unlocked_at BIGINT NULL,unlock_reason VARCHAR(500) NULL)`;
export class PostbankEstates{
constructor(bank,central,keys,authority,{clock=Date.now}={}){this.bank=bank;this.central=central;this.keys=keys;this.authority=authority;this.clock=clock;}
async access(actor,manage=false){const rights=await this.authority(actor);if(!rights.readAdmin||manage&&!rights.manageAdmin)throw new BankError('Bank management permission is required.',403);return rights;}
async list(actor){const rights=await this.access(actor);const rows=await this.bank.query("SELECT h.key_id,h.state,h.revision,h.frozen_at,h.unlocked_at,e.display_name,e.kind FROM pb_esk_estates h JOIN pb_entities e ON e.id=h.entity_id ORDER BY h.frozen_at DESC LIMIT 100");return {records:rows.map(r=>({keyId:r.key_id,state:r.state,revision:Number(r.revision),frozenAt:Number(r.frozen_at),unlockedAt:r.unlocked_at===null?null:Number(r.unlocked_at),name:r.display_name})),canManage:!!rights.manageAdmin};}
async freeze(actor,{keyId,confirmed,reason}){
await this.access(actor,true);if(!uuid(keyId)||confirmed!==true||typeof reason!=='string'||reason.trim().length<5||reason.length>500)throw new BankError('Confirm the ESK and freeze reason.');
const event=await this.keys.get(actor,keyId);
if(event.action!=='death'||event.targetKind!=='player'||event.attributes.loreDeath!==true)throw new BankError('A verified player lore-death ESK is required. Ordinary Minecraft deaths do not freeze accounts.',409);
const link=await this.central.prepare('SELECT user_id FROM site_game_links WHERE minecraft_uuid=?').bind(event.targetUuid).first();if(!link)throw new BankError('The ESK target has no linked account.',409);
return this.keys.useEvidence(actor,{keyId,consumer:'bank.estate-freeze',referenceId:keyId,conditions:{action:'death',targetUuid:event.targetUuid},intent:reason.trim()},async()=>{
return this.bank.transaction(async tx=>{
await this.access(actor,true);
const entity=await tx.first("SELECT e.id FROM pb_entities e JOIN pb_clients c ON c.entity_id=e.id WHERE e.kind='person' AND e.external_key=? AND e.active=1 FOR UPDATE",[link.user_id]);if(!entity)throw new BankError('No active personal bank client matches this ESK.',409);
const auditId=receipt(keyId,'freeze'),prior=await tx.first('SELECT details FROM pb_audit WHERE id=?',[auditId]);if(prior)return JSON.parse(prior.details);
const hold=await tx.first('SELECT * FROM pb_esk_estates WHERE entity_id=? FOR UPDATE',[entity.id]);if(hold?.state==='frozen')throw new BankError('This estate is already frozen by another ESK.',409);
const accounts=await tx.query("SELECT a.id,a.state,a.type_code FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number WHERE c.entity_id=? ORDER BY a.id FOR UPDATE",[entity.id]);
const affected=accounts.filter(a=>a.state==='active'&&a.type_code!=='106');if(!affected.length)throw new BankError('No active personal accounts are available to freeze.',409);
for(const a of affected)await tx.query("UPDATE pb_accounts SET state='blocked' WHERE id=? AND state='active'",[a.id]);
const now=this.clock();if(hold)await tx.query("UPDATE pb_esk_estates SET key_id=?,state='frozen',revision=revision+1,accounts_json=?,frozen_by=?,frozen_at=?,unlocked_by=NULL,unlocked_at=NULL,unlock_reason=NULL WHERE entity_id=?",[keyId,JSON.stringify(affected),actor.id,now,entity.id]);
else await tx.query("INSERT INTO pb_esk_estates(entity_id,key_id,state,revision,accounts_json,frozen_by,frozen_at) VALUES(?,?,'frozen',1,?,?,?)",[entity.id,keyId,JSON.stringify(affected),actor.id,now]);
const result={ok:true,keyId,state:'frozen',accounts:affected.length,balancesChanged:false,reason:reason.trim()};
await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[auditId,actor.id,'esk_estate_frozen',entity.id,JSON.stringify(result),now]);return result;
});
});
}
async unlock(actor,{keyId,revision,requestId,reason,confirmed}){
await this.access(actor,true);if(!uuid(keyId)||!uuid(requestId)||confirmed!==true||!Number.isSafeInteger(revision)||revision<1||typeof reason!=='string'||reason.trim().length<5||reason.length>500)throw new BankError('Confirm the ESK, current revision and unlock reason.');
const event=await this.keys.get(actor,keyId);
return this.keys.useEvidence(actor,{keyId,consumer:'bank.estate-unlock',referenceId:requestId,conditions:{action:'death',targetUuid:event.targetUuid},intent:reason.trim()},async()=>this.bank.transaction(async tx=>{
await this.access(actor,true);const hold=await tx.first('SELECT * FROM pb_esk_estates WHERE key_id=? FOR UPDATE',[keyId]);if(!hold)throw new BankError('ESK estate restriction not found.',404);
const auditId=receipt(requestId,'unlock'),prior=await tx.first('SELECT actor_id,details FROM pb_audit WHERE id=?',[auditId]);if(prior){const v=JSON.parse(prior.details);if(prior.actor_id!==actor.id||v.keyId!==keyId||v.reason!==reason.trim())throw new BankError('Unlock request reference conflict.',409);return v;}
if(hold.state!=='frozen'||Number(hold.revision)!==revision)throw new BankError('The estate changed. Reload before unlocking.',409);
const snapshot=JSON.parse(hold.accounts_json);
for(const a of snapshot){const current=await tx.first('SELECT a.state,p.state package_state FROM pb_accounts a LEFT JOIN pb_packages p ON p.id=a.package_id WHERE a.id=? FOR UPDATE',[a.id]);if(!current||current.state!=='blocked'||current.package_state!=='active')throw new BankError('An account restriction or package changed; review it before unlocking.',409);}
for(const a of snapshot)await tx.query('UPDATE pb_accounts SET state=? WHERE id=?',[a.state,a.id]);
const now=this.clock();await tx.query("UPDATE pb_esk_estates SET state='unlocked',revision=revision+1,unlocked_by=?,unlocked_at=?,unlock_reason=? WHERE key_id=? AND revision=?",[actor.id,now,reason.trim(),keyId,revision]);
const result={ok:true,keyId,state:'unlocked',revision:revision+1,accounts:snapshot.length,balancesChanged:false,reason:reason.trim()};
await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[auditId,actor.id,'esk_estate_unlocked',hold.entity_id,JSON.stringify(result),now]);return result;
}));
}
}

View file

@ -0,0 +1,33 @@
import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto';
import {companyFixture} from './company-deed-fixture.mjs';
import {initializeEntityState,createEntityStateKeys,validateEntityState} from '../node/entity-state-keys.mjs';
import {STAFF_OFFICE_ACCOUNT_ID} from '../node/organisation-keys.mjs';
async function fixture(){const f=await companyFixture();await initializeEntityState(f.db);const actor=f.people.Owner;
const service=createEntityStateKeys(f.db,f.keys,{clock:()=>1000,authorizeEvent:async a=>a.id===actor.id,authorizeRead:async a=>a.id===actor.id,authorizeEvidence:async a=>a.id===actor.id});
const event={eventId:randomUUID(),source:'verified-test',action:'death',targetUuid:randomUUID(),targetKind:'player',entityType:'minecraft:player',actorUuid:randomUUID(),cause:'player_attack',scope:'arrakis',world:'arrakis',occurredAt:900,references:{missionId:'assassination-1'},attributes:{loreDeath:true}};
return {...f,actor,service,event};}
test('ESK records one verified event, rejects changed replay and is a non-redeemable system key',async()=>{const f=await fixture();try{
const one=await f.service.record(f.actor,f.event);assert.equal((await f.service.record(f.actor,f.event)).keyId,one.keyId);assert.equal((await f.db.query('SELECT key_id FROM jarvis_entity_state_events')).length,1);
assert.equal((await f.service.get(f.actor,one.keyId)).targetUuid,f.event.targetUuid);
await assert.rejects(f.service.record(f.actor,{...f.event,cause:'lava'}),/conflict/);
await assert.rejects(f.service.record(f.people.Member,{...f.event,eventId:randomUUID()}),/issuer/);
const key=(await f.keys.list(STAFF_OFFICE_ACCOUNT_ID)).find(k=>k.id===one.keyId);assert.ok(key.code.startsWith('ESK-'));
await assert.rejects(f.keys.consume({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'entity-state',code:key.code,targetId:f.actor.id,requestId:randomUUID(),apply:async()=>{throw Error('must not run');}}),/cannot be redeemed/);
}finally{f.db.close();}});
test('one death supports independent quest and deed receipts, once per consumer reference; failed work rolls back',async()=>{const f=await fixture();try{
const {keyId}=await f.service.record(f.actor,f.event);let count=0;const request={keyId,consumer:'quest',referenceId:'quest-1',conditions:{action:'death',targetUuid:f.event.targetUuid}};
assert.equal((await f.service.useEvidence(f.actor,request,async()=>({n:++count}))).replayed,false);
assert.equal((await f.service.useEvidence(f.actor,request,async()=>({n:++count}))).replayed,true);assert.equal(count,1);
await f.service.useEvidence(f.actor,{...request,consumer:'deed',referenceId:'deed-1'},async()=>({n:++count}));assert.equal(count,2);
await assert.rejects(f.service.useEvidence(f.actor,{...request,referenceId:'wrong',conditions:{action:'ban'}},async()=>++count),/objective/);
await assert.rejects(f.service.useEvidence(f.actor,{...request,referenceId:'fails'},async()=>{throw Error('domain failed');}),/domain failed/);
assert.equal((await f.db.query('SELECT * FROM jarvis_entity_state_receipts')).length,2);
}finally{f.db.close();}});
test('mob/environment deaths and linked respawn/unban retain history without inventing a killer',async()=>{const f=await fixture();try{
const death=await f.service.record(f.actor,{...f.event,targetKind:'mob',entityType:'minecraft:zombie',actorUuid:null,cause:'lava'});
const respawn=await f.service.record(f.actor,{...f.event,eventId:randomUUID(),targetKind:'mob',entityType:'minecraft:zombie',actorUuid:null,cause:'respawn',action:'respawn',previousKeyId:death.keyId,occurredAt:950});assert.ok(respawn.keyId);
await assert.rejects(f.service.record(f.actor,{...f.event,eventId:randomUUID(),action:'unban',previousKeyId:death.keyId}),/transition/);
assert.throws(()=>validateEntityState({...f.event,targetKind:'mob',action:'ban'}),/target/);
assert.throws(()=>validateEntityState({...f.event,xp:999}),/fields/);
assert.throws(()=>validateEntityState({...f.event,attributes:{sql:{text:'x'}}}),/attribute/);
}finally{f.db.close();}});

View file

@ -0,0 +1,43 @@
import {createPostbankApi} from '../node/postbank-api.mjs';
import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto';
import {companyFixture} from './company-deed-fixture.mjs';import {BankFixture} from './postbank-fixture.mjs';
import {PostbankService} from '../node/postbank-service.mjs';import {BANK_VERSION} from '../node/postbank-catalogue.mjs';
import {initializeEntityState,createEntityStateKeys} from '../node/entity-state-keys.mjs';import {PostbankEstates,ESTATE_SCHEMA} from '../node/postbank-estates.mjs';
async function setup(){const f=await companyFixture(),bank=new BankFixture();await bank.query(ESTATE_SCHEMA);await initializeEntityState(f.db);const actor=f.people.Owner,target=f.people.Member,targetUuid=randomUUID();await f.db.query('UPDATE site_game_links SET minecraft_uuid=? WHERE user_id=?',[targetUuid,target.id]);
const entity={id:randomUUID(),kind:'person',key:target.id,name:'Estate test client',canView:true,canActivate:true,canPay:true};
const authority=async a=>({entities:[entity],eligibleStaff:[],readAdmin:a.id===actor.id,manageAdmin:a.id===actor.id});
const service=new PostbankService(bank,authority);await service.activate(target,{entityId:entity.id,packageKey:'pb_flow',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});
await bank.query("UPDATE pb_accounts SET balance_minor=10000 WHERE state='active'");
const keys=createEntityStateKeys(f.db,f.keys,{clock:()=>1000,authorizeEvent:async a=>a.id===actor.id,authorizeRead:async a=>a.id===actor.id,authorizeEvidence:async a=>a.id===actor.id});
const event={eventId:randomUUID(),source:'lore-test',action:'death',targetUuid,targetKind:'player',entityType:'minecraft:player',cause:'story-event',scope:'website-lore',world:'website',occurredAt:900,attributes:{loreDeath:true}};
return {...f,actor,target,bank,keys,event,authority,estates:new PostbankEstates(bank,f.db,keys,authority,{clock:()=>1000}),close(){bank.close();f.db.close();}};}
test('death ESK freezes existing bank accounts and staff Unlock restores them without moving money; both replay safely',async()=>{const f=await setup();try{
const initial=await f.bank.query('SELECT id,state,balance_minor,reserved_minor FROM pb_accounts ORDER BY id');const {keyId}=await f.keys.record(f.actor,f.event);
const freeze={keyId,confirmed:true,reason:'Verified story death'};const result=await f.estates.freeze(f.actor,freeze);assert.equal(result.result.state,'frozen');assert.equal((await f.estates.freeze(f.actor,freeze)).replayed,true);
assert.equal((await f.bank.first("SELECT COUNT(*) n FROM pb_accounts WHERE state='active'")).n,0);
const view=await f.estates.list(f.actor);assert.equal(view.records[0].state,'frozen');
const unlock={keyId,revision:view.records[0].revision,requestId:randomUUID(),reason:'Estate review completed',confirmed:true};assert.equal((await f.estates.unlock(f.actor,unlock)).result.state,'unlocked');assert.equal((await f.estates.unlock(f.actor,unlock)).replayed,true);
assert.deepEqual(await f.bank.query('SELECT id,state,balance_minor,reserved_minor FROM pb_accounts ORDER BY id'),initial);
assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_entries')).n,0);assert.equal((await f.keys.get(f.actor,keyId)).action,'death');
const audit=await f.bank.query("SELECT action FROM pb_audit WHERE action IN ('esk_estate_frozen','esk_estate_unlocked')");assert.equal(audit.length,2);
}finally{f.close();}});
test('ordinary deaths, wrong actors, stale revisions and changed replay requests cannot modify an estate',async()=>{const f=await setup();try{
const ordinary=await f.keys.record(f.actor,{...f.event,attributes:{}});await assert.rejects(f.estates.freeze(f.actor,{keyId:ordinary.keyId,confirmed:true,reason:'Ordinary mob death'}),/lore-death/);
const {keyId}=await f.keys.record(f.actor,{...f.event,eventId:randomUUID()});await assert.rejects(f.estates.freeze(f.target,{keyId,confirmed:true,reason:'Not a bank officer'}),e=>e.status===403);
await f.estates.freeze(f.actor,{keyId,confirmed:true,reason:'Verified story death'});
await assert.rejects(f.estates.unlock(f.actor,{keyId,revision:99,requestId:randomUUID(),reason:'Wrong revision provided',confirmed:true}),/changed/);
assert.equal((await f.bank.first('SELECT state FROM pb_esk_estates')).state,'frozen');
await assert.rejects(f.estates.freeze(f.actor,{keyId,confirmed:true,reason:'Changed replay reason'}),/conflict/);
}finally{f.close();}});
test('existing bank API guards ESK forms with identity, origin, confirmed fields and bank authority',async()=>{const f=await setup();try{
let actor=f.actor;const api=createPostbankApi(f.db,f.bank,{}, {authenticate:async()=>actor,authority:f.authority,entityStateKeys:f.keys});
const {keyId}=await f.keys.record(f.actor,f.event);
const call=(path,body,origin='https://cp.dunerealms.com')=>api(new Request('https://cp.dunerealms.com/api/bank/admin/estates'+path,body?{method:'POST',headers:{origin,'Content-Type':'application/json'},body:JSON.stringify(body)}:{}));
assert.equal((await call('')).status,200);
const input={keyId,reason:'Verified story death',confirmed:true};assert.equal((await call('/freeze',input,'https://evil.invalid')).status,403);
assert.equal((await call('/freeze',{...input,accountId:'arbitrary'})).status,400);
actor=f.target;assert.equal((await call('/freeze',input)).status,403);actor=f.actor;
assert.equal((await call('/freeze',input)).status,200);const view=await(await call('')).json();assert.equal(view.records[0].state,'frozen');
}finally{f.close();}});

Binary file not shown.

After

Width:  |  Height:  |  Size: 827 KiB