diff --git a/website/control-panel/clan-key-receipts.mjs b/website/control-panel/clan-key-receipts.mjs index d014daf6..019b309f 100644 --- a/website/control-panel/clan-key-receipts.mjs +++ b/website/control-panel/clan-key-receipts.mjs @@ -4,6 +4,7 @@ import {accessFor} from '../node/permissions.mjs'; import {ensureOriginalKeys} from '../node/organisation-key-service.mjs'; import {upgradeOriginalClan} from '../node/clan-key-upgrade.mjs'; import {OrganisationKeyError} from '../node/organisation-keys.mjs'; +import {privateKeyPresentation} from '../node/organisation-key-policy.mjs'; export function createClanKeyReceipts(db,{authenticate=r=>identity(r,db),access=u=>accessFor(db,u),keys=null,origin='https://cp.dunerealms.com'}={}){return async request=>{ const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}}); if(!['GET','POST'].includes(request.method))return reply({message:'Method not allowed.'},405); @@ -21,7 +22,7 @@ export function createClanKeyReceipts(db,{authenticate=r=>identity(r,db),access= } if(keys)await ensureOriginalKeys(keys,user.id); const secrets=keys?new Map((await keys.list(user.id)).map(r=>[r.id,r])):new Map(); - const {results}=await db.prepare("SELECT k.id,k.key_type,k.created_at,k.used_at,k.expires_at,k.revoked_at,k.target_id,c.name,c.tag,ch.charter_kind FROM organisation_keys k LEFT JOIN site_clans c ON c.id=k.target_id AND k.key_type IN ('clan-founding','clan-subhouse','political-appointment') LEFT JOIN site_clan_charters ch ON ch.clan_id=c.id WHERE k.account_id=? AND k.key_type IN ('clan-founding','company-founding','political-appointment','political-clan','clan-subhouse','company-subsidiary') ORDER BY k.created_at,k.id LIMIT 100").bind(user.id).all(); + const {results}=await db.prepare("SELECT k.id,k.key_type,k.created_at,k.used_at,k.expires_at,k.revoked_at,k.target_id,c.name,c.tag,ch.charter_kind FROM organisation_keys k LEFT JOIN site_clans c ON c.id=k.target_id AND k.key_type IN ('clan-founding','clan-subhouse','political-appointment') LEFT JOIN site_clan_charters ch ON ch.clan_id=c.id WHERE k.account_id=? AND k.key_type IN ('clan-founding','company-founding','political-appointment','political-clan','clan-subhouse','company-subsidiary','xp-correction','xp-transfer') ORDER BY k.created_at,k.id LIMIT 100").bind(user.id).all(); if(db.companyDeedsEnabled){const ids=[...new Set(results.filter(r=>['company-founding','company-subsidiary'].includes(r.key_type)&&r.target_id).map(r=>r.target_id))];if(ids.length){const {results:companies}=await db.prepare('SELECT c.id,c.name,d.charter_kind FROM corrino_companies c JOIN site_company_deeds d ON d.company_id=c.id WHERE c.id IN ('+ids.map(()=>'?').join(',')+')').bind(...ids).all();const map=new Map(companies.map(c=>[c.id,c]));for(const record of results)if(['company-founding','company-subsidiary'].includes(record.key_type)&&map.has(record.target_id))Object.assign(record,{name:map.get(record.target_id).name,charter_kind:map.get(record.target_id).charter_kind});}} - return reply({keys:results.map(r=>({id:r.id,type:r.key_type==='clan-founding'?'clan':r.key_type==='company-founding'?'company':r.key_type==='political-clan'?'politics-clan':r.key_type==='clan-subhouse'?'subhouse':r.key_type==='company-subsidiary'?'subsidiary':'politics',createdAt:Number(r.created_at),status:r.revoked_at!=null?'Revoked':r.used_at!=null?'Applied':r.expires_at!=null&&Number(r.expires_at)<=Date.now()?'Expired':keys?'Available':'Issued',clan:r.name||null,clanId:r.target_id,charter:r.charter_kind||null,code:secrets.get(r.id)?.code||null,edition:secrets.get(r.id)?.edition||null}))}); + return reply({keys:results.map(r=>({id:r.id,...privateKeyPresentation(r.key_type),type:r.key_type==='clan-founding'?'clan':r.key_type==='company-founding'?'company':r.key_type==='political-clan'?'politics-clan':r.key_type==='clan-subhouse'?'subhouse':r.key_type==='company-subsidiary'?'subsidiary':r.key_type==='xp-correction'?'xp-correction':r.key_type==='xp-transfer'?'xp-transfer':'politics',createdAt:Number(r.created_at),status:r.revoked_at!=null?'Revoked':r.used_at!=null?'Applied':r.expires_at!=null&&Number(r.expires_at)<=Date.now()?'Expired':keys?'Available':'Issued',clan:r.name||null,clanId:r.target_id,charter:r.charter_kind||null,code:privateKeyPresentation(r.key_type).showCode?(secrets.get(r.id)?.code||null):null,edition:secrets.get(r.id)?.edition||null}))}); };} diff --git a/website/control-panel/public/codex-code-format.mjs b/website/control-panel/public/codex-code-format.mjs index 9425b44f..278413fc 100644 --- a/website/control-panel/public/codex-code-format.mjs +++ b/website/control-panel/public/codex-code-format.mjs @@ -1,6 +1,6 @@ // Shared syntax only: a readable edition is never proof of ownership or authority. -const legacy=/^(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=/^(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=/^(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=/^(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); diff --git a/website/control-panel/public/cp-v2/cp-v2-jarvis-register.mjs b/website/control-panel/public/cp-v2/cp-v2-jarvis-register.mjs index 9443572b..3ac02bc1 100644 --- a/website/control-panel/public/cp-v2/cp-v2-jarvis-register.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-jarvis-register.mjs @@ -1,7 +1,7 @@ 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:[['ID','id'],['Type','type'],['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:[['ID','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={keys:[['ID','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:[['ID','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); diff --git a/website/control-panel/public/cp-v2/cp-v2-rewards.mjs b/website/control-panel/public/cp-v2/cp-v2-rewards.mjs index 8fb0ef7e..c1f80f6b 100644 --- a/website/control-panel/public/cp-v2/cp-v2-rewards.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-rewards.mjs @@ -19,7 +19,7 @@ function table(target,head,rows){const wrap=el('div',undefined,'cp-v2-company-ta export function mountRewards(host,{fetcher=fetch,initialTab}={}){ let active=true,busy=false,uncertain=false,orders=[];const controller=new AbortController(),{request}=createUserAPI(fetcher,controller.signal); const codes=el('section'),community=el('section'),tokens=el('section'),refresh=el('button','Refresh codes'),status=el('p','Opening your private rewards register…');status.setAttribute('role','status');refresh.type='button';codes.append(refresh); - const directory=el('section',undefined,'reward-code-directory'),filter=el('input'),typeFilter=el('select'),listing=el('div'),groups=new Map();filter.type='search';filter.placeholder='Search codes, rewards or references';filter.setAttribute('aria-label','Search your codes');typeFilter.setAttribute('aria-label','Filter code type');for(const [value,label] of [['all','All code types'],['kit','Kits'],['token','Upgrade Tokens'],['clan','Clan founding'],['company','Company clan founding'],['politics-clan','Political clan membership'],['subhouse','Subhouse founding'],['subsidiary','Subsidiary founding'],['politics','Political decisions'],['community','Community rewards']]){const option=el('option',label);option.value=value;typeFilter.append(option);}const controls=el('div',undefined,'reward-code-controls');controls.append(filter,typeFilter);const banner=el('header',undefined,'reward-code-banner'),crest=el('img');crest.src='https://www.dunerealms.com/assets/imperial-seal-128.png';crest.alt='';const copy=el('div');copy.append(el('small','SPOST · PRIVATE ENTITLEMENT REGISTER'),el('h4','Your codes. Your next chapter.'),el('p','Kits KIT-… · Upgrades UP-… · Clans CLAN-… · Companies COM-… · Royal POL-…'));banner.append(crest,copy);directory.append(banner,controls,listing);codes.append(status,directory); + const directory=el('section',undefined,'reward-code-directory'),filter=el('input'),typeFilter=el('select'),listing=el('div'),groups=new Map();filter.type='search';filter.placeholder='Search codes, rewards or references';filter.setAttribute('aria-label','Search your codes');typeFilter.setAttribute('aria-label','Filter code type');for(const [value,label] of [['all','All code types'],['kit','Kits'],['token','Upgrade Tokens'],['clan','Clan founding'],['company','Company clan founding'],['politics-clan','Political clan membership'],['subhouse','Subhouse founding'],['subsidiary','Subsidiary founding'],['politics','Political decisions'],['community','Community rewards'],['xp-correction','XP compensation'],['xp-transfer','Season XP transfer']]){const option=el('option',label);option.value=value;typeFilter.append(option);}const controls=el('div',undefined,'reward-code-controls');controls.append(filter,typeFilter);const banner=el('header',undefined,'reward-code-banner'),crest=el('img');crest.src='https://www.dunerealms.com/assets/imperial-seal-128.png';crest.alt='';const copy=el('div');copy.append(el('small','SPOST · PRIVATE ENTITLEMENT REGISTER'),el('h4','Your codes. Your next chapter.'),el('p','Kits KIT-… · Upgrades UP-… · Clans CLAN-… · Companies COM-… · Royal POL-…'));banner.append(crest,copy);directory.append(banner,controls,listing);codes.append(status,directory); function paintCodes(){const q=filter.value.trim().toLowerCase(),rows=[];for(const [kind,group] of groups){if(typeFilter.value!=='all'&&typeFilter.value!==kind)continue;for(const row of group.rows){if(q&&!([group.title,...row.map(v=>typeof v==='object'?v.textContent:v)].join(' ').toLowerCase().includes(q)))continue;rows.push([createCodeTypeIcon(kind),...row]);}}table(listing,['Type','Reward / entitlement','Reference / amount','Status','Private code / action'],rows);} function setCodes(kind,title,rows){groups.set(kind,{title,rows:rows.length?rows:[[title+' register','—','No records','—']]});paintCodes();} for(const [kind,title] of [['clan','Clan founding'],['company','Company clan founding'],['politics-clan','Political clan membership'],['subhouse','Subhouse founding'],['subsidiary','Subsidiary founding']])setCodes(kind,title,[[title+' register','Once per account','Loading…','—']]);for(const [kind,title] of [['kit','Kit'],['token','Upgrade Token'],['community','Community reward']])setCodes(kind,title,[[title+' register','—','Loading…','—']]);filter.oninput=typeFilter.onchange=paintCodes;const tailor=el('a','Apply Upgrade Tokens in Imperial Tailor →');tailor.href='#realm/kits-exchange';directory.append(tailor);directory.append(el('p','Clan and Royal grants appear here after issuance. Applied grants are receipts and cannot be reused. Formats: KIT-…, UP-…, CLAN-… and COM-…. Existing DRK/DRU codes remain valid.','reward-code-note')); @@ -34,7 +34,7 @@ export function mountRewards(host,{fetcher=fetch,initialTab}={}){ if(data[0].status==='fulfilled'){orders=data[0].value.orders;groupKitReceipts(orders);render();uncertain=false;}else{orders=[];setCodes('kit','Kit',[['Kit register','—',data[0].reason.message,'—']]);} community.replaceChildren();if(data[1].status==='fulfilled'){const d=data[1].value;if(!Array.isArray(d.available)||!Array.isArray(d.history))setCodes('community','Community reward',[['Community register','—','Community reward records could not be confirmed.','—']]);else{setCodes('community','Community reward',[...d.available,...d.history].map(row=>[row.month==='season-tavren-ii'?'Tavren II Aedrecht':row.month,row.reward_amount+' DM',row.delivered_at?'Delivered':row.delivery_ready===false?'Delivery not available':'Available',row.personal_code&&row.delivery_ready!==false&&/^[a-z0-9-]{8,128}$/i.test(row.personal_code)?codeCell('/communitycode '+row.personal_code,true):'—']));if(!d.linked)community.append(el('p','Link your Minecraft identity to see earned community rewards.'));}}else setCodes('community','Community reward',[['Community register','—',data[1].reason.message,'—']]); tokens.replaceChildren();if(data[2].status==='fulfilled'&&Array.isArray(data[2].value.tokens)){setCodes('token','Upgrade Token',data[2].value.tokens.map(row=>['Upgrade Token',new Date(row.createdAt).toLocaleString(),row.usedAt?'Used':'Available',!row.usedAt&&/^DRU-[A-F0-9]{48}$/.test(row.code||'')?codeCell(row.code):'—']));const workshop=el('a','Apply tokens in Imperial Tailor →');workshop.href='#realm/kits-exchange';tokens.append(workshop);}else setCodes('token','Upgrade Token',[['Token register','—',data[2].reason?.message||'Upgrade Token records could not be confirmed.','—']]); - if(data[3].status==='fulfilled'){const records=data[3].value.keys||[];for(const [kind,title]of [['clan','Clan founding'],['company','Company clan founding'],['politics-clan','Political clan membership'],['subhouse','Subhouse founding'],['subsidiary','Subsidiary founding'],['politics','Royal appointment']])setCodes(kind,title,records.filter(r=>r.type===kind).map(r=>[r.clan||title,r.id,r.status,r.status==='Applied'?'Applied to '+(r.clan||'your organisation')+' · '+(['subhouse','subsidiary'].includes(r.type)?'Parent-bound charter':r.type==='politics-clan'?'Office membership':r.charter==='royal'?'Royal House':'Registered charter'):r.code?codeCell(r.code):'—']));}else for(const [kind,title]of [['clan','Clan founding'],['company','Company clan founding'],['politics-clan','Political clan membership'],['subhouse','Subhouse founding'],['subsidiary','Subsidiary founding'],['politics','Royal appointment']])setCodes(kind,title,[[title,'—',data[3].reason.message,'—']]); + if(data[3].status==='fulfilled'){const records=(data[3].value.keys||[]).filter(row=>row.family!=='system');for(const [kind,title]of [['clan','Clan founding'],['company','Company clan founding'],['politics-clan','Political clan membership'],['subhouse','Subhouse founding'],['subsidiary','Subsidiary founding'],['politics','Royal appointment'],['xp-correction','XP compensation'],['xp-transfer','Season XP transfer']])setCodes(kind,title,records.filter(r=>r.type===kind).map(r=>[r.clan||title,r.id,r.status,r.status==='Applied'?'Applied to '+(r.clan||'your organisation')+' · '+(['subhouse','subsidiary'].includes(r.type)?'Parent-bound charter':r.type==='politics-clan'?'Office membership':r.charter==='royal'?'Royal House':'Registered charter'):r.code?codeCell(r.code):'—']));}else for(const [kind,title]of [['clan','Clan founding'],['company','Company clan founding'],['politics-clan','Political clan membership'],['subhouse','Subhouse founding'],['subsidiary','Subsidiary founding'],['politics','Royal appointment'],['xp-correction','XP compensation'],['xp-transfer','Season XP transfer']])setCodes(kind,title,[[title,'—',data[3].reason.message,'—']]); status.textContent=data.every(row=>row.status==='fulfilled')?'Your private reward records are loaded.':'Some reward services are unavailable. Other records remain visible.'; }catch(error){if(active){status.textContent=error.message;groups.clear();paintCodes();orders=[];community.replaceChildren();tokens.replaceChildren();uncertain=true;}}finally{busy=false;if(active){refresh.disabled=false;desk.setLocked(uncertain);}} } diff --git a/website/node/jarvis-management.mjs b/website/node/jarvis-management.mjs index 46edec76..afce4103 100644 --- a/website/node/jarvis-management.mjs +++ b/website/node/jarvis-management.mjs @@ -1,5 +1,6 @@ import {identity} from './auth.mjs'; import {can} from './permissions.mjs'; +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={ @@ -24,7 +25,8 @@ 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); - return reply({section,page,hasMore:rows.length>25,records:rows.slice(0,25)}); + 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); + 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;} }; } diff --git a/website/node/organisation-key-policy.mjs b/website/node/organisation-key-policy.mjs new file mode 100644 index 00000000..99e6e2aa --- /dev/null +++ b/website/node/organisation-key-policy.mjs @@ -0,0 +1,25 @@ +// Single server-side catalogue. Developer capabilities deliberately do not belong +// here: they have no website issuance, receipt or redemption surface. +const player=(prefix,purpose)=>Object.freeze({prefix,purpose,family:'player',operation:'redeem',playerRedeemable:true}); +const system=(prefix,purpose,operation='execute')=>Object.freeze({prefix,purpose,family:'system',operation,playerRedeemable:false}); +export const KEY_TYPES=Object.freeze({ + 'progression-policy':system('PRG','progression-policy-configuration'), + 'gazette-news':system('NEWS','public-news-record','record'), + 'xp-correction':player('XPC','approved-xp-correction'), + 'xp-transfer':player('XPX','season-xp-transfer'), + 'economy-snapshot':system('ECO-SNAP','immutable-economic-record','record'), + 'staff-parent-link':system('STAFF-LINK','protected-parent-link'), + 'entity-transfer':system('XFR','entity-transfer'), + 'quest':system('QST','persistent-quest'), + 'quest-milestone':system('QSM','progression-milestone','record'), + 'staff-office-royal':system('STAFF-POL','protected-office-royal'), + 'staff-company-royal':system('STAFF-COM','company-royal'), + 'clan-subhouse':player('CLAN-SUB','subhouse-founding'), + 'company-subsidiary':player('COM-SUB','subsidiary-founding'), + 'political-clan':system('POL-CLAN','office-membership'), + 'clan-founding':player('CLAN','original-founding'), + 'company-founding':player('COM','original-founding'), + 'political-appointment':player('POL','appointment') +}); +export function keyPolicy(type){const value=KEY_TYPES[type];if(!Object.hasOwn(KEY_TYPES,type))throw TypeError('Unknown organisation key type');return value;} +export function privateKeyPresentation(type){const {family,operation,playerRedeemable}=keyPolicy(type);return {family,operation,playerRedeemable,showCode:playerRedeemable};} diff --git a/website/node/organisation-keys.mjs b/website/node/organisation-keys.mjs index c1acefc0..ed5bfb64 100644 --- a/website/node/organisation-keys.mjs +++ b/website/node/organisation-keys.mjs @@ -1,22 +1,9 @@ +import {KEY_TYPES,keyPolicy} from './organisation-key-policy.mjs'; 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({ - 'economy-snapshot':Object.freeze({prefix:'ECO-SNAP',purpose:'immutable-economic-record'}), - 'staff-parent-link':Object.freeze({prefix:'STAFF-LINK',purpose:'protected-parent-link'}), - 'entity-transfer':Object.freeze({prefix:'XFR',purpose:'entity-transfer'}), - 'quest':Object.freeze({prefix:'QST',purpose:'persistent-quest'}), - 'quest-milestone':Object.freeze({prefix:'QSM',purpose:'progression-milestone'}), - 'staff-office-royal':Object.freeze({prefix:'STAFF-POL',purpose:'protected-office-royal'}), - 'staff-company-royal':Object.freeze({prefix:'STAFF-COM',purpose:'company-royal'}), - '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 ORGANISATION_KEY_TYPES=KEY_TYPES; export const STAFF_OFFICE_ACCOUNT_ID='00000000-0000-4000-8000-000000000041'; 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`, @@ -54,6 +41,9 @@ export function createOrganisationKeys(db,{secret,editions=null}={}){ async inspect(code,{accountId=null,expectedType=null}={}){let parsed,keyType,hash;try{parsed=parseOrganisationCode(code);keyType=Object.keys(ORGANISATION_KEY_TYPES).find(k=>ORGANISATION_KEY_TYPES[k].prefix===parsed.prefix);if(!keyType)return{valid:false,state:'unsupported'};hash=hashOrganisationKey(code,keyType);}catch{return{valid:false,state:'invalid'};}const row=await db.first('SELECT id,account_id,key_type,expires_at,revoked_at,used_at FROM organisation_keys WHERE code_hash=?',[hash]);if(!row||accountId&&row.account_id!==accountId||expectedType&&row.key_type!==expectedType)return{valid:false,state:'invalid'};if(parsed.edition){if(!editions)return{valid:false,state:'unavailable'};const edition=await editions.read(row.id);if(['stage','version','season'].some(k=>edition[k]!==parsed.edition[k]))return{valid:false,state:'invalid'};}return{valid:true,type:row.key_type,purpose:type(row.key_type).purpose,state:row.revoked_at!=null?'revoked':row.used_at!=null?'used':row.expires_at!=null&&Number(row.expires_at)<=Date.now()?'expired':'available'};}, async issue({accountId,keyType,scopeId,expiresAt=null,authorize=null}){ type(keyType); + 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==='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'); 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. @@ -66,9 +56,12 @@ export function createOrganisationKeys(db,{secret,editions=null}={}){ if(keyType==='staff-company-royal'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||!/^company:[a-f0-9-]{36}$/i.test(scopeId)||typeof authorize!=='function'))throw new TypeError('Staff company keys require the system issuer and a company authority adapter'); const code=generateOrganisationKey(keyType),id=randomUUID(),now=Date.now(),issuedEdition=editions?await editions.current():null; try{return await db.transaction(async tx=>{ + if(keyType==='progression-policy')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}); if(['staff-parent-link','entity-transfer'].includes(keyType))await authorize(tx,{accountId,keyType,scopeId}); - if(['quest','quest-milestone'].includes(keyType))await authorize(tx,{accountId,keyType,scopeId}); + if(['quest','quest-milestone'].includes(keyType))await authorize(tx,{accountId,keyType,scopeId,keyId:id}); if(keyType==='staff-office-royal')await authorize(tx,{accountId,keyType,scopeId}); if(keyType==='staff-company-royal')await authorize(tx,{accountId,keyType,scopeId}); if(['clan-subhouse','company-subsidiary'].includes(keyType))await authorize(tx,{accountId,keyType,scopeId}); @@ -98,7 +91,7 @@ export function createOrganisationKeys(db,{secret,editions=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(keyType==='economy-snapshot')throw new OrganisationKeyError('Economic snapshots are sealed records and cannot be redeemed'); + if(keyPolicy(keyType).operation==='record')throw new OrganisationKeyError('Sealed system records cannot be redeemed'); 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=>{ diff --git a/website/tests/organisation-key-policy.test.mjs b/website/tests/organisation-key-policy.test.mjs new file mode 100644 index 00000000..7617835f --- /dev/null +++ b/website/tests/organisation-key-policy.test.mjs @@ -0,0 +1,17 @@ +import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto'; +import {KEY_TYPES,keyPolicy,privateKeyPresentation} from '../node/organisation-key-policy.mjs'; +import {companyFixture} from './company-deed-fixture.mjs';import {STAFF_OFFICE_ACCOUNT_ID} from '../node/organisation-keys.mjs'; +test('every registered key has one explicit family and operation; dev keys are absent',()=>{ + for(const policy of Object.values(KEY_TYPES)){assert(['player','system'].includes(policy.family));assert(['redeem','execute','record'].includes(policy.operation));assert.equal(policy.playerRedeemable,policy.family==='player');assert.equal(Object.isFrozen(policy),true);} + assert.throws(()=>keyPolicy('dev-batch'));assert.throws(()=>keyPolicy('__proto__')); + for(const type of ['economy-snapshot','gazette-news','quest','quest-milestone','political-clan'])assert.equal(privateKeyPresentation(type).showCode,false); + for(const type of ['clan-founding','company-founding','xp-correction','xp-transfer'])assert.equal(privateKeyPresentation(type).showCode,true); +}); +test('news instruments cannot be issued as player rewards or redeemed through consume',async()=>{ + const {db,keys,people}=await companyFixture();try{ + const scopeId='news:'+randomUUID()+':v1'; + await assert.rejects(keys.issue({accountId:people.Owner.id,keyType:'gazette-news',scopeId,authorize:async()=>{}}),/system publication/); + const record=await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'gazette-news',scopeId,authorize:async()=>{}}); + await assert.rejects(keys.consume({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'gazette-news',code:record.code,targetId:randomUUID(),requestId:randomUUID(),apply:async()=>{throw Error('Must not run');}}),/cannot be redeemed/); + }finally{db.close();} +}); diff --git a/website/tests/original-keys.test.mjs b/website/tests/original-keys.test.mjs index 57441407..22efa0d9 100644 --- a/website/tests/original-keys.test.mjs +++ b/website/tests/original-keys.test.mjs @@ -24,6 +24,18 @@ function fixture(){ db.prepare=statement=>{let values=[];return {bind(...v){values=v;return this;},async all(){return {results:await db.query(statement,values)};},async first(){return db.first(statement,values);}};}; return {sql,db,keys,close:()=>sql.close()}; } +test('system office receipts never expose a player redemption secret',async()=>{ + const f=fixture();try{ + f.sql.exec('CREATE TABLE political_office_terms(id TEXT,user_id TEXT,faction TEXT,office TEXT,outcome TEXT,starts_at INT,expires_at INT)'); + const now=Date.now(),expiry=now+60000;await f.db.query("INSERT INTO political_office_terms VALUES(?,?, 'atreides','house_leader','winner',?,?)",[requestId,owner,now-1000,expiry]); + const instrument=await f.keys.issue({accountId:owner,keyType:'political-clan',scopeId:requestId,expiresAt:expiry});assert(instrument.code); + const route=createClanKeyReceipts(f.db,{keys:f.keys,authenticate:async()=>({id:owner})}); + const data=await (await route(new Request('https://cp.dunerealms.com/api/organisation-keys'))).json(); + const receipt=data.keys.find(r=>r.id===instrument.id);assert.equal(receipt.family,'system');assert.equal(receipt.playerRedeemable,false);assert.equal(receipt.code,null); + assert(data.keys.some(r=>r.type==='clan'&&r.family==='player'&&r.code)); + }finally{f.close();} +}); + test('all accounts receive exactly two lifetime grants and retries preserve the original secrets',async()=>{ const f=fixture();try{ assert.deepEqual(await grantCurrentAccountKeys(f.db,f.keys),{accounts:2,created:4,existing:0});