57 lines
5.9 KiB
JavaScript
57 lines
5.9 KiB
JavaScript
import {identity} from './auth.mjs';
|
|
import {accessFor} from './permissions.mjs';
|
|
import {currentOfficeController} from './entity-relations.mjs';
|
|
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
|
|
import {validUuid} from './game-link.mjs';
|
|
import {IMPERIAL_PASSAGE_COOLDOWN_MS,PASSAGE_HOUSES,passageHouses} from '../control-panel/public/imperial-passage-policy.mjs';
|
|
export const IMPERIAL_PASSAGE_SCHEMA=`CREATE TABLE IF NOT EXISTS jarvis_imperial_passage_orders(request_id CHAR(36) PRIMARY KEY,key_id CHAR(36) NOT NULL UNIQUE,actor_id CHAR(36) NOT NULL,term_id CHAR(36) NOT NULL,houses_json TEXT NOT NULL,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`;
|
|
const fail=(message,status=409)=>{throw Object.assign(Error(message),{status});};
|
|
const first=async(db,sql,args=[])=>(await db.query(sql,args))[0]||null;
|
|
async function latest(db){return first(db,"SELECT p.*,k.id verified_key FROM jarvis_imperial_passage_orders p LEFT JOIN organisation_keys k ON k.id=p.key_id AND k.account_id=? AND k.key_type='entity-state' AND k.scope_id=CONCAT('state:imperial-passage:',p.request_id) AND k.revoked_at IS NULL ORDER BY p.created_at DESC,p.request_id DESC LIMIT 1",[STAFF_OFFICE_ACCOUNT_ID]);}
|
|
// Retain old signed records for audit, but do not choose an arbitrary House
|
|
// when a legacy order contains multiple selections contrary to current policy.
|
|
function currentGrant(row){if(!row?.verified_key)return {houses:[],requiresReview:false};try{return {houses:passageHouses(JSON.parse(row.houses_json)),requiresReview:false};}catch{return {houses:[],requiresReview:true};}}
|
|
// The latest order replaces the entire previous selection; a revoked latest key
|
|
// must never revive an older selection. Fremen home travel remains independent.
|
|
export async function hasImperialPassage(db,house){
|
|
if(!PASSAGE_HOUSES.some(h=>h.id===house))return false;
|
|
const row=await latest(db);return currentGrant(row).houses.includes(house);
|
|
}
|
|
async function emperor(db,actor,now,{lock=false}={}){
|
|
const charter=await first(db,"SELECT c.staff_key_id FROM political_office_charters c JOIN organisation_keys k ON k.id=c.staff_key_id AND k.key_type='staff-office-royal' AND k.scope_id='office:emperor' AND k.account_id=? AND k.used_at IS NOT NULL AND k.revoked_at IS NULL WHERE c.office_key='emperor' AND c.charter_kind='royal'"+(lock?' FOR UPDATE':''),[STAFF_OFFICE_ACCOUNT_ID]);
|
|
if(!charter)return null;
|
|
const holder=await currentOfficeController(db,'emperor',now);if(holder?.userId!==actor?.id)return null;
|
|
if(lock){await first(db,'SELECT id FROM political_office_terms WHERE id=? FOR UPDATE',[holder.termId]);const current=await currentOfficeController(db,'emperor',now);if(current?.userId!==actor.id||current.termId!==holder.termId)return null;}
|
|
return holder;
|
|
}
|
|
export function createImperialPassage(db,keys,{clock=Date.now}={}){
|
|
async function read(actor){const [row,holder]=await Promise.all([latest(db),emperor(db,actor,clock())]);const cooldownUntil=row?Number(row.created_at)+IMPERIAL_PASSAGE_COOLDOWN_MS:null;return{...currentGrant(row),choices:PASSAGE_HOUSES,keyId:row?.key_id||null,requestId:row?.request_id||null,cooldownMs:IMPERIAL_PASSAGE_COOLDOWN_MS,cooldownUntil,canManage:!!holder,canExecute:!!holder&&(!cooldownUntil||clock()>=cooldownUntil)};}
|
|
async function grant(actor,input){
|
|
if(!input||Object.keys(input).sort().join(',')!=='houses,requestId'||!validUuid(input.requestId))fail('Invalid passage decision.',400);
|
|
let houses;try{houses=passageHouses(input.houses);}catch(e){fail(e.message,400);}
|
|
if(!keys)fail('The key service is unavailable.',503);
|
|
await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'entity-state',scopeId:'state:imperial-passage:'+input.requestId,authorize:async(tx,{keyId})=>{
|
|
const now=clock(),holder=await emperor(tx,actor,now,{lock:true});if(!holder)fail('Only the current Emperor can grant House passage.',403);
|
|
const prior=await first(tx,'SELECT * FROM jarvis_imperial_passage_orders WHERE request_id=?',[input.requestId]);
|
|
if(prior){if(prior.actor_id!==actor.id||prior.houses_json!==JSON.stringify(houses))fail('This decision reference was already used.');return;}
|
|
const previous=await latest(tx);if(previous&&now<Number(previous.created_at)+IMPERIAL_PASSAGE_COOLDOWN_MS)fail('Wait seven days after the previous passage decision.');
|
|
await tx.query('INSERT INTO jarvis_imperial_passage_orders(request_id,key_id,actor_id,term_id,houses_json,created_at) VALUES(?,?,?,?,?,?)',[input.requestId,keyId,actor.id,holder.termId,JSON.stringify(houses),now]);
|
|
}});return{ok:true,...await read(actor)};
|
|
}
|
|
return{read,grant};
|
|
}
|
|
export function createImperialPassageAPI(db,keys,{origin='https://cp.dunerealms.com',clock=Date.now,authenticate=r=>identity(r,db),access=a=>accessFor(db,a)}={}){
|
|
const service=createImperialPassage(db,keys,{clock}),reply=(b,s=200)=>Response.json(b,{status:s,headers:{'Cache-Control':'private, no-store'}});
|
|
return async request=>{try{
|
|
const actor=await authenticate(request);if(!actor)return reply({message:'Sign in first.'},401);
|
|
if(!(await access(actor)).nodes.includes('web.menu.game'))return reply({message:'Player access required.'},403);
|
|
if(new URL(request.url).search)return reply({message:'Identity overrides are not accepted.'},400);
|
|
if(request.method==='GET')return reply(await service.read(actor));
|
|
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>2048)return reply({message:'Request too large.'},413);
|
|
let body;try{body=JSON.parse(raw);}catch{return reply({message:'Invalid passage decision.'},400);}
|
|
return reply(await service.grant(actor,body));
|
|
}catch(e){return reply({message:e.status?e.message:'Passage decision was not confirmed. Refresh before retrying.'},e.status||503);}};
|
|
}
|

Staff