web/website/node/postbank-estates.mjs

46 lines
6.8 KiB
JavaScript

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;
}));
}
}