forked from unimatrix/web
1.0.1.1: shared Realm CP copies, JARVIS key families and Realm Nexus navigation
This commit is contained in:
parent
a4a875d09f
commit
73aa88b670
5 changed files with 594 additions and 379 deletions
10
website/node/jarvis-recruitment-policy.mjs
Normal file
10
website/node/jarvis-recruitment-policy.mjs
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
import {clanMemberLimit} from './clan-membership-policy.mjs';
|
||||
export const RECRUITMENT_PRICE_VERSION='recruitment-1.0.1.0-v1';
|
||||
// Quote only; a publishing handler must recheck authority, capacity and price and reserve payment.
|
||||
export function clanRecruitmentQuote({charterKind,memberCount,protectedInstitution=false,institutionLimit=null}){
|
||||
if(!['basic','original','royal'].includes(charterKind)||!Number.isSafeInteger(memberCount)||memberCount<0)throw TypeError('Invalid recruitment quote');
|
||||
const memberLimit=clanMemberLimit(charterKind,protectedInstitution?institutionLimit:null),availablePlaces=Math.max(0,memberLimit-memberCount);
|
||||
const unitPriceMinor=protectedInstitution?null:charterKind==='basic'?0:1000+25*memberCount;
|
||||
if(unitPriceMinor!==null&&!Number.isSafeInteger(unitPriceMinor))throw TypeError('Invalid recruitment amount');
|
||||
return {policyVersion:RECRUITMENT_PRICE_VERSION,currency:'DM',occupiedMembers:memberCount,memberLimit,availablePlaces:protectedInstitution?0:availablePlaces,unitPriceMinor,recruitmentOpen:!protectedInstitution&&availablePlaces>0};
|
||||
}
|
||||
|
|
@ -11,7 +11,7 @@ export const validReleaseVersion=value=>{
|
|||
const parts=value.split('.').map(Number),lastAlpha=[1,9,9,9];
|
||||
for(let i=0;i<4;i++){if(parts[i]<lastAlpha[i])return true;if(parts[i]>lastAlpha[i])return false;}return true;
|
||||
};
|
||||
export const DEFAULT_BADGES=Object.freeze({Roster:'NEW',Exchange:'UPDATE',Politics:'NEW',Clans:'NEW',Companies:'NEW',CP:'UPDATE'});
|
||||
export const DEFAULT_BADGES=Object.freeze({'Imperial Directorate':'NEW',Starport:'UPDATE','Realm Nexus':'NEW','Citizen Passport':'UPDATE'});
|
||||
const json=(data,status=200,publicRead=false)=>Response.json(data,{status,headers:{'Cache-Control':'no-store',...(publicRead?{'Access-Control-Allow-Origin':'*'}:{})}});
|
||||
export function validateMenuBadges(items,scope='header'){
|
||||
const catalogue=BADGE_SCOPES[scope];if(!catalogue||!Array.isArray(items)||items.length!==catalogue.length)throw Error('Choose one badge for every menu item.');
|
||||
|
|
|
|||
|
|
@ -1,84 +1,97 @@
|
|||
import {parseOrganisationCode,formatOrganisationCode} from '../control-panel/public/codex-code-format.mjs';
|
||||
import {createHash,createCipheriv,createDecipheriv,randomBytes,randomUUID} from 'node:crypto';
|
||||
|
||||
// Server-only. A secret grants a recorded entitlement; it is never an API credential.
|
||||
export const ORGANISATION_KEY_TYPES=Object.freeze({
|
||||
'clan-founding':Object.freeze({prefix:'CLAN',purpose:'original-founding'}),
|
||||
'company-founding':Object.freeze({prefix:'COM',purpose:'original-founding'}),
|
||||
'political-appointment':Object.freeze({prefix:'POL',purpose:'appointment'})
|
||||
});
|
||||
export const organisationKeySchema=Object.freeze([
|
||||
`CREATE TABLE IF NOT EXISTS organisation_keys (id CHAR(36) PRIMARY KEY,account_id CHAR(36) NOT NULL,key_type VARCHAR(32) NOT NULL,scope_id VARCHAR(160) NOT NULL,code_hash CHAR(64) NOT NULL UNIQUE,code_sealed TEXT NOT NULL,created_at BIGINT NOT NULL,expires_at BIGINT NULL,revoked_at BIGINT NULL,used_at BIGINT NULL,target_id CHAR(36) NULL,request_id CHAR(36) NULL,UNIQUE KEY organisation_key_grant(account_id,key_type,scope_id),INDEX organisation_key_owner(account_id,created_at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
||||
`CREATE TABLE IF NOT EXISTS organisation_key_events (id CHAR(36) PRIMARY KEY,key_id CHAR(36) NOT NULL,account_id CHAR(36) NOT NULL,event_type VARCHAR(16) NOT NULL,target_id CHAR(36) NULL,created_at BIGINT NOT NULL,INDEX organisation_key_history(key_id,created_at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`
|
||||
]);
|
||||
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i.test(v);
|
||||
const type=v=>{if(!Object.hasOwn(ORGANISATION_KEY_TYPES,v))throw new TypeError('Unknown organisation key type');return ORGANISATION_KEY_TYPES[v];};
|
||||
export function generateOrganisationKey(keyType){return `${type(keyType).prefix}-${randomBytes(24).toString('hex').toUpperCase()}`;}
|
||||
import {createHash,createCipheriv,createDecipheriv,randomBytes,randomUUID} from 'node:crypto';
|
||||
|
||||
// Server-only. A secret grants a recorded entitlement; it is never an API credential.
|
||||
export const ORGANISATION_KEY_TYPES=Object.freeze({
|
||||
'clan-subhouse':Object.freeze({prefix:'CLAN-SUB',purpose:'subhouse-founding'}),
|
||||
'company-subsidiary':Object.freeze({prefix:'COM-SUB',purpose:'subsidiary-founding'}),
|
||||
'political-clan':Object.freeze({prefix:'POL-CLAN',purpose:'office-membership'}),
|
||||
'clan-founding':Object.freeze({prefix:'CLAN',purpose:'original-founding'}),
|
||||
'company-founding':Object.freeze({prefix:'COM',purpose:'original-founding'}),
|
||||
'political-appointment':Object.freeze({prefix:'POL',purpose:'appointment'})
|
||||
});
|
||||
export const organisationKeySchema=Object.freeze([
|
||||
`CREATE TABLE IF NOT EXISTS organisation_keys (id CHAR(36) PRIMARY KEY,account_id CHAR(36) NOT NULL,key_type VARCHAR(32) NOT NULL,scope_id VARCHAR(160) NOT NULL,code_hash CHAR(64) NOT NULL UNIQUE,code_sealed TEXT NOT NULL,created_at BIGINT NOT NULL,expires_at BIGINT NULL,revoked_at BIGINT NULL,used_at BIGINT NULL,target_id CHAR(36) NULL,request_id CHAR(36) NULL,UNIQUE KEY organisation_key_grant(account_id,key_type,scope_id),INDEX organisation_key_owner(account_id,created_at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
||||
`CREATE TABLE IF NOT EXISTS organisation_key_events (id CHAR(36) PRIMARY KEY,key_id CHAR(36) NOT NULL,account_id CHAR(36) NOT NULL,event_type VARCHAR(16) NOT NULL,target_id CHAR(36) NULL,created_at BIGINT NOT NULL,INDEX organisation_key_history(key_id,created_at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`
|
||||
]);
|
||||
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i.test(v);
|
||||
const type=v=>{if(!Object.hasOwn(ORGANISATION_KEY_TYPES,v))throw new TypeError('Unknown organisation key type');return ORGANISATION_KEY_TYPES[v];};
|
||||
export function generateOrganisationKey(keyType){return `${type(keyType).prefix}-${randomBytes(24).toString('hex').toUpperCase()}`;}
|
||||
export function hashOrganisationKey(code,keyType){
|
||||
const parsed=parseOrganisationCode(code);if(parsed.prefix!==type(keyType).prefix)throw new TypeError('Invalid organisation code');
|
||||
return createHash('sha256').update(parsed.canonical).digest('hex');
|
||||
}
|
||||
export class OrganisationKeyError extends Error {}
|
||||
export function checkOrganisationKey(row,{accountId,keyType,targetId,requestId,now=Date.now()}){
|
||||
if(!row||row.account_id!==accountId||row.key_type!==keyType)throw new OrganisationKeyError('Code unavailable for this account and purpose');
|
||||
if(row.revoked_at!=null)throw new OrganisationKeyError('Code revoked');
|
||||
if(row.used_at!=null){
|
||||
if(row.target_id===targetId&&row.request_id===requestId)return 'replayed';
|
||||
throw new OrganisationKeyError('Code already used');
|
||||
}
|
||||
if(row.expires_at!=null&&Number(row.expires_at)<=now)throw new OrganisationKeyError('Code expired');
|
||||
return 'available';
|
||||
}
|
||||
export async function initializeOrganisationKeys(db){for(const sql of organisationKeySchema)await db.query(sql);}
|
||||
|
||||
// These methods are internal: callers must check identity and domain authority first.
|
||||
// In particular, POL issuance requires an existing valid political decision.
|
||||
export function createOrganisationKeys(db,{secret,editions=null}={}){
|
||||
if(typeof secret!=='string'||!(/^[a-f0-9]{64}$/i).test(secret))throw new TypeError('A dedicated organisation key encryption secret is required');
|
||||
const encryptionKey=Buffer.from(secret,'hex');
|
||||
const seal=(code,aad)=>{const iv=randomBytes(12),cipher=createCipheriv('aes-256-gcm',encryptionKey,iv);cipher.setAAD(Buffer.from(aad));const encrypted=Buffer.concat([cipher.update(code,'utf8'),cipher.final()]);return [iv,cipher.getAuthTag(),encrypted].map(v=>v.toString('base64')).join('.');};
|
||||
const unseal=(value,aad)=>{const [iv,tag,data]=value.split('.').map(v=>Buffer.from(v,'base64')),cipher=createDecipheriv('aes-256-gcm',encryptionKey,iv);cipher.setAAD(Buffer.from(aad));cipher.setAuthTag(tag);return Buffer.concat([cipher.update(data),cipher.final()]).toString('utf8');};
|
||||
const event=(tx,row,action,targetId,now)=>tx.query('INSERT INTO organisation_key_events(id,key_id,account_id,event_type,target_id,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),row.id,row.account_id,action,targetId,now]);
|
||||
return Object.freeze({
|
||||
async issue({accountId,keyType,scopeId,expiresAt=null}){
|
||||
type(keyType);
|
||||
if(!uuid(accountId)||typeof scopeId!=='string'||!scopeId.trim()||scopeId.length>160||expiresAt!==null&&(!Number.isSafeInteger(expiresAt)||expiresAt<=Date.now()))throw new TypeError('Invalid key grant');
|
||||
// Founding is once per account for its entire lifetime, including after sale/archive.
|
||||
if(keyType.endsWith('-founding')&&(scopeId!=='original'||expiresAt!==null))throw new TypeError('Founding grant must use the lifetime original scope');
|
||||
const code=generateOrganisationKey(keyType),id=randomUUID(),now=Date.now(),issuedEdition=editions?await editions.current():null;
|
||||
try{return await db.transaction(async tx=>{
|
||||
await tx.query('INSERT INTO organisation_keys(id,account_id,key_type,scope_id,code_hash,code_sealed,created_at,expires_at) VALUES(?,?,?,?,?,?,?,?)',[id,accountId,keyType,scopeId,hashOrganisationKey(code,keyType),seal(code,`${id}:${accountId}:${keyType}`),now,expiresAt]);
|
||||
export class OrganisationKeyError extends Error {}
|
||||
export function checkOrganisationKey(row,{accountId,keyType,targetId,requestId,now=Date.now()}){
|
||||
if(!row||row.account_id!==accountId||row.key_type!==keyType)throw new OrganisationKeyError('Code unavailable for this account and purpose');
|
||||
if(row.revoked_at!=null)throw new OrganisationKeyError('Code revoked');
|
||||
if(row.used_at!=null){
|
||||
if(row.target_id===targetId&&row.request_id===requestId)return 'replayed';
|
||||
throw new OrganisationKeyError('Code already used');
|
||||
}
|
||||
if(row.expires_at!=null&&Number(row.expires_at)<=now)throw new OrganisationKeyError('Code expired');
|
||||
return 'available';
|
||||
}
|
||||
export async function initializeOrganisationKeys(db){for(const sql of organisationKeySchema)await db.query(sql);}
|
||||
|
||||
// These methods are internal: callers must check identity and domain authority first.
|
||||
// In particular, POL issuance requires an existing valid political decision.
|
||||
export function createOrganisationKeys(db,{secret,editions=null}={}){
|
||||
if(typeof secret!=='string'||!(/^[a-f0-9]{64}$/i).test(secret))throw new TypeError('A dedicated organisation key encryption secret is required');
|
||||
const encryptionKey=Buffer.from(secret,'hex');
|
||||
const seal=(code,aad)=>{const iv=randomBytes(12),cipher=createCipheriv('aes-256-gcm',encryptionKey,iv);cipher.setAAD(Buffer.from(aad));const encrypted=Buffer.concat([cipher.update(code,'utf8'),cipher.final()]);return [iv,cipher.getAuthTag(),encrypted].map(v=>v.toString('base64')).join('.');};
|
||||
const unseal=(value,aad)=>{const [iv,tag,data]=value.split('.').map(v=>Buffer.from(v,'base64')),cipher=createDecipheriv('aes-256-gcm',encryptionKey,iv);cipher.setAAD(Buffer.from(aad));cipher.setAuthTag(tag);return Buffer.concat([cipher.update(data),cipher.final()]).toString('utf8');};
|
||||
const event=(tx,row,action,targetId,now)=>tx.query('INSERT INTO organisation_key_events(id,key_id,account_id,event_type,target_id,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),row.id,row.account_id,action,targetId,now]);
|
||||
return Object.freeze({
|
||||
async issue({accountId,keyType,scopeId,expiresAt=null,authorize=null}){
|
||||
type(keyType);
|
||||
if(!uuid(accountId)||typeof scopeId!=='string'||!scopeId.trim()||scopeId.length>160||expiresAt!==null&&(!Number.isSafeInteger(expiresAt)||expiresAt<=Date.now()))throw new TypeError('Invalid key grant');
|
||||
// Founding is once per account for its entire lifetime, including after sale/archive.
|
||||
if(keyType.endsWith('-founding')&&(scopeId!=='original'||expiresAt!==null))throw new TypeError('Founding grant must use the lifetime original scope');
|
||||
if(['clan-subhouse','company-subsidiary'].includes(keyType)&&(!(scopeId.split(':').length===3&&scopeId.split(':')[0]==='parent'&&uuid(scopeId.split(':')[1])&&uuid(scopeId.split(':')[2]))||typeof authorize!=='function'))throw new TypeError('Subhouse keys require a parent-deed scope and an authority adapter');
|
||||
if(keyType==='political-clan'&&(!uuid(scopeId)||expiresAt===null))throw new TypeError('Political clan keys require an expiring office deed');
|
||||
const code=generateOrganisationKey(keyType),id=randomUUID(),now=Date.now(),issuedEdition=editions?await editions.current():null;
|
||||
try{return await db.transaction(async tx=>{
|
||||
if(['clan-subhouse','company-subsidiary'].includes(keyType))await authorize(tx,{accountId,keyType,scopeId});
|
||||
if(keyType==='political-clan'){
|
||||
const term=await tx.first("SELECT faction,office,expires_at FROM political_office_terms WHERE id=? AND user_id=? AND outcome='winner' AND starts_at<=? AND expires_at>? FOR UPDATE",[scopeId,accountId,now,now]);
|
||||
if(!term||Number(term.expires_at)!==expiresAt)throw new OrganisationKeyError('An active matching political office deed is required');
|
||||
const count=await tx.first("SELECT COUNT(*) total FROM political_office_terms WHERE faction=? AND office=? AND outcome='winner' AND starts_at<=? AND expires_at>?",[term.faction,term.office,now,now]);
|
||||
if(Number(count.total)!==1)throw new OrganisationKeyError('Political office deed is ambiguous');
|
||||
}
|
||||
|
||||
await tx.query('INSERT INTO organisation_keys(id,account_id,key_type,scope_id,code_hash,code_sealed,created_at,expires_at) VALUES(?,?,?,?,?,?,?,?)',[id,accountId,keyType,scopeId,hashOrganisationKey(code,keyType),seal(code,`${id}:${accountId}:${keyType}`),now,expiresAt]);
|
||||
if(editions)await editions.record(tx,id,issuedEdition);
|
||||
await event(tx,{id,account_id:accountId},'issued',null,now);
|
||||
const edition=editions?await editions.read(id,tx):null;return {id,code:edition?formatOrganisationCode(code,edition):code,edition,created:true};
|
||||
});}catch(error){
|
||||
if(error.code!=='ER_DUP_ENTRY')throw error;
|
||||
const prior=await db.query('SELECT id FROM organisation_keys WHERE account_id=? AND key_type=? AND scope_id=?',[accountId,keyType,scopeId]);
|
||||
if(!prior[0])throw error;
|
||||
// No replacement secret and no restored entitlement on retry.
|
||||
return {id:prior[0].id,created:false};
|
||||
}
|
||||
},
|
||||
async list(accountId){
|
||||
if(!uuid(accountId))throw new TypeError('Invalid account');
|
||||
const rows=await db.query('SELECT * FROM organisation_keys WHERE account_id=? ORDER BY created_at,id',[accountId]);
|
||||
await event(tx,{id,account_id:accountId},'issued',null,now);
|
||||
const edition=editions?await editions.read(id,tx):null;return {id,code:edition?formatOrganisationCode(code,edition):code,edition,created:true};
|
||||
});}catch(error){
|
||||
if(error.code!=='ER_DUP_ENTRY')throw error;
|
||||
const prior=await db.query('SELECT id FROM organisation_keys WHERE account_id=? AND key_type=? AND scope_id=?',[accountId,keyType,scopeId]);
|
||||
if(!prior[0])throw error;
|
||||
// No replacement secret and no restored entitlement on retry.
|
||||
return {id:prior[0].id,created:false};
|
||||
}
|
||||
},
|
||||
async list(accountId){
|
||||
if(!uuid(accountId))throw new TypeError('Invalid account');
|
||||
const rows=await db.query('SELECT * FROM organisation_keys WHERE account_id=? ORDER BY created_at,id',[accountId]);
|
||||
const editionMap=editions?await editions.forAccount(accountId):null;
|
||||
return rows.map(row=>{const edition=editionMap?.get(row.id);if(editions&&!edition)throw Error('Code edition is unavailable');const available=row.revoked_at==null&&row.used_at==null&&(row.expires_at==null||Number(row.expires_at)>Date.now());const raw=available?unseal(row.code_sealed,`${row.id}:${accountId}:${row.key_type}`):null;return {id:row.id,edition,keyType:row.key_type,scopeId:row.scope_id,createdAt:Number(row.created_at),targetId:row.target_id,status:row.revoked_at!=null?'revoked':row.used_at!=null?'used':row.expires_at!=null&&Number(row.expires_at)<=Date.now()?'expired':'available',code:raw&&edition?formatOrganisationCode(raw,edition):raw};});
|
||||
},
|
||||
async consume({accountId,keyType,code,targetId,requestId,apply}){
|
||||
if(!uuid(accountId)||!uuid(targetId)||!uuid(requestId)||typeof apply!=='function')throw new TypeError('Invalid key redemption');
|
||||
const hash=hashOrganisationKey(code,keyType);
|
||||
return db.transaction(async tx=>{
|
||||
const row=await tx.first('SELECT * FROM organisation_keys WHERE code_hash=? FOR UPDATE',[hash]),now=Date.now();
|
||||
return rows.map(row=>{const edition=editionMap?.get(row.id);if(editions&&!edition)throw Error('Code edition is unavailable');const available=row.revoked_at==null&&row.used_at==null&&(row.expires_at==null||Number(row.expires_at)>Date.now());const raw=available?unseal(row.code_sealed,`${row.id}:${accountId}:${row.key_type}`):null;return {id:row.id,edition,keyType:row.key_type,scopeId:row.scope_id,createdAt:Number(row.created_at),targetId:row.target_id,status:row.revoked_at!=null?'revoked':row.used_at!=null?'used':row.expires_at!=null&&Number(row.expires_at)<=Date.now()?'expired':'available',code:raw&&edition?formatOrganisationCode(raw,edition):raw};});
|
||||
},
|
||||
async consume({accountId,keyType,code,targetId,requestId,apply}){
|
||||
if(!uuid(accountId)||!uuid(targetId)||!uuid(requestId)||typeof apply!=='function')throw new TypeError('Invalid key redemption');
|
||||
const hash=hashOrganisationKey(code,keyType);
|
||||
return db.transaction(async tx=>{
|
||||
const row=await tx.first('SELECT * FROM organisation_keys WHERE code_hash=? FOR UPDATE',[hash]),now=Date.now();
|
||||
const parsed=parseOrganisationCode(code);if(parsed.edition){if(!row||!editions)throw new OrganisationKeyError('Code edition could not be verified');const edition=await editions.read(row.id,tx);if(['stage','version','season'].some(k=>parsed.edition[k]!==edition[k]))throw new OrganisationKeyError('Code edition does not match its original record');}
|
||||
const state=checkOrganisationKey(row,{accountId,keyType,targetId,requestId,now});
|
||||
if(state==='replayed')return {id:row.id,targetId,replayed:true};
|
||||
// Domain writes MUST use this transaction. A failed creation/appointment consumes nothing.
|
||||
await apply(tx,{keyId:row.id,targetId,purpose:type(keyType).purpose});
|
||||
await tx.query('UPDATE organisation_keys SET used_at=?,target_id=?,request_id=? WHERE id=?',[now,targetId,requestId,row.id]);
|
||||
await event(tx,row,'used',targetId,now);
|
||||
return {id:row.id,targetId,replayed:false};
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
const state=checkOrganisationKey(row,{accountId,keyType,targetId,requestId,now});
|
||||
if(state==='replayed')return {id:row.id,targetId,replayed:true};
|
||||
// Domain writes MUST use this transaction. A failed creation/appointment consumes nothing.
|
||||
await apply(tx,{keyId:row.id,targetId,purpose:type(keyType).purpose,scopeId:row.scope_id});
|
||||
await tx.query('UPDATE organisation_keys SET used_at=?,target_id=?,request_id=? WHERE id=?',[now,targetId,requestId,row.id]);
|
||||
await event(tx,row,'used',targetId,now);
|
||||
return {id:row.id,targetId,replayed:false};
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
|
|||
15
website/node/politics-workspace.mjs
Normal file
15
website/node/politics-workspace.mjs
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
import {identity} from './auth.mjs';
|
||||
import {accessFor} from './permissions.mjs';
|
||||
import {readGovernmentOffices} from './public-government.mjs';
|
||||
// Protected political organisations project active office deeds; they never replace personal membership.
|
||||
export function createPoliticsWorkspace(db,{authenticate=r=>identity(r,db),access=u=>accessFor(db,u),clock=Date.now,keys=null}={}){return async request=>{
|
||||
const reply=(v,status=200)=>Response.json(v,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}});
|
||||
if(request.method!=='GET')return reply({message:'Read-only political workspace.'},405);
|
||||
const user=await authenticate(request);if(!user)return reply({message:'Sign in to open Politics CP.'},401);
|
||||
if(!(await access(user)).nodes.includes('web.menu.game'))return reply({message:'Game account access required.'},403);
|
||||
const params=new URL(request.url).searchParams,selected=params.get('office');if([...params.keys()].some(k=>k!=='office')||params.getAll('office').length>1||selected!==null&&!/^[a-z_]{1,32}$/.test(selected))return reply({message:'Choose a valid political organisation.'},400);
|
||||
try{const account=await db.prepare("SELECT username FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'").bind(user.id).first();if(!account)return reply({message:'Account access changed.'},403);const offices=await readGovernmentOffices(db,clock());const grants=new Map();if(keys){const now=clock();const {results:terms}=await db.prepare("SELECT id,faction,office,expires_at FROM political_office_terms WHERE user_id=? AND outcome='winner' AND starts_at<=? AND expires_at>?").bind(user.id,now,now).all();for(const office of offices.filter(o=>o.holder?.username.toLowerCase()===String(account.username).toLowerCase())){const matches=terms.filter(t=>t.faction===office.faction&&t.office===office.office);if(matches.length!==1)continue;const grant=await keys.issue({accountId:user.id,keyType:'political-clan',scopeId:matches[0].id,expiresAt:Number(matches[0].expires_at)});grants.set(office.key,grant.id);}}const usable=keys?new Set((await keys.list(user.id)).filter(k=>['available','used'].includes(k.status)).map(k=>k.id)):null;const belongs=o=>o.holder?.username.toLowerCase()===String(account.username).toLowerCase()&&(!usable||usable.has(grants.get(o.key)));const organisations=offices.map(o=>({id:o.key,name:o.scope,description:o.description,tag:o.faction.toUpperCase(),emblem:'https://www.dunerealms.com/assets/seals/'+o.art,protected:true,kind:'politics',role:belongs(o)?'officeholder':'visitor',members:o.holder?[{username:o.holder.username,role:'officeholder',name:o.holder.name}]:[],membership:belongs(o)?{source:'active-office-deed',keyId:grants.get(o.key)||null,startsAt:o.term.startsAt,expiresAt:o.term.expiresAt}:null}));
|
||||
if(selected&&!organisations.some(o=>o.id===selected))return reply({message:'Political organisation not found.'},404);
|
||||
return reply({organisations,selected:selected||organisations.find(o=>o.membership)?.id||organisations[0]?.id||null,membershipSource:'active-office-deed',decisionKeysSeparate:true});
|
||||
}catch{return reply({message:'Political deed membership could not be verified.'},503);}
|
||||
};}
|
||||
13
website/node/subhouse-keys.mjs
Normal file
13
website/node/subhouse-keys.mjs
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import {clanDeedAuthority} from './clan-deeds.mjs';
|
||||
import {OrganisationKeyError} 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);
|
||||
// Internal issuer; the later creation/transfer handler must revalidate this same mother deed.
|
||||
export async function issueClanSubhouseKey(db,keys,user,{parentClanId,requestId}){
|
||||
if(!uuid(parentClanId)||!uuid(requestId)||!uuid(user?.id))throw TypeError('Choose a valid mother deed and request');
|
||||
return keys.issue({accountId:user.id,keyType:'clan-subhouse',scopeId:'parent:'+parentClanId+':'+requestId,authorize:async tx=>{
|
||||
if(!await tx.first('SELECT id FROM site_clans WHERE id=? AND active=1 FOR UPDATE',[parentClanId]))throw new OrganisationKeyError('Mother clan unavailable');
|
||||
const reader={prepare(sql){let values=[];return {bind(...args){values=args;return this;},first:()=>tx.first(sql,values),all:async()=>({results:await tx.query(sql,values)})};}};
|
||||
const authority=await clanDeedAuthority(reader,user.id,parentClanId);
|
||||
if(!authority.canManage||!authority.deed?.keyed||authority.deed.root!==parentClanId||authority.deed.clan.institution_key)throw new OrganisationKeyError('A current Keyed or Royal mother deed is required');
|
||||
}});
|
||||
}
|
||||
Loading…
Reference in a new issue

Staff