From 144171601e5b761e3b72252c84ea8db805472cda Mon Sep 17 00:00:00 2001 From: unimatrix Date: Wed, 18 Nov 2026 01:40:21 +0000 Subject: [PATCH 1/2] Connect Company clone features and keyed Royal mailbox rollout --- docs/design/COMPANY-CLONE-PARITY.md | 25 +++++++++++ website/control-panel/company-emblems.mjs | 42 +++++++++++++++++++ .../public/clan-dashboard-data.mjs | 6 ++- .../public/codex-code-format.mjs | 4 +- .../public/cp-v2/cp-v2-company-emblem.mjs | 12 ++++++ .../cp-v2/cp-v2-organisation-navigation.mjs | 2 +- .../public/cp-v2/cp-v2-organisation-shell.mjs | 13 +++--- .../public/cp-v2/cp-v2-post-menu.mjs | 4 +- .../public/cp-v2/cp-v2-post-pages.mjs | 4 +- .../control-panel/public/internal-mail.mjs | 8 ++-- .../public/user-service-entry.mjs | 2 +- website/control-panel/server.mjs | 14 +++++-- website/node/company-deed-route.mjs | 5 ++- website/node/company-deeds.mjs | 10 +++++ website/node/company-royal-mail.mjs | 38 +++++++++++++++++ website/node/company-workspace.mjs | 29 ++++++------- website/node/internal-mail-companies.mjs | 30 +++++++++++++ website/node/internal-mail.mjs | 13 ++++-- website/node/member-holdings.mjs | 9 +++- website/node/organisation-keys.mjs | 7 ++++ website/node/political-office-charters.mjs | 32 ++++++++++++++ website/node/politics-workspace.mjs | 2 +- website/node/postbank-service.mjs | 2 +- website/node/public-organisations.mjs | 5 ++- website/node/public/passport.css | 2 + website/node/public/passport.js | 2 +- website/node/server.mjs | 2 + .../scripts/provision-unicorp-royal-mail.mjs | 8 ++++ website/tests/character-identity.test.mjs | 2 + website/tests/company-emblems.test.mjs | 5 +++ website/tests/company-mail.test.mjs | 6 +++ website/tests/company-royal-mail.test.mjs | 3 ++ website/tests/cp-v2-post-menu.test.mjs | 2 +- .../tests/political-office-charters.test.mjs | 3 ++ 34 files changed, 304 insertions(+), 49 deletions(-) create mode 100644 docs/design/COMPANY-CLONE-PARITY.md create mode 100644 website/control-panel/company-emblems.mjs create mode 100644 website/control-panel/public/cp-v2/cp-v2-company-emblem.mjs create mode 100644 website/node/company-royal-mail.mjs create mode 100644 website/node/internal-mail-companies.mjs create mode 100644 website/node/political-office-charters.mjs create mode 100644 website/scripts/provision-unicorp-royal-mail.mjs create mode 100644 website/tests/company-emblems.test.mjs create mode 100644 website/tests/company-mail.test.mjs create mode 100644 website/tests/company-royal-mail.test.mjs create mode 100644 website/tests/political-office-charters.test.mjs diff --git a/docs/design/COMPANY-CLONE-PARITY.md b/docs/design/COMPANY-CLONE-PARITY.md new file mode 100644 index 00000000..231bd0bf --- /dev/null +++ b/docs/design/COMPANY-CLONE-PARITY.md @@ -0,0 +1,25 @@ +# Company clone parity and Royal mailbox rollout + +Company emblems reuse Clan raster normalization, size limits and version checks. +Actual Company and active political deeds appear in holdings; Daughter entities +includes both Company and Clan relationships. These views grant no permissions. + +Protected political offices receive an automatically consumed staff Royal key. +Membership follows current office terms; political decision keys remain separate. + +Company mail reuses the existing mail engine and pinned original origins. +Standalone Companies work without owning a Clan. Created subsidiaries inherit +the mother's mailbox; acquired entities retain their previous mailbox origin. +Company creation triggers provisioning and the existing reconciler retries it. +No message contents are moved or deleted. Full transfer execution is separate work. + +Unicorp's explicitly authorised rollout checks its exact slug/name, active deed, +owner unimatrix999 and previously consumed original COM key. One staff Company +Royal key upgrades its deed and queues a separate mailbox. The mail reconciler +provisions it; repeats create no duplicate key or mailbox. Revocation or lost +Royal standing denies separate mailbox access. Mismatches remain pending rather +than interrupting the website. No Minecraft changes are included. + +scripts/provision-unicorp-royal-mail.mjs checks by default; --apply performs the +approved rollout. CP startup and the mail reconciler use the same implementation. +General Royal mailbox settings and Company claims remain separate pending work. diff --git a/website/control-panel/company-emblems.mjs b/website/control-panel/company-emblems.mjs new file mode 100644 index 00000000..95572dbe --- /dev/null +++ b/website/control-panel/company-emblems.mjs @@ -0,0 +1,42 @@ +import {randomUUID} from 'node:crypto'; +import {identity} from '../node/auth.mjs'; +import {companyId,readCompanyDeed,companyDeedView} from '../node/company-deeds.mjs'; +import {normalizeClanImage} from './clan-emblems.mjs'; +export const COMPANY_EMBLEM_SCHEMA=`CREATE TABLE IF NOT EXISTS site_company_emblems (company_id CHAR(36) PRIMARY KEY,image_blob MEDIUMBLOB NULL,version INT NOT NULL DEFAULT 0,updated_by CHAR(36) NOT NULL,updated_at BIGINT NOT NULL,FOREIGN KEY(company_id) REFERENCES corrino_companies(id))`; +export const companyEmblemUrl=(id,version=0)=>'https://cp.dunerealms.com/api/company-emblems/'+encodeURIComponent(id)+'?v='+Number(version); +const fail=(message,status)=>Object.assign(Error(message),{status}); +function reader(tx){return{prepare(sql){let args=[];return{bind(...values){args=values;return this;},first:()=>tx.first(sql,args),all:async()=>({results:await tx.query(sql,args)})};}};} +// Same raster normalizer, size limits and optimistic versioning as Clan emblems. +// Company authority stays in the Company deed adapter, never Clan SQL. +export function createCompanyEmblems(db,{origin='https://cp.dunerealms.com',authenticate=r=>identity(r,db),normalize=normalizeClanImage}={}){return async request=>{ + const id=new URL(request.url).pathname.split('/').at(-1),reply=(v,status=200)=>Response.json(v,{status,headers:{'Cache-Control':'no-store'}}); + if(!companyId(id))return reply({message:'Company not found.'},404); + try{ + if(request.method==='GET'){ + const row=await db.prepare("SELECT e.image_blob FROM corrino_companies c LEFT JOIN site_company_emblems e ON e.company_id=c.id WHERE c.id=? AND c.status='active'").bind(id).first(); + if(!row)return reply({message:'Company not found.'},404); + return row.image_blob?new Response(row.image_blob,{headers:{'Content-Type':'image/webp','Cache-Control':'public,max-age=60','X-Content-Type-Options':'nosniff'}}):Response.redirect('https://www.dunerealms.com/assets/guild.webp',302); + } + if(!['POST','DELETE'].includes(request.method))return reply({message:'Method not allowed.'},405); + if(request.headers.get('origin')!==origin)throw fail('Origin rejected.',403); + const user=await authenticate(request);if(!user)throw fail('Sign in to manage the company emblem.',401); + const deed=await readCompanyDeed(db,id);if(!companyDeedView(deed,user.id).canManage||deed.company.status!=='active')throw fail('Current company management is required.',403); + const expected=request.headers.get('if-match');if(!/^"\d{1,9}"$/.test(expected||''))throw fail('Reload the current company image before editing.',400); + let bytes=null; + if(request.method==='POST'){ + if(!/^image\/(png|jpeg|webp)$/.test(request.headers.get('content-type')||''))throw fail('Upload a PNG, JPEG or WebP image.',415); + const stream=request.body?.getReader();if(!stream)throw fail('Choose an image.',400);const chunks=[];let size=0; + while(true){const {done,value}=await stream.read();if(done)break;size+=value.length;if(size>2097152){await stream.cancel();throw fail('Maximum image size is 2 MB.',413);}chunks.push(Buffer.from(value));} + try{bytes=await normalize(Buffer.concat(chunks));}catch(error){throw fail(error.message,400);} + } + return await db.transaction(async tx=>{ + await tx.first('SELECT id FROM corrino_companies WHERE id=? FOR UPDATE',[id]);await tx.first('SELECT company_id FROM site_company_deeds WHERE company_id=? FOR UPDATE',[id]); + const fresh=await authenticate(request),current=await readCompanyDeed(reader(tx),id); + if(fresh?.id!==user.id||!companyDeedView(current,user.id).canManage||current.company.status!=='active')throw fail('Company authority or session changed.',403); + const prior=await tx.first('SELECT version FROM site_company_emblems WHERE company_id=? FOR UPDATE',[id]),version=Number(prior?.version||0);if(version!==Number(expected.slice(1,-1)))throw fail('The emblem changed. Reload before replacing it.',409); + const now=Date.now();await tx.query('INSERT INTO site_company_emblems(company_id,image_blob,version,updated_by,updated_at) VALUES(?,?,?,?,?) ON DUPLICATE KEY UPDATE image_blob=VALUES(image_blob),version=VALUES(version),updated_by=VALUES(updated_by),updated_at=VALUES(updated_at)',[id,bytes,version+1,user.id,now]); + await tx.query('INSERT INTO corrino_company_events(id,company_id,action,actor_id,details_json,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),id,bytes?'emblem-uploaded':'emblem-removed',user.id,JSON.stringify({version:version+1}),now]); + return reply({ok:true,version:version+1,url:companyEmblemUrl(id,version+1)}); + }); + }catch(error){return reply({message:error.status?error.message:'The company emblem could not be saved.'},error.status||503);} +};} diff --git a/website/control-panel/public/clan-dashboard-data.mjs b/website/control-panel/public/clan-dashboard-data.mjs index 9332c8f8..0e99f7b7 100644 --- a/website/control-panel/public/clan-dashboard-data.mjs +++ b/website/control-panel/public/clan-dashboard-data.mjs @@ -1,6 +1,6 @@ // Read adapters for existing authorised services. No payment or membership writes. -export function projectClanTreasury(view,clanId){ - const entity=Array.isArray(view?.entities)?view.entities.find(e=>e.kind==='clan'&&e.clanId===clanId):null; +export function projectClanTreasury(view,clanId,{kind='clan'}={}){ + const entity=Array.isArray(view?.entities)?view.entities.find(e=>e.kind===kind&&e[kind==='company'?'companyId':'clanId']===clanId):null; if(!entity)throw Error('Clan bank access unavailable'); const accounts=(entity.accounts||[]).filter(a=>a.state==='active'&&a.type==='105').map(a=>{ if(typeof a.id!=='string'||!a.id||!/^DR\d{14}$/.test(a.number||'')||typeof a.available!=='string'||!/^-?\d+\.\d{2}$/.test(a.available))throw Error('Clan funds were not confirmed'); @@ -12,3 +12,5 @@ export async function loadClanTreasury(clanId,{fetcher=fetch}={}){return project export async function loadClanMail({fetcher=fetch,clanId}={}){const result=await read(fetcher,'/api/internal-mail/messages/list',{scope:'clan',...(clanId?{clanId}:{}),folder:'INBOX',offset:0,limit:1,unread:true});if(!Number.isSafeInteger(result.total)||result.total<0)throw Error('Unread count unavailable');return result.total;} export async function loadClanClaims(clanId,{fetcher=fetch}={}){return (await read(fetcher,'/api/v1/claims/overview?clanId='+encodeURIComponent(clanId))).claims;} + +export async function loadCompanyTreasury(companyId,{fetcher=fetch}={}){return projectClanTreasury(await read(fetcher,'/api/bank/overview'),companyId,{kind:'company'});} diff --git a/website/control-panel/public/codex-code-format.mjs b/website/control-panel/public/codex-code-format.mjs index be7bc8a3..d0a9b579 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=/^(CLAN-SUB|COM-SUB|POL-CLAN|CLAN|COM|POL)-([A-F0-9]{48})$/; -const versioned=/^(CLAN-SUB|COM-SUB|POL-CLAN|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=/^(STAFF-COM|STAFF-POL|CLAN-SUB|COM-SUB|POL-CLAN|CLAN|COM|POL)-([A-F0-9]{48})$/; +const versioned=/^(STAFF-COM|STAFF-POL|CLAN-SUB|COM-SUB|POL-CLAN|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-company-emblem.mjs b/website/control-panel/public/cp-v2/cp-v2-company-emblem.mjs new file mode 100644 index 00000000..6f36c86c --- /dev/null +++ b/website/control-panel/public/cp-v2/cp-v2-company-emblem.mjs @@ -0,0 +1,12 @@ +import {element as el} from './cp-v2-page-template.mjs'; +export function mountCompanyEmblem(host,{record,onSaved=()=>{},fetcher=fetch}){ + const controller=new AbortController();let active=true,version=record.emblemVersion||0,busy=false,hasEmblem=!!record.hasEmblem; + const box=el('section',undefined,'organisation-settings-card'),form=el('form',undefined,'organisation-settings-form'),image=el('img'),file=el('input'),save=el('button','Upload emblem'),remove=el('button','Use placeholder'),status=el('p'); + image.src=record.emblem;image.alt=record.name+' emblem';image.width=128;image.height=128;image.style.objectFit='contain';file.type='file';file.accept='image/png,image/jpeg,image/webp';file.setAttribute('aria-label','Company emblem image');save.type='submit';remove.type='button';status.setAttribute('role','status'); + box.append(el('h3','Company emblem'),image);form.append(file,el('p','Still PNG, JPEG or WebP · maximum 2 MB · displayed on company pages, profiles and the directory.'),save,remove,status);box.append(form);const target=host.querySelector('[role=tabpanel][id$=identity-panel] .organisation-settings-grid')||host;target.append(box); + const lock=()=>{file.disabled=save.disabled=busy||!record.canManage;remove.disabled=busy||!record.canManage||!hasEmblem;};lock(); + async function send(method){if(busy||!record.canManage)return;const input=file.files[0];if(method==='POST'&&(!input||input.size>2097152)){status.textContent='Choose an image of at most 2 MB.';return;}busy=true;lock();status.textContent='Saving…';try{ + const response=await fetcher('/api/company-emblems/'+encodeURIComponent(record.id),{method,credentials:'same-origin',cache:'no-store',signal:controller.signal,headers:{'If-Match':'"'+version+'"',...(method==='POST'?{'Content-Type':input.type}:{})},...(method==='POST'?{body:input}:{})}),data=await response.json();if(!response.ok)throw Error(data.message||'Image could not be saved.');if(!active)return;version=data.version;hasEmblem=method==='POST';image.src=data.url;Object.assign(record,{emblem:data.url,emblemVersion:version,hasEmblem});onSaved(data);status.textContent='Company emblem saved.'; + }catch(error){if(active)status.textContent=error.message;}finally{busy=false;if(active)lock();}} + form.onsubmit=e=>{e.preventDefault();void send('POST');};remove.onclick=()=>void send('DELETE');return()=>{active=false;controller.abort();box.remove();}; +} diff --git a/website/control-panel/public/cp-v2/cp-v2-organisation-navigation.mjs b/website/control-panel/public/cp-v2/cp-v2-organisation-navigation.mjs index 0cc5b2b7..18557376 100644 --- a/website/control-panel/public/cp-v2/cp-v2-organisation-navigation.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-organisation-navigation.mjs @@ -7,7 +7,7 @@ export function organisationPage(hash=''){ if(typeof hash!=='string'||hash.length>300)return null; const page=hash.replace(/^#/,'').split('/').at(-1),aliases={'politics-overview':'overview','dashboard':'overview','company-claims':'claims'}; if(Object.hasOwn(aliases,page))return aliases[page]; - return [...ORGANISATION_MENU_GROUPS.flatMap(([,items])=>items.map(([id])=>id)),'people','applications'].includes(page)?page:null; + return [...ORGANISATION_MENU_GROUPS.flatMap(([,items])=>items.map(([id])=>id)),'people','applications','mail'].includes(page)?page:null; } export function organisationMenuItems(kind){ if(!['company','politics'].includes(kind))throw TypeError('Unknown organisation workspace'); diff --git a/website/control-panel/public/cp-v2/cp-v2-organisation-shell.mjs b/website/control-panel/public/cp-v2/cp-v2-organisation-shell.mjs index a8ef2cdb..08acdce1 100644 --- a/website/control-panel/public/cp-v2/cp-v2-organisation-shell.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-organisation-shell.mjs @@ -1,3 +1,5 @@ +import {loadCompanyTreasury} from '../clan-dashboard-data.mjs'; +import {mountCompanyEmblem} from './cp-v2-company-emblem.mjs'; import {mountCompanyRegistration,mountCompanyDeed,mountCompanyRoster} from './cp-v2-company-deed.mjs'; import {mountExchangeDesign} from './cp-v2-exchange-design.mjs'; import {mountOrganisationEditor} from '../organisation-editor.mjs'; @@ -20,7 +22,7 @@ export function startOrganisationCP(kind){ const go=id=>{location.hash=prefix+'/'+id;}; function measure(){if(stopped||parent===window)return;const height=Math.ceil(document.body.getBoundingClientRect().height)+2;if(height!==lastHeight&&height>=100&&height<=200000){lastHeight=height;parent.postMessage({type:'dune-embed-size',height},outer);}} const observer=new ResizeObserver(()=>requestAnimationFrame(measure));observer.observe(document.body);const onMeasure=e=>{if(e.source===parent&&e.origin===outer&&e.data?.type==='dune-embed-measure')measure();};window.addEventListener('message',onMeasure); - const mapCompanies=data=>data.companies.map(c=>({...c,emblem:assets+'guild.webp',members:c.members||[...new Set([c.founder_name,c.ceo_name].filter(Boolean))].map(username=>({username,role:'leadership'}))})); + const mapCompanies=data=>data.companies.map(c=>({...c,emblem:c.emblem||assets+'guild.webp',members:c.members||[...new Set([c.founder_name,c.ceo_name].filter(Boolean))].map(username=>({username,role:'leadership'}))})); const route=()=>organisationPage(location.hash); const onRoute=()=>{if(!company||!ready){render();return;}const turn=++routeTurn;dispose();dispose=()=>{};content.replaceChildren(el('p','Opening your company…'));const id=new URL(location.href).searchParams.get('company');fetch('/api/companies/workspace'+(id?'?company='+encodeURIComponent(id):''),{credentials:'same-origin',cache:'no-store'}).then(async response=>{const data=await response.json();if(!response.ok)throw Error(data.message||'Company workspace unavailable.');if(stopped||turn!==routeTurn)return;records=mapCompanies(data);selected=data.selected;render();}).catch(error=>{if(!stopped&&turn===routeTurn)content.replaceChildren(el('p',error.message));});}; function pending(host,title,copy){const box=el('section',undefined,'organisation-settings-card');box.append(el('h3',title),el('p',copy),reference());host.append(box);} @@ -38,10 +40,11 @@ export function startOrganisationCP(kind){ const navigate={onMembers:()=>go('people'),onRequests:()=>go('applications')}; if(page==='overview'&&(!company&&!route()&&location.hash&& !location.hash.startsWith('#household/'))){const old=location.hash.slice(1).split('/').at(-1);if(old&&!['politics-overview','dashboard'].includes(old)){dispose=mountPoliticsPage(host,old);return;}} if(page==='overview'){ - host.append(createOrganisationDashboard({kind,organisation:{...record,tag:record.tag||record.slug||'REGISTERED',emblem:record.emblem||assets+fallback,homeworldName:record.homeworldName||(company?'Company register':'Political office'),titles:{officeholder:'Office deed holder'}},members:record.members||[],canReview:company&&!!record.canReview,requests:company?record.requests||[]:[],role:record.role==='Founder'||record.role==='CEO'?'owner':record.role,memberSummary:company?(record.memberCount==null?'Verified leadership':record.memberCount+' / '+record.memberLimit+' registered members'):undefined,loadMotd:record.role==='visitor'?undefined:async()=>(await loadSettings()).motd,activityStatus:'unavailable',links:{claims:'#'+prefix+'/claims'},...navigate})); + host.append(createOrganisationDashboard({kind,organisation:{...record,tag:record.tag||record.slug||'REGISTERED',emblem:record.emblem||assets+fallback,homeworldName:record.homeworldName||(company?'Company register':'Political office'),titles:{officeholder:'Office deed holder'}},members:record.members||[],canReview:company&&!!record.canReview,requests:company?record.requests||[]:[],role:record.role==='Founder'||record.role==='CEO'?'owner':record.role,memberSummary:company?(record.memberCount==null?'Verified leadership':record.memberCount+' / '+record.memberLimit+' registered members'):undefined,loadMotd:record.role==='visitor'?undefined:async()=>(await loadSettings()).motd,activityStatus:'unavailable',loadTreasury:company&&record.canManage?()=>loadCompanyTreasury(record.id):undefined,loadMailbox:company&&record.canManage?async()=>{const r=await fetch('/api/internal-mail/messages/list',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({scope:'company',companyId:record.id,folder:'INBOX',offset:0,limit:1,unread:true}),cache:'no-store'});const data=await r.json();if(!r.ok)throw Error('Mailbox unavailable');return data.total;}:undefined,links:{mail:'#'+prefix+'/mail',claims:'#'+prefix+'/claims'},...navigate})); }else if(page==='settings'){ - const sections=[['Identity & homeworld','Registered organisation identity.',record.name],['Message of the day','Organisation messages will use the shared service.',null],['Ownership deed & dynasty',company?'Company clan charter · COM keys.':'Protected political clan charter · political-clan keys. Political decision keys are separate.',record.membership?'Active office deed · ends '+new Date(record.membership.expiresAt).toLocaleString('en-GB'):'No new charter entitlement is inferred.'],['Claim charter & capacity','The shared claim model will be connected to this organisation.',null],['Relations & subhouses','The shared parent-deed mechanism will manage subordinate organisations.',null]].map(([title,description,text])=>({title,description,content:text?el('p',text):null,pending:!text}));host.append(createOrganisationSettings(sections));dispose=mountOrganisationEditor(host,{kind,id:record.id,onSaved:data=>Object.assign(record,{name:data.name,description:data.description,motd:data.motd})});if(company){const stopEditor=dispose,stopDeed=mountCompanyDeed(host,{id:record.id,onChanged:()=>location.reload()});dispose=()=>{stopEditor();stopDeed();};}const note=el('p',company?'COM clan keys belong to company charters.':'Political-clan keys belong to protected organisation deeds; POL decision keys remain separate.');host.append(note); + const sections=[['Identity & homeworld','Registered organisation identity.',record.name],['Message of the day','Organisation messages will use the shared service.',null],['Ownership deed & dynasty',company?'Company clan charter · COM keys.':'Protected political clan charter · political-clan keys. Political decision keys are separate.',record.membership?'Active office deed · ends '+new Date(record.membership.expiresAt).toLocaleString('en-GB'):'No new charter entitlement is inferred.'],['Claim charter & capacity','The shared claim model will be connected to this organisation.',null],['Relations & subhouses','The shared parent-deed mechanism will manage subordinate organisations.',null]].map(([title,description,text])=>({title,description,content:text?el('p',text):null,pending:!text}));host.append(createOrganisationSettings(sections));dispose=mountOrganisationEditor(host,{kind,id:record.id,onSaved:data=>Object.assign(record,{name:data.name,description:data.description,motd:data.motd})});if(company){const stopEditor=dispose,stopEmblem=mountCompanyEmblem(host,{record}),stopDeed=mountCompanyDeed(host,{id:record.id,onChanged:()=>location.reload()});dispose=()=>{stopEditor();stopEmblem();stopDeed();};}const note=el('p',company?'COM clan keys belong to company charters.':'Political-clan keys belong to protected organisation deeds; POL decision keys remain separate.');host.append(note); Promise.resolve().then(async()=>{const r=await fetch('/api/organisation-keys',{credentials:'same-origin',cache:'no-store'});if(!r.ok)throw Error();const data=await r.json();if(turn!==generation||stopped)return;const rows=(data.keys||[]).filter(k=>company?k.type==='company':k.type==='politics-clan');const box=el('section',undefined,'organisation-settings-card');box.append(el('h3',noun+' clan keys'));for(const key of rows){box.append(el('p',key.status+(key.code?' · '+key.code:'')));}if(!rows.length)box.append(el('p','No organisation-clan keys are present in your private register.'));host.append(box);}).catch(()=>{if(turn===generation)note.append(el('span',' The private key register is unavailable.'));}); + }else if(page==='mail'&&company){const frame=el('iframe');frame.title=record.name+' correspondence';frame.src='/user-service.html?service=inbox&company='+encodeURIComponent(record.id)+'#company-inbox';frame.style.cssText='width:100%;min-height:900px;border:0';host.append(frame); }else if(page==='claims'){dispose=mountClaims(host,{kind:company?'company':'protected',name:record.name});} else if(page==='boards'){if(company)dispose=mountNativeService(host,'company-boards',{singleHeading:true,organisationId:record.id});else dispose=mountNativeService(host,'election-boards',{singleHeading:true});} @@ -56,5 +59,5 @@ export function startOrganisationCP(kind){ const mobile=()=>{const open=left.classList.toggle('open');right.classList.toggle('open',open);document.querySelector('#mobile-menu').setAttribute('aria-expanded',String(open));};document.querySelector('#mobile-menu').onclick=mobile;window.addEventListener('hashchange',onRoute);watchMenuHighlights(document.body); window.addEventListener('pagehide',()=>{stopped=true;generation++;dispose();observer.disconnect();window.removeEventListener('hashchange',onRoute);window.removeEventListener('message',onMeasure);},{once:true}); startCPAuthentication(async account=>{user=account;if(!user.permissions?.includes('web.menu.game')){content.replaceChildren(el('p','Game account access is required.'));return;}const id=new URL(location.href).searchParams.get(company?'company':'office');try{const response=await fetch(company?'/api/companies/workspace'+(id?'?company='+encodeURIComponent(id):''):'/api/politics/workspace'+(id?'?office='+encodeURIComponent(id):''),{credentials:'same-origin',cache:'no-store'}),data=await response.json();if(!response.ok)throw Error(data.message||'Organisation unavailable.');if(stopped)return;records=company?mapCompanies(data):data.organisations;selected=data.selected;ready=true;render();}catch(e){content.replaceChildren(el('p',e.message),reference());}}); -} - +} + diff --git a/website/control-panel/public/cp-v2/cp-v2-post-menu.mjs b/website/control-panel/public/cp-v2/cp-v2-post-menu.mjs index 3a905a4c..1212d5ea 100644 --- a/website/control-panel/public/cp-v2/cp-v2-post-menu.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-post-menu.mjs @@ -2,9 +2,9 @@ const item=(id,label,artwork)=>({id,label,artwork,viewPermission:'web.mail.inter export function mailboxMenu(data){ if(!data||data.eligible!==true)throw Error('Internal mailbox access could not be confirmed.'); const rows=[item('mail-inbox','Inbox','mail-stamp-personal.svg')]; - if(typeof data.clan?.name==='string'&&data.clan.name.trim())rows.push(item('clan-inbox',data.clan.name,'mail-stamp-clan.svg')); + if(typeof data.clan?.name==='string'&&data.clan.name.trim())rows.push(item('clan-inbox','Clan / Company','mail-stamp-clan.svg')); if(typeof data.faction?.name==='string'&&data.faction.name.trim())rows.push(item('faction-inbox',data.faction.name,'mail-stamp-faction.svg')); - if(data.imperial===true)rows.push(item('imperial-inbox','Imperial','mail-stamp-imperial.svg')); + if(data.imperial===true)rows.push(item('imperial-inbox','Office mail','mail-stamp-imperial.svg')); if(data.staff===true)rows.push(item('staff-inbox','Staff','mail-stamp-staff.svg')); rows.push(item('mail-request','Request inbox','mail-stamp-personal.svg')); return rows; diff --git a/website/control-panel/public/cp-v2/cp-v2-post-pages.mjs b/website/control-panel/public/cp-v2/cp-v2-post-pages.mjs index 8ff68a5b..6ee67367 100644 --- a/website/control-panel/public/cp-v2/cp-v2-post-pages.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-post-pages.mjs @@ -2,9 +2,9 @@ import {createCPV2Page,element as el} from './cp-v2-page-template.mjs'; import {mountNativeService} from './cp-v2-native-services.mjs'; import {mountDesignPage} from './cp-v2-design-pages.mjs'; export const POST_IMPORTS=Object.freeze({ - 'clan-inbox':{service:'post-mail',title:'Clan Inbox',folder:'INBOX',initialTab:'clan-inbox'}, + 'clan-inbox':{service:'post-mail',title:'Clan / Company mail',folder:'INBOX',initialTab:'clan-inbox'}, 'faction-inbox':{service:'post-mail',title:'House Inbox',folder:'INBOX',initialTab:'faction-inbox'}, - 'imperial-inbox':{service:'post-mail',title:'Imperial Inbox',folder:'INBOX',initialTab:'imperial-inbox'}, + 'imperial-inbox':{service:'post-mail',title:'Office mail',folder:'INBOX',initialTab:'imperial-inbox'}, 'staff-inbox':{service:'post-mail',title:'Staff Inbox',folder:'INBOX',initialTab:'staff-inbox'}, 'mail-inbox':{service:'post-mail',title:'Incoming Dispatches',folder:'INBOX'}, 'shared-inbox':{service:'post-mail',title:'Incoming Dispatches',folder:'INBOX'}, diff --git a/website/control-panel/public/internal-mail.mjs b/website/control-panel/public/internal-mail.mjs index 2b73d320..416942a0 100644 --- a/website/control-panel/public/internal-mail.mjs +++ b/website/control-panel/public/internal-mail.mjs @@ -9,12 +9,12 @@ const factionTags=['Faction','Council','Members','Elections','Announcements','Di const imperialTags=['Imperial','Council','Decrees','Appointments','Diplomacy','Orders','Legal','System']; const staffTags=['Staff','Mail Reports','Legal','Support','Moderation','Administration','Announcements','System']; function availableTags(view){const base=view.scope==='clan'?clanTags:view.scope==='staff'?staffTags:view.scope==='faction'?factionTags:view.scope==='imperial'?imperialTags:defaults;const shared=new Set([...clanTags,'House','Elections','Appointments','Rallies','Transport','Faction Bank','Faction Kit']);return [...new Set([...base,...view.tags])].filter(tag=>view.scope!=='personal'||!shared.has(tag)||base.includes(tag));} -async function api(path,body){if(body&&/^(messages|folders|attachments)\//.test(path))body={...body,scope:body.scope||views.get(location.hash.slice(1))?.scope||'personal'};const version=generation,r=await fetch('/api/internal-mail/'+path,{method:body===undefined?'GET':'POST',headers:body===undefined?{}:{'Content-Type':'application/json'},...(body===undefined?{}:{body:JSON.stringify(body)}),cache:'no-store'});if(version!==generation)throw Error('Session changed.');const value=await r.json();if(!r.ok)throw Error(value.message||'Mail operation failed.');return value;} +async function api(path,body){if(body?.scope==='company')body={...body,companyId:body.companyId||account?.company?.id};if(path==='me'){const company=new URL(location.href).searchParams.get('company');if(company)path+='?company='+encodeURIComponent(company);}if(body&&/^(messages|folders|attachments)\//.test(path))body={...body,scope:body.scope||views.get(location.hash.slice(1))?.scope||'personal'};const version=generation,r=await fetch('/api/internal-mail/'+path,{method:body===undefined?'GET':'POST',headers:body===undefined?{}:{'Content-Type':'application/json'},...(body===undefined?{}:{body:JSON.stringify(body)}),cache:'no-store'});if(version!==generation)throw Error('Session changed.');const value=await r.json();if(!r.ok)throw Error(value.message||'Mail operation failed.');return value;} function field(form,label,type='text'){const box=el('label',label),input=el(type==='textarea'?'textarea':'input');if(type!=='textarea')input.type=type;box.append(input);form.append(box);return input;} function status(node,text){node.textContent=text;node.setAttribute('role','status');} function clearSecret(){if(secret){secret.value='';secret.hidden=true;}clearTimeout(secretTimer);} function dialog(title){const d=el('dialog',undefined,'internal-mail-dialog');d.append(el('h2',title));const close=button('Close',()=>d.close());d.append(close);d.addEventListener('close',()=>d.remove(),{once:true});document.body.append(d);d.showModal();return d;} -function reference(view,item){return{folder:view.folder,uid:item.uid,uidValidity:view.validity,scope:view.scope||'personal'};} +function reference(view,item){return{folder:view.folder,uid:item.uid,uidValidity:view.validity,scope:view.scope||'personal',...(view.scope==='company'?{companyId:account?.company?.id}:{})};} function plainHtml(html){const doc=new DOMParser().parseFromString(html,'text/html');for(const n of doc.querySelectorAll('script,style,iframe,object'))n.remove();return doc.body.textContent||'';} function openWebmail(url){const a=el('a','Open webmail ↗');a.href=url||'https://www.lgbbenelux.org/webmail/';a.target='_blank';a.rel='noopener noreferrer';return a;} async function attachment(view,item,part){try{const version=generation,r=await fetch('/api/internal-mail/attachments/get',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({...reference(view,item),partId:part.partId}),cache:'no-store'});if(version!==generation)return;if(!r.ok){const value=await r.json();throw Error(value.message);}const url=URL.createObjectURL(await r.blob()),a=el('a');a.href=url;a.download=part.filename||'attachment';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}catch(e){status(view.notice,e.message);}} @@ -43,7 +43,7 @@ function moveMessage(view,item,row){row.querySelector('.internal-mail-move')?.re function updateBulk(view){const count=view.selected.size;view.bulkMove.disabled=!count||view.bulkBusy;view.bulkCount.textContent=count+' selected';const checks=[...view.list.querySelectorAll('.internal-mail-message-check')];view.selectAll.checked=!!checks.length&&checks.every(c=>c.checked);view.selectAll.indeterminate=checks.some(c=>c.checked)&&!view.selectAll.checked;} function bulkTools(view){const box=el('div',undefined,'internal-mail-bulk'),all=el('label','Select all'),check=el('input'),destination=el('select'),count=el('span','0 selected');check.type='checkbox';check.setAttribute('aria-label','Select all messages on this page');all.prepend(check);destination.setAttribute('aria-label','Move selected messages to folder');const move=button('Move selected',async()=>{if(!view.selected.size||!destination.value||view.bulkBusy)return;view.bulkBusy=true;updateBulk(view);const version=generation,sourceFolder=view.folder,uidValidity=view.validity,sourceScope=view.scope||'personal',target=destination.value,rows=[...view.selected.values()];let moved=0,failed=0;for(const item of rows){if(version!==generation)break;try{await api('messages/move',{folder:sourceFolder,uid:item.uid,uidValidity,destination:target,scope:sourceScope});moved++;}catch{failed++;}}view.bulkBusy=false;if(version!==generation)return;await loadMessages(view,false);status(view.notice,moved+' message'+(moved===1?'':'s')+' moved.'+(failed?' '+failed+' could not be moved. Select those messages again to retry.':''));});move.disabled=true;check.onchange=()=>{for(const c of view.list.querySelectorAll('.internal-mail-message-check')){c.checked=check.checked;c.dispatchEvent(new Event('change'));}};box.append(count,all,destination,move);view.bulk=box;view.selectAll=check;view.bulkDestination=destination;view.bulkMove=move;view.bulkCount=count;return box;} async function loadMessages(view,clearNotice=true){if(!account?.active)return;const version=generation;view.selected.clear();view.list.replaceChildren(el('p','Loading messages…'));if(clearNotice)status(view.notice,'');try{const value=await api('messages/list',{folder:view.folder,offset:view.offset,limit:25,unread:view.unread.checked,...(view.filter.value?{tag:view.filter.value}:{}),sort:view.sort.value,scope:view.scope});if(version!==generation)return;view.validity=value.uidValidity;view.tags=[...new Set([...view.tags,...(value.tags||[])])];view.folderNames=value.folders;view.bulkDestination.replaceChildren();for(const name of value.folders)if(name!==view.folder)view.bulkDestination.add(new Option(name==='INBOX'?'Inbox':name,name));paintFolders(view);const selected=view.filter.value;view.filter.replaceChildren(new Option('All tags',''));for(const tag of [...new Set([...defaults,...view.tags])])view.filter.add(new Option(tag,tag));view.filter.value=selected;paintTagFilters(view);view.list.replaceChildren();for(const item of value.items){const row=el('article',undefined,'internal-mail-row'+(!item.seen?' is-unread':'')),open=button('',()=>{view.list.querySelectorAll('.is-selected').forEach(n=>n.classList.remove('is-selected'));row.classList.add('is-selected');void read(view,item,view.reading);}),sender=el('strong',displayMail(item.senderName||item.sender),'internal-mail-sender'),subject=el('span',displayMail(item.subject||'(No subject)'),'internal-mail-subject'),date=el('time',item.date);open.className='internal-mail-row-open';open.append(sender,subject,date);const selection=el('label',undefined,'internal-mail-row-select'),check=el('input');check.type='checkbox';check.className='internal-mail-message-check';check.setAttribute('aria-label','Select message: '+displayMail(item.subject||'(No subject)'));selection.append(check);row.append(selection,open);check.onchange=()=>{if(check.checked)view.selected.set(item.uid,item);else view.selected.delete(item.uid);row.classList.toggle('is-bulk-selected',check.checked);updateBulk(view);};for(const tag of item.tags||[])row.append(el('span',tagLabel(view,tag),'internal-mail-tag tone-'+tagTone(tag)));view.list.append(row);}if(!value.items.length)view.list.append(el('p','No messages in this folder.'));view.counter.textContent=value.total?String(view.offset+1)+'–'+Math.min(view.offset+25,value.total)+' of '+value.total:'No messages';view.prev.disabled=view.offset===0;view.next.disabled=view.offset+25>=value.total;view.loaded=true;updateBulk(view);window.dispatchEvent(new Event("dune:mail-changed"));}catch(e){if(version===generation)status(view.notice,e.message);}} -function mailboxTabs(view){const nav=el('nav',undefined,'internal-mail-mailbox-tabs');nav.setAttribute('aria-label','Mailbox');for(const [page,label,asset]of [['shared-inbox','INBOX','mail-stamp-personal.svg'],...(account?.clan?[['clan-inbox',account.clan.name,'mail-stamp-clan.svg']]:[]),...(account?.faction?[['faction-inbox',account.faction.name,'mail-stamp-faction.svg']]:[]),...(account?.imperial?[['imperial-inbox','Imperial','mail-stamp-imperial.svg']]:[]),...(account?.staff?[['staff-inbox','Staff','mail-stamp-staff.svg']]:[])]){const link=el('a'),image=el('img');image.src='/assets/'+asset;image.alt='';image.width=34;image.height=34;link.href='#'+page;link.append(image,el('span',label));if(page===view.section.id)link.setAttribute('aria-current','page');nav.append(link);}return nav;} +function mailboxTabs(view){const nav=el('nav',undefined,'internal-mail-mailbox-tabs');nav.setAttribute('aria-label','Mailbox');for(const [page,label,asset]of [['shared-inbox','INBOX','mail-stamp-personal.svg'],...(account?.company?[['company-inbox',account.company.name,'mail-stamp-clan.svg']]:[]),...(account?.clan?[['clan-inbox',account.clan.name,'mail-stamp-clan.svg']]:[]),...(account?.faction?[['faction-inbox',account.faction.name,'mail-stamp-faction.svg']]:[]),...(account?.imperial?[['imperial-inbox','Imperial','mail-stamp-imperial.svg']]:[]),...(account?.staff?[['staff-inbox','Staff','mail-stamp-staff.svg']]:[])]){const link=el('a'),image=el('img');image.src='/assets/'+asset;image.alt='';image.width=34;image.height=34;link.href='#'+page;link.append(image,el('span',label));if(page===view.section.id)link.setAttribute('aria-current','page');nav.append(link);}return nav;} function mountView(section,title,scope='personal'){if(views.has(section.id))return views.get(section.id);section.dataset.internalMail='true';const pageBanner=section.querySelector(':scope > .cp-user-page-hero')||document.querySelector('#shared-inbox > .cp-user-page-hero')?.cloneNode(true);if(pageBanner){section.classList.add('politics-page');pageBanner.classList.add('internal-mail-page-banner');}const content=el('div',undefined,'internal-mail-workspace'),hero=el('header',undefined,'internal-mail-hero'),art=el('img');art.src='/assets/imperial-post-logo.svg';art.className='internal-mail-brand-logo';art.alt='';art.width=88;art.height=88;const intro=el('div');intro.append(el('p','THE IMPERIAL POST','internal-mail-eyebrow'),el('h2',title),el('p','Your private messages, dispatches and ticket updates.'));hero.append(art,...(scope==='personal'?[]:[intro]));const address=el('p',undefined,'internal-mail-account'),notice=el('p'),tools=el('div',undefined,'internal-mail-actions'),tagBar=el('details',undefined,'internal-mail-tag-bar'),sort=el('select'),filter=el('select'),unread=el('input'),list=el('div',undefined,'internal-mail-list'),reading=el('div',undefined,'internal-mail-reading-stack'),counter=el('span');reading.setAttribute('aria-label','Message reading pane');reading.append(el('p','Select a message to read it.'));filter.setAttribute('aria-label','Filter by tag');filter.add(new Option('All tags',''));unread.type='checkbox';const unreadLabel=el('label');unreadLabel.append(unread,document.createTextNode('Unread only'));const inboxCard=el('section',undefined,'internal-mail-inbox-card');inboxCard.setAttribute('aria-label','Inbox and mail folders');sort.setAttribute('aria-label','Sort messages');for(const [value,label]of [['newest','Newest first'],['oldest','Oldest first'],['sender','Sender'],['subject','Subject']])sort.add(new Option(label,value));const view={section,content,inboxCard,tagBar,sort,address,notice,list,reading,counter,filter,unread,selected:new Map(),bulkBusy:false,scope,folder:'INBOX',offset:0,tags:[]};tools.append(button('✉ Compose',()=>compose(view)),button('Refresh',()=>loadMessages(view)),sort,unreadLabel);const shell=el('div',undefined,'internal-mail-shell'),folders=el('nav',undefined,'internal-mail-folders');folders.setAttribute('aria-label','Mail folders');view.folders=folders;paintFolders(view);paintTagFilters(view);const main=el('div',undefined,'internal-mail-main'),panes=el('div',undefined,'internal-mail-panes');panes.append(list,reading);const pager=el('div',undefined,'internal-mail-actions');view.prev=button('Previous',()=>{view.offset=Math.max(0,view.offset-25);void loadMessages(view);});view.next=button('Next',()=>{view.offset+=25;void loadMessages(view);});pager.append(view.prev,counter,view.next);main.append(bulkTools(view),list,pager);shell.append(folders,main);inboxCard.append(tagBar,mailboxTabs(view),tools,notice,shell);const provider=el('footer',undefined,'internal-mail-provider'),providerLogo=el('img');providerLogo.src='/assets/spost-logo-v1.svg';providerLogo.alt='Spost';providerLogo.width=130;providerLogo.height=43;const brands=el('div',undefined,'internal-mail-provider-brands'),parentBrand=el('a',undefined,'internal-mail-parent-brand'),groupLogo=el('img');parentBrand.href='https://www.dunerealms.com/corrino-group.html';groupLogo.src='/assets/corrino-group-v4.png';groupLogo.alt='Corrino Group';groupLogo.className='internal-mail-group-logo';groupLogo.width=116;groupLogo.height=28;parentBrand.append(el('span','part of'),groupLogo);brands.append(providerLogo,parentBrand);provider.append(el('span','Service provided by Spost'),brands);content.append(hero,address,inboxCard,reading,el('p','Messages expire after 30 days · 100 MiB storage · Private tags','internal-mail-retention'),provider);section.replaceChildren(...(pageBanner?[pageBanner]:[]),content);for(const control of [sort,unread])control.onchange=()=>{view.offset=0;void loadMessages(view);};views.set(section.id,view);return view;} function forwardingSettings(data){const box=el('section',undefined,'internal-mail-settings'),form=el('form'),address=field(form,'Forwarding email address','email'),note=el('p');address.value=data.forwardingAddress||'';address.autocomplete='email';box.append(el('h3','Forward internal mail'),el('p','Keep a copy in your internal inbox and forward new mail to your verified Support notification email. Verify the address in Account security first.'));const save=el('button','Save forwarding'),remove=button('Disable forwarding',()=>change(null));save.type='submit';form.append(save,remove,note);async function change(value){save.disabled=remove.disabled=true;try{const result=await api('forwarding',{address:value});address.value=result.forwardingAddress||'';status(note,result.forwardingAddress?'Forwarding enabled. A copy stays in your internal inbox.':'Forwarding disabled. Messages remain in your internal inbox.');}catch(e){status(note,e.message);}finally{save.disabled=remove.disabled=false;}}form.onsubmit=e=>{e.preventDefault();if(address.reportValidity())void change(address.value);};box.append(form);return box;} function settings(data){const parent=document.getElementById('security');if(!parent)return;settingsBox?.remove();settingsBox=el('div',undefined,'internal-mail-settings');settingsBox.append(el('h3','Internal mailbox'),el('p',data.active?'Your private DuneRealms inbox':'Internal mailbox is not ready yet.'));if(!data.active){settingsBox.append(el('p','Mailbox setup will retry automatically.'));parent.append(settingsBox);return;} @@ -51,7 +51,7 @@ function settings(data){const parent=document.getElementById('security');if(!par async function passwordAction(action){const pw=current.value;clearSecret();current.value='';const buttons=[...form.querySelectorAll('button')];buttons.forEach(b=>b.disabled=true);try{if(!pw)throw Error('Enter your website password first.');if(action==='reveal'){const value=await api('password/reveal',{currentPassword:pw});secret.value=value.password;secret.hidden=false;secretTimer=setTimeout(clearSecret,60000);status(note,'Mailbox password shown for 60 seconds. It is separate from your website password.');}else{await api('password',{currentPassword:pw,requestId:crypto.randomUUID(),...(action==='generate'?{generate:true}:{newPassword:fresh.value})});fresh.value='';status(note,'Mailbox password changed. Inbox access automatically uses the new credential.');if(action==='generate'){const value=await api('password/reveal',{currentPassword:pw});secret.value=value.password;secret.hidden=false;secretTimer=setTimeout(clearSecret,60000);}}}catch(e){status(note,e.message);}finally{buttons.forEach(b=>b.disabled=false);}} form.append(button('Reveal password',()=>passwordAction('reveal')),button('Save new mailbox password',()=>passwordAction('change')),button('Generate & show new password',()=>passwordAction('generate')),secret,note);form.onsubmit=e=>e.preventDefault();settingsBox.append(form);const client=el('details');client.append(el('summary','Thunderbird / Outlook setup'),el('p','IMAP: mail.lgbbenelux.org · port 993 · SSL/TLS. SMTP: mail.lgbbenelux.org · port 587 · STARTTLS. Your technical client credentials are managed internally. Use the mailbox password shown above. Messages older than 30 days are permanently purged, including Sent and Trash.'));settingsBox.append(client);parent.append(settingsBox);} function clearPrivateViews(){clearSecret();for(const d of document.querySelectorAll('.internal-mail-dialog'))d.remove();settingsBox?.remove();settingsBox=null;for(const view of views.values()){view.content.querySelector('.internal-mail-compose')?.remove();view.list.replaceChildren();view.reading.replaceChildren();view.address.textContent='';view.notice.textContent='';view.counter.textContent='';view.tags=[];view.filter.replaceChildren(new Option('All tags',''));}} -async function load(){const version=++generation;clearPrivateViews();try{const data=await api('me');if(version!==generation)return;account=data;void refreshPersonalLabels(version);settings(data);const dashboard=document.getElementById('dashboard');if(!dashboard)return;for(const [id,title,scope]of [['shared-inbox','Inbox','personal'],...(data.clan?[['clan-inbox',data.clan.name,'clan']]:[]),...(data.faction?[['faction-inbox',data.faction.name,'faction']]:[]),...(data.imperial?[['imperial-inbox','Imperial','imperial']]:[]),...(data.staff?[['staff-inbox','Staff','staff']]:[])]){let section=document.getElementById(id);if(!section){section=el('section');section.id=id;section.hidden=true;dashboard.append(section);}const view=mountView(section,title,scope);section.hidden=false;view.scope=scope;view.loaded=false;view.address.textContent=scope==='clan'?'Clan mailbox · '+data.clan.name:scope==='staff'?'Shared staff mailbox':scope==='faction'?'Shared faction mailbox · '+data.faction.name:scope==='imperial'?'Shared Imperial mailbox':'Your private DuneRealms inbox';const oldTabs=view.content.querySelector('.internal-mail-mailbox-tabs');oldTabs?.replaceWith(mailboxTabs(view));}if(!data.clan){document.getElementById('clan-inbox')?.remove();views.delete('clan-inbox');}if(!data.staff){document.getElementById('staff-inbox')?.remove();views.delete('staff-inbox');}for(const [id,allowed]of [['faction-inbox',data.faction],['imperial-inbox',data.imperial]])if(!allowed){document.getElementById(id)?.remove();views.delete(id);}const view=views.get(location.hash.slice(1))||views.get('shared-inbox');if(data.active)await loadMessages(view);else view.list.replaceChildren(el('p','Mailbox setup is pending. Please try again shortly.'));window.dispatchEvent(new HashChangeEvent('hashchange'));}catch(e){account=null;if(version!==generation)return;const security=document.getElementById('security');if(security){settingsBox?.remove();settingsBox=el('div',undefined,'internal-mail-settings');settingsBox.append(el('h3','Internal mailbox'),el('p',e.message),button('Retry mailbox setup',load));security.append(settingsBox);}}} +async function load(){const version=++generation;clearPrivateViews();try{const data=await api('me');if(version!==generation)return;account=data;void refreshPersonalLabels(version);settings(data);const dashboard=document.getElementById('dashboard');if(!dashboard)return;for(const [id,title,scope]of [['shared-inbox','Inbox','personal'],...(data.company?[['company-inbox',data.company.name,'company']]:[]),...(data.clan?[['clan-inbox',data.clan.name,'clan']]:[]),...(data.faction?[['faction-inbox',data.faction.name,'faction']]:[]),...(data.imperial?[['imperial-inbox','Imperial','imperial']]:[]),...(data.staff?[['staff-inbox','Staff','staff']]:[])]){let section=document.getElementById(id);if(!section){section=el('section');section.id=id;section.hidden=true;dashboard.append(section);}const view=mountView(section,title,scope);section.hidden=false;view.scope=scope;view.loaded=false;view.address.textContent=scope==='company'?'Company mailbox · '+data.company.name:scope==='clan'?'Clan mailbox · '+data.clan.name:scope==='staff'?'Shared staff mailbox':scope==='faction'?'Shared faction mailbox · '+data.faction.name:scope==='imperial'?'Shared Imperial mailbox':'Your private DuneRealms inbox';const oldTabs=view.content.querySelector('.internal-mail-mailbox-tabs');oldTabs?.replaceWith(mailboxTabs(view));}if(!data.company){document.getElementById('company-inbox')?.remove();views.delete('company-inbox');}if(!data.clan){document.getElementById('clan-inbox')?.remove();views.delete('clan-inbox');}if(!data.staff){document.getElementById('staff-inbox')?.remove();views.delete('staff-inbox');}for(const [id,allowed]of [['faction-inbox',data.faction],['imperial-inbox',data.imperial]])if(!allowed){document.getElementById(id)?.remove();views.delete(id);}const view=views.get(location.hash.slice(1))||views.get('shared-inbox');if(data.active)await loadMessages(view);else view.list.replaceChildren(el('p','Mailbox setup is pending. Please try again shortly.'));window.dispatchEvent(new HashChangeEvent('hashchange'));}catch(e){account=null;if(version!==generation)return;const security=document.getElementById('security');if(security){settingsBox?.remove();settingsBox=el('div',undefined,'internal-mail-settings');settingsBox.append(el('h3','Internal mailbox'),el('p',e.message),button('Retry mailbox setup',load));security.append(settingsBox);}}} window.addEventListener('dune:session',event=>{if(event.detail)void load();else{generation++;account=null;clearPrivateViews();}});window.addEventListener('hashchange',()=>{clearSecret();if(location.hash==='#internal-mail')location.replace('#shared-inbox');const view=views.get(location.hash.slice(1));if(account?.active&&view&&!view.loaded)void loadMessages(view);});window.addEventListener('pagehide',clearPrivateViews);const session=await fetch('/api/auth/session',{cache:'no-store'});if(session.ok&&(await session.json()).authenticated)await load(); // V2 adapter: navigate only existing folders; never creates folders or sends mail. diff --git a/website/control-panel/public/user-service-entry.mjs b/website/control-panel/public/user-service-entry.mjs index c028a981..fd1bab97 100644 --- a/website/control-panel/public/user-service-entry.mjs +++ b/website/control-panel/public/user-service-entry.mjs @@ -6,7 +6,7 @@ const SERVICES={ 'mail-settings':{title:'Correspondence Settings',art:'imperial-post-logo.svg',permission:null,pages:['security'],styles:['internal-mail.css'],modules:['./internal-mail.mjs']}, webmail:{title:'DuneRealms Mail',art:'imperial-post-logo.svg',permission:null,pages:['webmail'],styles:['git-control.css','mail-workspace.css'],modules:['./webmail.mjs']}, bank:{title:'Imperial Postbank',art:'imperial-postbank-v2.png',permission:'web.bank.personal.view',pages:['personal-bank'],styles:['banking.css'],modules:['./banking.mjs']}, - inbox:{title:'My Correspondence',art:'imperial-post-logo.svg',permission:null,pages:['shared-inbox','clan-inbox','faction-inbox','imperial-inbox','staff-inbox'],styles:['internal-mail.css'],modules:['./internal-mail.mjs']}, + inbox:{title:'My Correspondence',art:'imperial-post-logo.svg',permission:null,pages:['shared-inbox','company-inbox','clan-inbox','faction-inbox','imperial-inbox','staff-inbox'],styles:['internal-mail.css'],modules:['./internal-mail.mjs']}, tailor:{title:'Imperial Tailor',art:'nav-clan-v2.webp',permission:'web.menu.inventory',pages:['kits-exchange','kit-checkout','kit-story','kit-receipts'],styles:['kit-generator.css','kit-market.css'],modules:['./kit-market.mjs']} }; const key=new URL(location.href).searchParams.get('service'),spec=SERVICES[key],status=document.querySelector('#service-status'),dashboard=document.querySelector('#dashboard'); diff --git a/website/control-panel/server.mjs b/website/control-panel/server.mjs index a1ea966b..43acbfab 100644 --- a/website/control-panel/server.mjs +++ b/website/control-panel/server.mjs @@ -1,3 +1,8 @@ +import {ownCompanyMailbox,ensureCompanyMailbox} from '../node/internal-mail-companies.mjs'; +import {internalMailBroker} from '../node/internal-mail.mjs'; +import {applyUnicorpRoyalMailbox} from '../node/company-royal-mail.mjs'; +import {createCompanyEmblems} from './company-emblems.mjs'; +import {ensurePoliticalOfficeCharters} from '../node/political-office-charters.mjs'; import {createCompanyRecruitment} from '../node/company-recruitment.mjs'; import {initializeCompanyDeeds} from '../node/company-deeds.mjs'; import {createCompanyDeedRoute} from '../node/company-deed-route.mjs'; @@ -148,7 +153,7 @@ export function createPanel(db,settings={},dependencies={}){ const tailorAppearance=createTailorAppearance(db,dependencies.tailorAppearance); const memorials=createMemorials(db,{...settings,PUBLIC_ORIGIN:'https://www.dunerealms.com'}); const memberProfiles=createMemberProfiles(db,settings); - const honours=createHonourRoute(db,origin);const ranks=createRankAdmin(db,settings,origin);const badges=createBadgeAdmin(db,origin);const manualSeals=createManualSealRoute(db,origin);const sealCatalog=createSealCatalogAdmin(db,origin);const companyAdmin=createCompanyAdmin(db,origin);const companyDeeds=createCompanyDeedRoute(db,{keys:dependencies.organisationKeys,origin});const companyWorkspace=createCompanyWorkspace(db),politicsWorkspace=createPoliticsWorkspace(db,{keys:dependencies.organisationKeys}); + const honours=createHonourRoute(db,origin);const ranks=createRankAdmin(db,settings,origin);const badges=createBadgeAdmin(db,origin);const manualSeals=createManualSealRoute(db,origin);const sealCatalog=createSealCatalogAdmin(db,origin);const companyAdmin=createCompanyAdmin(db,origin);const companyDeeds=createCompanyDeedRoute(db,{keys:dependencies.organisationKeys,origin,onCompanyCreated:async({id,ownerId})=>{const company=await ownCompanyMailbox(db,{id:ownerId},id);if(company)await ensureCompanyMailbox(company,internalMailBroker,db);}});const companyWorkspace=createCompanyWorkspace(db),politicsWorkspace=createPoliticsWorkspace(db,{keys:dependencies.organisationKeys}); const manual=createStaffManual(db); const staffBureauRead=createStaffBureauReadApi(db); const citizenDirectory=createCitizenDirectory(db);const lifeStatus=createLifeStatus(db,{origin}); @@ -159,7 +164,7 @@ export function createPanel(db,settings={},dependencies={}){ const community=createCommunityAdmin(db,settings,{pool}); const exchange=createExchange(db,pool); let clans,companyRecruitment;const jarvis=createJarvisServices(db,dependencies.bankDatabase||null,settings,{...dependencies.jarvis,invokeClans:request=>clans(request),invokeCompany:request=>companyRecruitment(request)});companyRecruitment=createCompanyRecruitment(db,{origin,requestIntegration:jarvis.companyRequests});clans=createClans(db,{origin,onClanCreated:()=>syncClanMailRegistry(db),onClanDeleted:()=>syncClanMailRegistry(db),requestIntegration:jarvis.requests});const gameTickets=createGameTickets(db,settings); - const clanEmblems=createClanEmblems(db,{origin}); + const clanEmblems=createClanEmblems(db,{origin}),companyEmblems=createCompanyEmblems(db,{origin}); const questRewards=createQuestRewards(db,settings,pool); const gameRanks=createGameRanks(db,settings); const kitStudio=createKitStudio(db,settings,dependencies.kitStudio); @@ -254,6 +259,7 @@ export function createPanel(db,settings={},dependencies={}){ if(path==='/api/quests'||path.startsWith('/api/quests/'))return quests(request); if(['/api/clans/shop','/api/clans/shop/price','/api/clans/game-context'].includes(path))return clanShop(request); if(path.startsWith('/api/clan-emblems/'))return clanEmblems(request); + if(path.startsWith('/api/company-emblems/'))return companyEmblems(request); if(path==='/api/clans'||path.startsWith('/api/clans/'))return clans(request); if(path.startsWith('/api/hosting/'))return hosting(request); if(path==='/api/mail/accounts')return mailAccounts(request); @@ -350,7 +356,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 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);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 initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);const handle=createPanel(db,settings,{inventoryPool,bankDatabase,organisationKeys}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com'; + const db=await openDatabase(settings);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 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);const handle=createPanel(db,settings,{inventoryPool,bankDatabase,organisationKeys}),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:'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"}; @@ -367,4 +373,4 @@ export async function startPanel(settings=process.env){ } if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href)await startPanel(); - + diff --git a/website/node/company-deed-route.mjs b/website/node/company-deed-route.mjs index 3b271416..968cfda2 100644 --- a/website/node/company-deed-route.mjs +++ b/website/node/company-deed-route.mjs @@ -5,7 +5,7 @@ import {validateCompanyInput} from './company-registry.mjs'; import {OrganisationKeyError} from './organisation-keys.mjs'; import {companyId,recordInitialCompanyDeed,readCompanyDeed,companyDeedView,upgradeOriginalCompany} from './company-deeds.mjs'; const fault=(message,status=409)=>Object.assign(Error(message),{status}); -export function createCompanyDeedRoute(db,{keys=null,origin='https://cp.dunerealms.com',authenticate=r=>identity(r,db),access=u=>accessFor(db,u),clock=Date.now}={}){return async request=>{ +export function createCompanyDeedRoute(db,{keys=null,origin='https://cp.dunerealms.com',authenticate=r=>identity(r,db),access=u=>accessFor(db,u),clock=Date.now,onCompanyCreated=async()=>{}}={}){return async request=>{ const reply=(value,status=200)=>Response.json(value,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}}),url=new URL(request.url),match=/^\/api\/companies\/deeds(?:\/([a-f0-9-]{36}))?$/i.exec(url.pathname); if(!match||url.search)return reply({message:'Company deed not found.'},404); if(!['GET','POST'].includes(request.method))return reply({message:'Method not allowed.'},405); @@ -27,7 +27,7 @@ export function createCompanyDeedRoute(db,{keys=null,origin='https://cp.dunereal let input;try{input=validateCompanyInput(body);}catch{throw fault('Use a public address of 3–64 lowercase letters, numbers or hyphens, a name up to 120 characters and a description up to 1,000.',400);} if(/[\x00-\x1f\x7f]/.test(input.name)||/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(input.description))throw fault('Remove control characters from the company details.',400); const fingerprint=createHash('sha256').update(JSON.stringify(input)).digest('hex'); - return await db.transaction(async tx=>{ + const response=await db.transaction(async tx=>{ const actor=await tx.first("SELECT id FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%' FOR UPDATE",[user.id]);if(!actor)throw fault('Account access changed.',403); const prior=await tx.first('SELECT company_id,actor_id,action,details_json FROM corrino_company_events WHERE id=? FOR UPDATE',[body.requestId]); if(prior){let details;try{details=JSON.parse(prior.details_json);}catch{}if(prior.actor_id!==user.id||prior.action!=='basic-registration'||details?.fingerprint!==fingerprint)throw fault('This instruction reference was already used.');return reply({ok:true,companyId:prior.company_id,replayed:true});} @@ -38,5 +38,6 @@ export function createCompanyDeedRoute(db,{keys=null,origin='https://cp.dunereal await recordInitialCompanyDeed(tx,company,now); await tx.query('INSERT INTO corrino_company_events(id,company_id,action,actor_id,details_json,created_at) VALUES(?,?,?,?,?,?)',[body.requestId,company.id,'basic-registration',user.id,JSON.stringify({fingerprint}),now]);return reply({ok:true,companyId:company.id,replayed:false},201); }); + if(response.ok){const result=await response.clone().json();try{await onCompanyCreated({id:result.companyId,ownerId:user.id});}catch{console.error('Company mailbox provisioning pending');}}return response; }catch(error){if(error instanceof TypeError)return reply({message:error.message},400);if(error instanceof OrganisationKeyError)return reply({message:error.message},409);if(error.code==='ER_DUP_ENTRY')return reply({message:'That public company address is already registered.'},409);return reply({message:error.status?error.message:'The company instruction could not be confirmed.'},error.status||503);} };} diff --git a/website/node/company-deeds.mjs b/website/node/company-deeds.mjs index bc60390b..302e7bda 100644 --- a/website/node/company-deeds.mjs +++ b/website/node/company-deeds.mjs @@ -1,10 +1,17 @@ +import {COMPANY_ROYAL_MAIL_SCHEMA} from './company-royal-mail.mjs'; +import {CLAIM_REGISTRY_SCHEMA} from './claim-registry.mjs'; import {JARVIS_COMPANY_REQUEST_SCHEMA} from './jarvis-request-domains.mjs'; import {randomUUID} from 'node:crypto'; import {OrganisationKeyError} from './organisation-keys.mjs'; import {clanMemberLimit} from './clan-membership-policy.mjs'; export const COMPANY_DEED_SCHEMA=[ + CLAIM_REGISTRY_SCHEMA, + COMPANY_ROYAL_MAIL_SCHEMA, ...JARVIS_COMPANY_REQUEST_SCHEMA, + `CREATE TABLE IF NOT EXISTS site_company_mail_origins (company_id CHAR(36) PRIMARY KEY,clan_id CHAR(36) NOT NULL,created_at BIGINT NOT NULL,FOREIGN KEY(company_id) REFERENCES corrino_companies(id))`, + `CREATE TABLE IF NOT EXISTS site_company_emblems (company_id CHAR(36) PRIMARY KEY,image_blob MEDIUMBLOB NULL,version INT NOT NULL DEFAULT 0,updated_by CHAR(36) NOT NULL,updated_at BIGINT NOT NULL,FOREIGN KEY(company_id) REFERENCES corrino_companies(id))`, + `CREATE TABLE IF NOT EXISTS site_company_relations (company_id CHAR(36) PRIMARY KEY,parent_company_id CHAR(36) NOT NULL,relation_origin VARCHAR(12) NOT NULL DEFAULT 'created',updated_at BIGINT NOT NULL,FOREIGN KEY(company_id) REFERENCES corrino_companies(id),FOREIGN KEY(parent_company_id) REFERENCES corrino_companies(id))`, `CREATE TABLE IF NOT EXISTS site_company_requests(company_id CHAR(36) NOT NULL,user_id CHAR(36) NOT NULL,status VARCHAR(12) NOT NULL,created_at BIGINT NOT NULL,updated_at BIGINT NOT NULL,decided_by CHAR(36) NULL,PRIMARY KEY(company_id,user_id))`, `CREATE TABLE IF NOT EXISTS site_company_deeds(company_id CHAR(36) PRIMARY KEY,owner_account_id CHAR(36) NOT NULL,charter_kind VARCHAR(16) NOT NULL DEFAULT 'basic',original_key_id CHAR(36) NULL UNIQUE,version INT NOT NULL DEFAULT 1,created_at BIGINT NOT NULL,updated_at BIGINT NOT NULL,FOREIGN KEY(company_id) REFERENCES corrino_companies(id),FOREIGN KEY(owner_account_id) REFERENCES site_accounts(id))`, `CREATE TABLE IF NOT EXISTS site_company_members(company_id CHAR(36) NOT NULL,user_id CHAR(36) NOT NULL,joined_at BIGINT NOT NULL,PRIMARY KEY(company_id,user_id),FOREIGN KEY(company_id) REFERENCES corrino_companies(id),FOREIGN KEY(user_id) REFERENCES site_accounts(id))` @@ -23,6 +30,9 @@ export async function recordInitialCompanyDeed(tx,company,now){ export async function initializeCompanyDeeds(db,{mysql=true,clock=Date.now}={}){ for(const sql of COMPANY_DEED_SCHEMA)await db.prepare(sql+(mysql?' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4':'')).run(); await db.transaction(async tx=>{const companies=await tx.query("SELECT c.id,c.founded_by,c.created_at FROM corrino_companies c JOIN site_accounts a ON a.id=c.founded_by LEFT JOIN site_company_deeds d ON d.company_id=c.id WHERE c.status IN ('active','pending') AND d.company_id IS NULL ORDER BY c.id FOR UPDATE");for(const company of companies)await recordInitialCompanyDeed(tx,company,clock());}); + // Pin existing companies to their original founder's single Clan mailbox. + // Later acquisitions never rewrite this origin or migrate messages. + await db.query("INSERT INTO site_company_mail_origins(company_id,clan_id,created_at) SELECT c.id,MIN(cl.id),? FROM corrino_companies c JOIN site_clans cl ON cl.owner_id=c.founded_by AND cl.active=1 LEFT JOIN site_company_mail_origins m ON m.company_id=c.id LEFT JOIN site_company_relations r ON r.company_id=c.id AND r.relation_origin='created' WHERE m.company_id IS NULL AND r.company_id IS NULL GROUP BY c.id HAVING COUNT(cl.id)=1 ON DUPLICATE KEY UPDATE company_id=VALUES(company_id)",[clock()]); db.companyDeedsEnabled=true; } diff --git a/website/node/company-royal-mail.mjs b/website/node/company-royal-mail.mjs new file mode 100644 index 00000000..053618a1 --- /dev/null +++ b/website/node/company-royal-mail.mjs @@ -0,0 +1,38 @@ +import {createHash,randomUUID} from 'node:crypto'; +import {STAFF_OFFICE_ACCOUNT_ID,OrganisationKeyError} from './organisation-keys.mjs'; +export const COMPANY_ROYAL_MAIL_SCHEMA=`CREATE TABLE IF NOT EXISTS site_company_royal_mail (company_id CHAR(36) PRIMARY KEY,royal_key_id CHAR(36) NOT NULL UNIQUE,mailbox_id CHAR(36) NOT NULL UNIQUE,state VARCHAR(12) NOT NULL,updated_at BIGINT NOT NULL)`; +export function separateCompanyMailboxId(id){const h=createHash('sha256').update('dunerealms:royal-company-mail:'+id).digest('hex');return h.slice(0,8)+'-'+h.slice(8,12)+'-4'+h.slice(13,16)+'-8'+h.slice(17,20)+'-'+h.slice(20,32);} +const targetSql="SELECT c.id,c.name,c.slug,c.status,d.owner_account_id,d.charter_kind,d.original_key_id FROM corrino_companies c JOIN site_company_deeds d ON d.company_id=c.id JOIN site_accounts a ON a.id=d.owner_account_id WHERE c.slug='unicorp' AND LOWER(c.name)='unicorp' AND LOWER(a.username)='unimatrix999' AND a.password_hash NOT LIKE '!%'"; +const first=(db,sql,args=[])=>typeof db.first==='function'?db.first(sql,args):db.prepare(sql).bind(...args).first(); +async function verifyOriginal(tx,c){ + const original=c&&await first(tx,"SELECT id FROM organisation_keys WHERE id=? AND key_type='company-founding' AND target_id=? AND used_at IS NOT NULL AND revoked_at IS NULL",[c.original_key_id,c.id]); + if(!c||c.status!=='active'||!['original','royal'].includes(c.charter_kind)||!original)throw new OrganisationKeyError('The active Unicorp original Company deed must match before the authorised Royal upgrade'); +} +// One explicitly requested rollout. No other company, account, personal key or +// old mailbox is promoted, moved, deleted or granted staff access. +export async function applyUnicorpRoyalMailbox(db,keys,{apply=false,clock=Date.now}={}){ + const rows=await db.query(targetSql);if(!rows.length)return{state:'not_found',changed:false};if(rows.length!==1)throw new OrganisationKeyError('Unicorp identity is ambiguous');const c=rows[0]; + await verifyOriginal(db,c);if(!apply)return{state:'ready',companyId:c.id,name:c.name,currentCharter:c.charter_kind,desiredCharter:'royal',mailbox:'separate',changed:false}; + await db.query(COMPANY_ROYAL_MAIL_SCHEMA); + const scopeId='company:'+c.id,grant=await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-company-royal',scopeId,authorize:async tx=>{await verifyOriginal(tx,await tx.first(targetSql+' FOR UPDATE'));}}),key=(await keys.list(STAFF_OFFICE_ACCOUNT_ID)).find(k=>k.id===grant.id); + if(key?.status==='available')await keys.consume({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-company-royal',code:key.code,targetId:c.id,requestId:c.id,apply:async(tx,context)=>{ + const current=await tx.first(targetSql+' FOR UPDATE');await verifyOriginal(tx,current);if(current.id!==c.id||context.scopeId!==scopeId)throw new OrganisationKeyError('The Company deed changed');const now=clock(); + await tx.query("UPDATE site_company_deeds SET charter_kind='royal',version=version+1,updated_at=? WHERE company_id=?",[now,c.id]); + await tx.query("INSERT INTO site_company_royal_mail(company_id,royal_key_id,mailbox_id,state,updated_at) VALUES(?,?,?,'pending',?)",[c.id,context.keyId,separateCompanyMailboxId(c.id),now]); + await tx.query('INSERT INTO corrino_company_events(id,company_id,action,actor_id,details_json,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),c.id,'staff-royal-upgrade',STAFF_OFFICE_ACCOUNT_ID,JSON.stringify({keyId:context.keyId,reason:'Explicit owner request: Royal Unicorp and separate mailbox',mailbox:'separate'}),now]); + }}); + const record=await first(db,'SELECT royal_key_id,mailbox_id,state FROM site_company_royal_mail WHERE company_id=?',[c.id]); + if(!record||record.royal_key_id!==grant.id||key?.status!=='available'&&(key?.status!=='used'||key.targetId!==c.id))throw new OrganisationKeyError('Unicorp Royal staff key requires review'); + return{state:record.state,companyId:c.id,name:c.name,charter:'royal',changed:key.status==='available'}; +} +export async function readRoyalCompanyMailbox(db,id,now=Date.now()){ + return first(db,"SELECT m.mailbox_id,m.state,c.id,c.name,c.slug FROM site_company_royal_mail m JOIN corrino_companies c ON c.id=m.company_id JOIN site_company_deeds d ON d.company_id=c.id JOIN organisation_keys k ON k.id=m.royal_key_id WHERE c.id=? AND c.status='active' AND d.charter_kind='royal' AND k.key_type IN ('staff-company-royal','political-appointment') AND k.used_at IS NOT NULL AND k.target_id=c.id AND k.revoked_at IS NULL AND (k.expires_at IS NULL OR k.expires_at>?)",[id,now]); +} +export async function reconcileRoyalCompanyMail(db,broker){ + await db.query(COMPANY_ROYAL_MAIL_SCHEMA);const rows=await db.query("SELECT company_id FROM site_company_royal_mail WHERE state='pending' ORDER BY company_id");let activated=0; + for(const row of rows){const source=await readRoyalCompanyMailbox(db,row.company_id);if(!source)continue; + await broker({action:'internal_ensure',userId:source.mailbox_id,eligible:true,mailboxKind:'clan',resourceId:source.id,localPart:'company-'+source.slug+'.internal'}); + if(!await readRoyalCompanyMailbox(db,row.company_id))continue; + await db.query("UPDATE site_company_royal_mail SET state='active',updated_at=? WHERE company_id=? AND mailbox_id=? AND state='pending'",[Date.now(),source.id,source.mailbox_id]);activated++; + }return{activated}; +} diff --git a/website/node/company-workspace.mjs b/website/node/company-workspace.mjs index 94ae9538..ceca46f0 100644 --- a/website/node/company-workspace.mjs +++ b/website/node/company-workspace.mjs @@ -1,17 +1,18 @@ +import {companyEmblemUrl} from '../control-panel/company-emblems.mjs'; import {readCompanyDeed,companyDeedView} from './company-deeds.mjs'; -import {identity} from './auth.mjs'; -const uuid=/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i; -export function createCompanyWorkspace(db,{authenticate=request=>identity(request,db)}={}){return async request=>{ - const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}}); - if(request.method!=='GET')return reply({message:'Method not allowed.'},405); - const user=await authenticate(request);if(!user)return reply({message:'Sign in to open Company CP.'},401); - const params=new URL(request.url).searchParams,id=params.get('company'); - if([...params.keys()].some(k=>k!=='company')||params.getAll('company').length>1||id!==null&&!uuid.test(id))return reply({message:'Choose a valid company.'},400); +import {identity} from './auth.mjs'; +const uuid=/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i; +export function createCompanyWorkspace(db,{authenticate=request=>identity(request,db)}={}){return async request=>{ + const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}}); + if(request.method!=='GET')return reply({message:'Method not allowed.'},405); + const user=await authenticate(request);if(!user)return reply({message:'Sign in to open Company CP.'},401); + const params=new URL(request.url).searchParams,id=params.get('company'); + if([...params.keys()].some(k=>k!=='company')||params.getAll('company').length>1||id!==null&&!uuid.test(id))return reply({message:'Choose a valid company.'},400); const ownerSource=db.companyDeedsEnabled?'EXISTS(SELECT 1 FROM site_company_deeds d WHERE d.company_id=c.id AND d.owner_account_id=?)':'c.founded_by=?'; const extra=db.companyDeedsEnabled?' OR EXISTS(SELECT 1 FROM site_company_members m WHERE m.company_id=c.id AND m.user_id=?)':''; - const {results=[]}=await db.prepare('SELECT c.id,c.slug,c.name,c.description,c.status,c.founded_by,c.ceo_account_id,a.username ceo_name,f.username founder_name FROM corrino_companies c LEFT JOIN site_accounts a ON a.id=c.ceo_account_id LEFT JOIN site_accounts f ON f.id=c.founded_by WHERE ('+ownerSource+' OR c.ceo_account_id=?'+extra+')'+(db.companyDeedsEnabled?" AND c.status IN ('active','pending')":'')+' ORDER BY c.name LIMIT 100').bind(user.id,user.id,...(db.companyDeedsEnabled?[user.id]:[])).all(); - let companies=results.map(({founded_by,ceo_account_id,...company})=>({...company,role:founded_by===user.id?'Founder':'CEO'})); - if(db.companyDeedsEnabled)companies=await Promise.all(companies.map(async c=>{const view=companyDeedView(await readCompanyDeed(db,c.id),user.id),requests=view.canManage?(await db.prepare("SELECT a.username FROM site_company_requests r JOIN site_jarvis_company_applications j ON j.company_id=r.company_id AND j.user_id=r.user_id JOIN site_accounts a ON a.id=r.user_id WHERE r.company_id=? AND r.status='pending' ORDER BY r.created_at LIMIT 101").bind(c.id).all()).results:[];return{...c,...view,canReview:view.canManage,requests};})); - if(id&&!companies.some(c=>c.id===id))return reply({message:'This company is not available to your account.'},404); - return reply({companies,selected:id||companies[0]?.id||null}); -};} + const {results=[]}=await db.prepare('SELECT c.id,c.slug,c.name,c.description,c.status,c.founded_by,c.ceo_account_id,a.username ceo_name,f.username founder_name FROM corrino_companies c LEFT JOIN site_accounts a ON a.id=c.ceo_account_id LEFT JOIN site_accounts f ON f.id=c.founded_by WHERE ('+ownerSource+' OR c.ceo_account_id=?'+extra+')'+(db.companyDeedsEnabled?" AND c.status IN ('active','pending')":'')+' ORDER BY c.name LIMIT 100').bind(user.id,user.id,...(db.companyDeedsEnabled?[user.id]:[])).all(); + let companies=results.map(({founded_by,ceo_account_id,...company})=>({...company,role:founded_by===user.id?'Founder':'CEO'})); + if(db.companyDeedsEnabled)companies=await Promise.all(companies.map(async c=>{const view=companyDeedView(await readCompanyDeed(db,c.id),user.id),requests=view.canManage?(await db.prepare("SELECT a.username FROM site_company_requests r JOIN site_jarvis_company_applications j ON j.company_id=r.company_id AND j.user_id=r.user_id JOIN site_accounts a ON a.id=r.user_id WHERE r.company_id=? AND r.status='pending' ORDER BY r.created_at LIMIT 101").bind(c.id).all()).results:[];const emblem=await db.prepare('SELECT version,image_blob IS NOT NULL has_emblem FROM site_company_emblems WHERE company_id=?').bind(c.id).first();return{...c,...view,emblem:companyEmblemUrl(c.id,emblem?.version||0),emblemVersion:Number(emblem?.version||0),hasEmblem:!!emblem?.has_emblem,canReview:view.canManage,requests};})); + if(id&&!companies.some(c=>c.id===id))return reply({message:'This company is not available to your account.'},404); + return reply({companies,selected:id||companies[0]?.id||null}); +};} diff --git a/website/node/internal-mail-companies.mjs b/website/node/internal-mail-companies.mjs new file mode 100644 index 00000000..d14ea8d3 --- /dev/null +++ b/website/node/internal-mail-companies.mjs @@ -0,0 +1,30 @@ +import {readRoyalCompanyMailbox} from './company-royal-mail.mjs'; +import {clanMailboxId} from './internal-mail-clans.mjs'; +import {companyId,readCompanyDeed,companyDeedView} from './company-deeds.mjs'; +import {ensureClanMailbox,ownClanMailbox} from './internal-mail-clans.mjs'; +// Company CP opens the existing original Clan mailbox. It does not provision a +// Company-specific inbox or expand access beyond the existing Clan authority. +export async function companyMailboxClan(db,id,seen=new Set()){ + if(seen.has(id)||seen.size>=32)throw Error('Company mailbox ancestry requires review');seen.add(id); + const prior=await db.prepare('SELECT clan_id FROM site_company_mail_origins WHERE company_id=?').bind(id).first();if(prior)return prior.clan_id; + const relation=await db.prepare('SELECT parent_company_id,relation_origin FROM site_company_relations WHERE company_id=?').bind(id).first(); + if(relation?.relation_origin==='created'){const clanId=await companyMailboxClan(db,relation.parent_company_id,seen);if(!clanId)return null;await db.query('INSERT INTO site_company_mail_origins(company_id,clan_id,created_at) VALUES(?,?,?) ON DUPLICATE KEY UPDATE company_id=VALUES(company_id)',[id,clanId,Date.now()]);return(await db.prepare('SELECT clan_id FROM site_company_mail_origins WHERE company_id=?').bind(id).first()).clan_id;} + const {results}=await db.prepare("SELECT cl.id FROM corrino_companies c JOIN site_clans cl ON cl.owner_id=c.founded_by AND cl.active=1 WHERE c.id=? ORDER BY cl.id").bind(id).all();if(results.length>1)return null;const sourceId=results[0]?.id||id; + await db.query('INSERT INTO site_company_mail_origins(company_id,clan_id,created_at) VALUES(?,?,?) ON DUPLICATE KEY UPDATE company_id=VALUES(company_id)',[id,sourceId,Date.now()]); + return(await db.prepare('SELECT clan_id FROM site_company_mail_origins WHERE company_id=?').bind(id).first()).clan_id; +} +export async function ownCompanyMailbox(db,user,id){ + if(!db.companyDeedsEnabled||!companyId(id))return null; + const deed=await readCompanyDeed(db,id);if(deed.company.status!=='active')return null;let view;try{view=companyDeedView(deed,user.id);}catch(error){if(error.status===403)return null;throw error;}if(!view.canManage)return null; + const royal=await readRoyalCompanyMailbox(db,id);if(royal?.state==='active')return{id,name:deed.company.name,separate:true,mailboxId:royal.mailbox_id}; + const clanId=await companyMailboxClan(db,id);if(!clanId)return null; + const clan=await db.prepare('SELECT id,name,tag FROM site_clans WHERE id=? AND active=1').bind(clanId).first();if(clan){if(!await ownClanMailbox(db,user,clanId))return null;return{id,name:deed.company.name,clanId,clan};} + const source=await db.prepare("SELECT id,name,slug FROM corrino_companies WHERE id=? AND status='active'").bind(clanId).first();if(!source)return null;return{id,name:deed.company.name,standalone:true,source}; +} +export async function ensureCompanyMailbox(company,broker,db){ + if(company.separate){const current=await readRoyalCompanyMailbox(db,company.id);if(!current||current.state!=='active'||current.mailbox_id!==company.mailboxId)throw Object.assign(Error('Royal Company mailbox authority changed'),{status:403});return{userId:current.mailbox_id};} + if(company.standalone){const source=company.source,userId=clanMailboxId(source.id);const status=await broker({action:'internal_ensure',userId,eligible:true,mailboxKind:'clan',resourceId:source.id,localPart:'company-'+source.slug+'.internal'});return{userId,address:status.address};} + return ensureClanMailbox(db,company.clan,broker); +} + +export async function reconcileCompanyMail(db,broker){if(!db.companyDeedsEnabled)return;const {results}=await db.prepare("SELECT d.company_id,d.owner_account_id FROM site_company_deeds d JOIN corrino_companies c ON c.id=d.company_id WHERE c.status='active' ORDER BY d.company_id").all();const seen=new Set();for(const row of results){const company=await ownCompanyMailbox(db,{id:row.owner_account_id},row.company_id);if(!company)continue;const id=company.mailboxId||clanMailboxId(company.source?.id||company.clanId);if(seen.has(id))continue;await ensureCompanyMailbox(company,broker,db);seen.add(id);}} diff --git a/website/node/internal-mail.mjs b/website/node/internal-mail.mjs index 60af3501..88cc64fc 100644 --- a/website/node/internal-mail.mjs +++ b/website/node/internal-mail.mjs @@ -1,3 +1,5 @@ +import {reconcileRoyalCompanyMail} from './company-royal-mail.mjs'; +import {ownCompanyMailbox,ensureCompanyMailbox,reconcileCompanyMail} from './internal-mail-companies.mjs'; import {runJarvisApplicationNotifications} from './jarvis-notifications.mjs'; import {runPoliticalNotifications} from './political-notifications.mjs'; import {runTicketMail} from './internal-mail-tickets.mjs'; @@ -55,7 +57,7 @@ export async function resolveMailRecipients(db,values,{eligible=internalMailElig } return [...new Set(resolved)]; } -export function startInternalMailSync(db,{broker=internalMailBroker,jarvisStore=null}={}){let busy=false,closed=false;const sync=async()=>{if(busy||closed)return;busy=true;try{await initializePoliticalMailRanks(db);await initializeMailReports(db);await ensureStaffMailbox(broker);await initializeClanMail(db);await reconcileClanMail(db,broker);const{results}=await db.prepare(eligibilitySql).all();for(const user of results){if(closed)break;await ensureInternalMailbox(db,user,broker).catch(()=>{});}await runTicketMail(db,{broker,eligible:internalMailEligible,staffAccess:canUseStaffMail});await runPoliticalNotifications(db,{broker,eligible:internalMailEligible}).catch(()=>console.error('Election notices pending'));if(jarvisStore){await runJarvisApplicationNotifications(db,jarvisStore,{broker,eligible:internalMailEligible}).catch(()=>console.error('Recruitment notices pending'));if(db.companyDeedsEnabled)await runJarvisApplicationNotifications(db,jarvisStore,{broker,eligible:internalMailEligible,kind:'company'}).catch(()=>console.error('Company recruitment notices pending'));}}catch{console.error('Internal mailbox reconciliation pending');}finally{busy=false;}};void sync();const timer=setInterval(sync,60000);timer.unref();return()=>{closed=true;clearInterval(timer);};} +export function startInternalMailSync(db,{broker=internalMailBroker,jarvisStore=null}={}){let busy=false,closed=false;const sync=async()=>{if(busy||closed)return;busy=true;try{await initializePoliticalMailRanks(db);await initializeMailReports(db);await ensureStaffMailbox(broker);await reconcileRoyalCompanyMail(db,broker);await reconcileCompanyMail(db,broker);await initializeClanMail(db);await reconcileClanMail(db,broker);const{results}=await db.prepare(eligibilitySql).all();for(const user of results){if(closed)break;await ensureInternalMailbox(db,user,broker).catch(()=>{});}await runTicketMail(db,{broker,eligible:internalMailEligible,staffAccess:canUseStaffMail});await runPoliticalNotifications(db,{broker,eligible:internalMailEligible}).catch(()=>console.error('Election notices pending'));if(jarvisStore){await runJarvisApplicationNotifications(db,jarvisStore,{broker,eligible:internalMailEligible}).catch(()=>console.error('Recruitment notices pending'));if(db.companyDeedsEnabled)await runJarvisApplicationNotifications(db,jarvisStore,{broker,eligible:internalMailEligible,kind:'company'}).catch(()=>console.error('Company recruitment notices pending'));}}catch{console.error('Internal mailbox reconciliation pending');}finally{busy=false;}};void sync();const timer=setInterval(sync,60000);timer.unref();return()=>{closed=true;clearInterval(timer);};} const routes={ '/api/internal-mail/messages/list':['internal_list',['folder','offset','limit','unread','tag','sort']], '/api/internal-mail/messages/move':['internal_move',['folder','uid','uidValidity','destination']], @@ -88,12 +90,17 @@ export function createInternalMail(db,{origin='https://cp.dunerealms.com',broker const political=await governmentAccess(db,user); if(political?.canFactionMail)await ensureGovernmentMailbox('faction',political.factionId,broker); if(political?.canImperialMail)await ensureGovernmentMailbox('imperial',null,broker); - return reply({...value,eligible:true,staff,faction:political?.canFactionMail?{name:political.factionName}:null,imperial:!!political?.canImperialMail,clan:clan?{name:clan.name,role:clan.clan_role}:null}); + const companyId=new URL(request.url).searchParams.get('company'),company=companyId?await ownCompanyMailbox(db,user,companyId):null;if(companyId&&!company)return reply({message:'Current company management is required.'},403);if(company)await ensureCompanyMailbox(company,broker,db); + return reply({...value,company:company?{id:company.id,name:company.name,clanId:company.clanId}:null,eligible:true,staff,faction:political?.canFactionMail?{name:political.factionName}:null,imperial:!!political?.canImperialMail,clan:clan?{name:clan.name,role:clan.clan_role}:null}); } let body;try{body=await request.json();}catch{return reply({message:'Send valid JSON'},400);} if(!body||typeof body!=='object'||Array.isArray(body))return reply({message:'Invalid request'},400); let mailboxUserId=user.id,mailboxName=user.username,political=null; - if(body.scope==='clan'){ + if(body.scope==='company'){ + if(path.startsWith('/api/internal-mail/password')||path==='/api/internal-mail/forwarding')return reply({message:'Shared company credentials and forwarding are managed internally.'},403); + const company=await ownCompanyMailbox(db,user,body.companyId);if(!company)return reply({message:'Current company management is required.'},403); + mailboxUserId=(await ensureCompanyMailbox(company,broker,db)).userId;mailboxName=company.name+' (internal)'; + }else if(body.scope==='clan'){ if(path.startsWith('/api/internal-mail/password')||path==='/api/internal-mail/forwarding')return reply({message:'Shared clan credentials and forwarding cannot be changed here.'},403); const clan=await ownClanMailbox(db,user,body.clanId||null);if(!clan)return reply({message:'Only the current clan owner and officers can open CLAN mail.'},403); mailboxUserId=(await ensureClanMailbox(db,clan,broker)).userId; diff --git a/website/node/member-holdings.mjs b/website/node/member-holdings.mjs index 055c0a60..163f999c 100644 --- a/website/node/member-holdings.mjs +++ b/website/node/member-holdings.mjs @@ -10,8 +10,9 @@ export async function memberHoldings(db,target){ try{clans=(await db.prepare('SELECT c.id,c.name,c.tag,c.home_world,c.owner_id,i.institution_key,d.parent_clan_id,d.heir_account_id,d.heir_joined_at,d.consort_account_id,d.consort_joined_at,ch.charter_kind FROM site_clans c LEFT JOIN site_clan_deeds d ON d.clan_id=c.id LEFT JOIN site_clan_charters ch ON ch.clan_id=c.id LEFT JOIN site_clan_institutions i ON i.clan_id=c.id WHERE c.active=1 ORDER BY c.name_key LIMIT 501').all()).results;if(clans.length>500)throw Error('Public clan register exceeds its current view.');}catch(error){if(!missing(error))throw error;clans=[];result.state='partial';result.clansState='unavailable';} const current=await db.prepare('SELECT m.clan_id,m.joined_at FROM site_clan_members m JOIN site_game_links l ON l.user_id=m.user_id AND l.minecraft_uuid=m.minecraft_uuid WHERE m.user_id=?').bind(target.id).first(); const politicalIdentity=await readPoliticalIdentity(db,target),characterGender=(await readCharacterPreferences(db,target.id)).ownerDefault; + for(const office of politicalIdentity.poldeeds.records||[])result.deeds.push({id:office.key,name:office.scope,kind:'royal',entityKind:'politics',url:'https://www.dunerealms.com/political-houses/'+encodeURIComponent(office.key),emblem:office.seal,basis:'Active office deed'}); const rank=[],owned=new Set(); - for(const c of clans){const kind=c.charter_kind||'basic',record={id:c.id,name:c.name,tag:c.tag,kind,url:'https://www.dunerealms.com/clans/'+encodeURIComponent(c.tag),emblem:'https://cp.dunerealms.com/api/clan-emblems/'+encodeURIComponent(c.id)};let role=null; + for(const c of clans){const kind=c.charter_kind||'basic',record={id:c.id,name:c.name,tag:c.tag,kind,entityKind:'clan',url:'https://www.dunerealms.com/clans/'+encodeURIComponent(c.tag),emblem:'https://cp.dunerealms.com/api/clan-emblems/'+encodeURIComponent(c.id)};let role=null; if(c.owner_id===target.id){result.clans.push(record);result.deeds.push(record);owned.add(c.id);role='ruler';} else if(c.heir_account_id===target.id&&['original','royal'].includes(kind)&¤t&&Number(current.joined_at)===Number(c.heir_joined_at)&&clanHierarchyRoot(clans,current.clan_id)===clanHierarchyRoot(clans,c.id))role='heir'; else if(c.consort_account_id===target.id&¤t&&Number(current.joined_at)===Number(c.consort_joined_at))role='consort'; @@ -24,5 +25,11 @@ export async function memberHoldings(db,target){ if(results.length>100)throw Error('Public company register exceeds its current view.'); result.companies=results.filter(c=>BigInt(c.owned_shares)>0n||c.founded_by===target.id&&BigInt(c.issued_shares)===0n).map(c=>({id:c.id,name:c.name,url:'https://corp.dunerealms.com/#company/company-overview/'+encodeURIComponent(c.id),basis:BigInt(c.owned_shares)>0n?'Shareholder':'Registered founder'})); }catch(error){if(!missing(error))throw error;result.state='partial';result.companiesState='unavailable';} + if(db.companyDeedsEnabled){ + const {results:companies}=await db.prepare("SELECT c.id,c.name,c.slug,d.charter_kind FROM corrino_companies c JOIN site_company_deeds d ON d.company_id=c.id WHERE c.status='active' AND d.owner_account_id=? ORDER BY c.name").bind(target.id).all(); + const {results:children}=await db.prepare("SELECT c.id,c.name,c.slug,r.parent_company_id FROM site_company_relations r JOIN corrino_companies c ON c.id=r.company_id JOIN site_company_deeds d ON d.company_id=r.parent_company_id WHERE d.owner_account_id=? AND c.status='active' ORDER BY c.name").bind(target.id).all(); + for(const c of children)result.subhouses.push({id:c.id,name:c.name,entityKind:'company',parentCompanyId:c.parent_company_id,url:'https://www.dunerealms.com/companies/'+encodeURIComponent(c.slug),emblem:'https://cp.dunerealms.com/api/company-emblems/'+encodeURIComponent(c.id)}); + for(const c of companies){const record={id:c.id,name:c.name,kind:c.charter_kind,entityKind:'company',url:'https://www.dunerealms.com/companies/'+encodeURIComponent(c.slug),emblem:'https://cp.dunerealms.com/api/company-emblems/'+encodeURIComponent(c.id),basis:'Registered deed owner'};result.deeds.push(record);if(!result.companies.some(r=>r.id===c.id))result.companies.push(record);} + } return result; } diff --git a/website/node/organisation-keys.mjs b/website/node/organisation-keys.mjs index 11bbcd97..9b70143e 100644 --- a/website/node/organisation-keys.mjs +++ b/website/node/organisation-keys.mjs @@ -3,6 +3,8 @@ import {createHash,createCipheriv,createDecipheriv,randomBytes,randomUUID} from // Server-only. A secret grants a recorded entitlement; it is never an API credential. export const ORGANISATION_KEY_TYPES=Object.freeze({ + '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'}), @@ -10,6 +12,7 @@ export const ORGANISATION_KEY_TYPES=Object.freeze({ 'company-founding':Object.freeze({prefix:'COM',purpose:'original-founding'}), 'political-appointment':Object.freeze({prefix:'POL',purpose:'appointment'}) }); +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`, `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` @@ -50,8 +53,12 @@ export function createOrganisationKeys(db,{secret,editions=null}={}){ 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'); + if(keyType==='staff-office-royal'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||!/^office:[a-z_]{1,32}$/.test(scopeId)||typeof authorize!=='function'))throw new TypeError('Staff office keys require the system issuer and a protected-office authority adapter'); + 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==='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}); 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]); diff --git a/website/node/political-office-charters.mjs b/website/node/political-office-charters.mjs new file mode 100644 index 00000000..d3002be7 --- /dev/null +++ b/website/node/political-office-charters.mjs @@ -0,0 +1,32 @@ +import {createHash} from 'node:crypto'; +import {PUBLIC_OFFICES} from './public-government.mjs'; +import {STAFF_OFFICE_ACCOUNT_ID,OrganisationKeyError} from './organisation-keys.mjs'; + +export const POLITICAL_OFFICE_CHARTER_SCHEMA=`CREATE TABLE IF NOT EXISTS political_office_charters (office_key VARCHAR(32) PRIMARY KEY,organisation_id CHAR(36) NOT NULL UNIQUE,charter_kind VARCHAR(12) NOT NULL,staff_key_id CHAR(36) NOT NULL UNIQUE,applied_at BIGINT NOT NULL)`; +export function politicalOfficeId(key){ + if(!PUBLIC_OFFICES.some(o=>o.key===key))throw new TypeError('Unknown protected political office'); + const hex=createHash('sha256').update('dunerealms:protected-office:'+key).digest('hex'); + return hex.slice(0,8)+'-'+hex.slice(8,12)+'-4'+hex.slice(13,16)+'-8'+hex.slice(17,20)+'-'+hex.slice(20,32); +} +// Internal system reconciliation, never a user redemption or a personal founding grant. +// Royal standing belongs to the office; membership still follows the current office deed. +export async function ensurePoliticalOfficeCharters(db,keys,{clock=Date.now}={}){ + if(!keys)throw new TypeError('The organisation key service is required'); + await db.query(POLITICAL_OFFICE_CHARTER_SCHEMA); + let applied=0; + for(const office of PUBLIC_OFFICES){ + const targetId=politicalOfficeId(office.key),scopeId='office:'+office.key; + const grant=await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-office-royal',scopeId,authorize:async()=>{politicalOfficeId(office.key);}}); + const key=(await keys.list(STAFF_OFFICE_ACCOUNT_ID)).find(k=>k.id===grant.id); + if(key?.status==='available'){ + await keys.consume({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-office-royal',code:key.code,targetId,requestId:targetId,apply:async(tx,context)=>{ + if(context.scopeId!==scopeId)throw new OrganisationKeyError('Staff key does not match this office'); + await tx.query('INSERT INTO political_office_charters(office_key,organisation_id,charter_kind,staff_key_id,applied_at) VALUES(?,?,?,?,?)',[office.key,targetId,'royal',context.keyId,clock()]); + }});applied++; + } + const row=await db.prepare('SELECT organisation_id,charter_kind,staff_key_id FROM political_office_charters WHERE office_key=?').bind(office.key).first(); + if(key?.status!=='available'&&key?.status!=='used'||!row||row.organisation_id!==targetId||row.charter_kind!=='royal'||row.staff_key_id!==grant.id||key?.status==='used'&&key.targetId!==targetId)throw new OrganisationKeyError('Protected office staff charter requires review'); + } + db.politicalOfficeChartersEnabled=true; + return{offices:PUBLIC_OFFICES.length,applied}; +} diff --git a/website/node/politics-workspace.mjs b/website/node/politics-workspace.mjs index 311fa09f..41be04d8 100644 --- a/website/node/politics-workspace.mjs +++ b/website/node/politics-workspace.mjs @@ -8,7 +8,7 @@ export function createPoliticsWorkspace(db,{authenticate=r=>identity(r,db),acces 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})); + 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',charterKind:'royal',memberLimit:50,charterSource:'staff-key',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);} diff --git a/website/node/postbank-service.mjs b/website/node/postbank-service.mjs index 7917c616..2fbc6b53 100644 --- a/website/node/postbank-service.mjs +++ b/website/node/postbank-service.mjs @@ -23,7 +23,7 @@ export class PostbankService{ const client=await this.db.first('SELECT client_number FROM pb_clients WHERE entity_id=?',[e.id]); const packages=client?await this.db.query('SELECT id,package_key,monthly_minor,state FROM pb_packages WHERE client_number=? ORDER BY accepted_at,id',[client.client_number]):[]; const accounts=client?await this.db.query('SELECT a.id,a.account_number,a.type_code,a.display_name,a.balance_minor,a.reserved_minor,a.state,a.package_id,a.system_key,COALESCE(o.balance_guard,0) AS balance_guard FROM pb_accounts a LEFT JOIN pb_account_options o ON o.account_id=a.id WHERE a.client_number=? ORDER BY a.id',[client.client_number]):[]; - entities.push({id:e.id,kind:e.kind,...(e.kind==='clan'?{clanId:e.key}:{}),name:e.name,bankingRequirement:e.bankingRequirement||null,clientNumber:client?.client_number||null,state:client?'active':'not_activated',canActivate:e.canActivate,canPay:e.canPay,expiresAt:e.expiresAt,packages:packages.map(p=>({id:p.id,key:p.package_key,name:PACKAGES.find(s=>s.key===p.package_key)?.name||p.package_key,monthly:money(p.monthly_minor),state:p.state})),accounts:accounts.filter(a=>canViewAccount(context,e.id,a.id)).map(a=>({canPay:a.state==='active'&&a.type_code!=='106'&&canDebitAccount(context,e.id,a.id),id:String(a.id),number:a.account_number,type:a.type_code,name:a.display_name,balance:money(a.balance_minor),available:a.type_code==='106'?'0.00':money(BigInt(a.balance_minor)-BigInt(a.reserved_minor)),state:a.state,packageId:a.package_id,options:{balanceGuardEligible:!['979','106'].includes(a.type_code)&&!a.system_key,balanceGuard:Boolean(a.balance_guard),monthly:money(a.balance_guard?100:0),state:'configured_pending_billing'}}))}); + entities.push({id:e.id,kind:e.kind,...(e.kind==='clan'?{clanId:e.key}:e.kind==='company'?{companyId:e.key}:{}),name:e.name,bankingRequirement:e.bankingRequirement||null,clientNumber:client?.client_number||null,state:client?'active':'not_activated',canActivate:e.canActivate,canPay:e.canPay,expiresAt:e.expiresAt,packages:packages.map(p=>({id:p.id,key:p.package_key,name:PACKAGES.find(s=>s.key===p.package_key)?.name||p.package_key,monthly:money(p.monthly_minor),state:p.state})),accounts:accounts.filter(a=>canViewAccount(context,e.id,a.id)).map(a=>({canPay:a.state==='active'&&a.type_code!=='106'&&canDebitAccount(context,e.id,a.id),id:String(a.id),number:a.account_number,type:a.type_code,name:a.display_name,balance:money(a.balance_minor),available:a.type_code==='106'?'0.00':money(BigInt(a.balance_minor)-BigInt(a.reserved_minor)),state:a.state,packageId:a.package_id,options:{balanceGuardEligible:!['979','106'].includes(a.type_code)&&!a.system_key,balanceGuard:Boolean(a.balance_guard),monthly:money(a.balance_guard?100:0),state:'configured_pending_billing'}}))}); } return {entities,catalogue:PACKAGES.map(p=>({...p,monthly:money(p.monthly),extraFee:money(p.extraFee)})),termsVersion:BANK_VERSION,admin:{canView:context.readAdmin,canManage:context.manageAdmin},server:{state:'not_linked',name:'Game server account',message:'The game bank is not connected. No game balances or transactions are imported.'},billing:{state:'planned',message:'Monthly fees are disclosed in the package catalogue. Automated billing is not enabled in this foundation batch.'}}; } diff --git a/website/node/public-organisations.mjs b/website/node/public-organisations.mjs index f8fe3649..4f799d3b 100644 --- a/website/node/public-organisations.mjs +++ b/website/node/public-organisations.mjs @@ -1,14 +1,15 @@ +import {companyEmblemUrl} from '../control-panel/company-emblems.mjs'; import {identity} from './auth.mjs'; import {readGovernmentOffices} from './public-government.mjs'; const assets='https://www.dunerealms.com/assets/'; // Public projections contain no account identifiers, private keys or financial records. export async function readPublicOrganisations(db,kind,now=Date.now()){ - if(kind==='politics')return (await readGovernmentOffices(db,now)).map(o=>({id:o.key,tag:o.key,name:o.scope,description:o.description,emblem:o.art?.startsWith('https://')?o.art:assets+'seals/'+o.art,owner_username:o.holder?.username,owner_name:o.holder?.name,member_count:o.holder?1:0,institution_key:o.key,standing:o.state,realm:o.chamber,created_at:null,term:o.term,members:o.holder?[{username:o.holder.username,title:o.name}]:[]})); + if(kind==='politics')return (await readGovernmentOffices(db,now)).map(o=>({id:o.key,tag:o.key,name:o.scope,description:o.description,emblem:o.art?.startsWith('https://')?o.art:assets+'seals/'+o.art,owner_username:o.holder?.username,owner_name:o.holder?.name,member_count:o.holder?1:0,institution_key:o.key,standing:'Royal Office',charterKind:'royal',officeState:o.state,realm:o.chamber,created_at:null,term:o.term,members:o.holder?[{username:o.holder.username,title:o.name}]:[]})); if(kind!=='company')throw TypeError('Unknown organisation register'); if(db.companyDeedsEnabled){ const {results=[]}=await db.prepare("SELECT c.id,c.slug,c.name,c.description,c.created_at,d.charter_kind,a.username AS owner_username,a.display_name AS owner_name,(SELECT COUNT(*) FROM site_company_members m WHERE m.company_id=c.id)+CASE WHEN c.ceo_account_id IS NOT NULL AND EXISTS(SELECT 1 FROM site_accounts x WHERE x.id=c.ceo_account_id) AND NOT EXISTS(SELECT 1 FROM site_company_members m WHERE m.company_id=c.id AND m.user_id=c.ceo_account_id) THEN 1 ELSE 0 END AS member_count FROM corrino_companies c JOIN site_company_deeds d ON d.company_id=c.id LEFT JOIN site_accounts a ON a.id=d.owner_account_id AND a.password_hash NOT LIKE '!%' WHERE c.status='active' ORDER BY c.name").all(); const {results:members=[]}=await db.prepare("SELECT c.id company_id,u.username,u.display_name,CASE WHEN u.id=d.owner_account_id THEN 'Company owner' WHEN u.id=c.ceo_account_id THEN 'Chief Executive' ELSE 'Member' END title FROM corrino_companies c JOIN site_company_deeds d ON d.company_id=c.id JOIN site_accounts u ON (u.id=c.ceo_account_id OR EXISTS(SELECT 1 FROM site_company_members m WHERE m.company_id=c.id AND m.user_id=u.id)) WHERE c.status='active' AND u.password_hash NOT LIKE '!%' ORDER BY c.id,u.username").all(); - return results.map(({id,...c})=>({...c,id:c.slug,tag:c.slug,member_count:Number(c.member_count),emblem:assets+'guild.webp',standing:{basic:'Basic Company',original:'Keyed Company',royal:'Royal Company'}[c.charter_kind]||'Company',realm:'Spacing Guild · Commerce',members:members.filter(m=>m.company_id===id).map(m=>({username:m.username,name:m.display_name||m.username,title:m.title}))})); + return results.map(({id,...c})=>({...c,id:c.slug,tag:c.slug,member_count:Number(c.member_count),emblem:companyEmblemUrl(id),standing:{basic:'Basic Company',original:'Keyed Company',royal:'Royal Company'}[c.charter_kind]||'Company',realm:'Spacing Guild · Commerce',members:members.filter(m=>m.company_id===id).map(m=>({username:m.username,name:m.display_name||m.username,title:m.title}))})); } const {results=[]}=await db.prepare("SELECT c.slug,c.name,c.description,c.created_at,a.username AS owner_username,a.display_name AS owner_name FROM corrino_companies c LEFT JOIN site_accounts a ON a.id=c.ceo_account_id AND a.password_hash NOT LIKE '!%' WHERE c.status='active' ORDER BY c.name").all(); return results.map(c=>({...c,id:c.slug,tag:c.slug,emblem:assets+'guild.webp',standing:'Registered company',realm:'Spacing Guild · Commerce',member_count:null,members:c.owner_username?[{username:c.owner_username,title:'Chief Executive'}]:[]})); diff --git a/website/node/public/passport.css b/website/node/public/passport.css index 4cb548b2..5b884219 100644 --- a/website/node/public/passport.css +++ b/website/node/public/passport.css @@ -9,3 +9,5 @@ #passport-title,.profile-holding-box h3,.profile-holding-box a{font-family:'Cinzel','Palatino Linotype',serif;font-weight:600;letter-spacing:.025em;text-wrap:balance} .profile-holding-box{position:relative;overflow:hidden}.profile-holding-box:after{content:'';position:absolute;right:16px;top:14px;width:68px;height:68px;pointer-events:none;opacity:.12;background:url('/assets/imperial-seal-128.png') center/contain no-repeat}.profile-holding-box h3{position:relative;z-index:1;padding-right:50px;font-family:'Cinzel','Palatino Linotype',serif;font-weight:600}.profile-holding-link{text-decoration:none;font-family:'Cinzel','Palatino Linotype',serif;letter-spacing:.015em}.profile-holding-link:hover{color:#fff0bb}.profile-holding-link .profile-appointment-seal{width:64px;height:64px;filter:drop-shadow(0 4px 6px #0007)}.profile-deed-icon{display:block;width:76px;height:76px;flex:0 0 76px;background:url('https://cp.dunerealms.com/assets/organisation-deeds-clan-tiers-v1.png') left center/300% 100% no-repeat;filter:drop-shadow(0 4px 6px #0007)}.profile-deed-original{background-position:center}.profile-deed-royal{background-position:right} + +.profile-deed-entity-company{background-image:url('https://cp.dunerealms.com/assets/organisation-deeds-company-tiers-v1.png')}.profile-deed-entity-politics{background-image:url('/assets/imperial-seal-128.png');background-size:contain;background-position:center} diff --git a/website/node/public/passport.js b/website/node/public/passport.js index cbcf5bd0..933816d0 100644 --- a/website/node/public/passport.js +++ b/website/node/public/passport.js @@ -16,7 +16,7 @@ function render(p){ text('forum',p.forum?.status==='linked'?p.forum.username:'Not linked'); if(typeof p.avatar==='string'&&/^https:\/\/cp\.dunerealms\.com\/api\/avatars\//.test(p.avatar)){$('avatar').src=p.avatar;$('avatar').hidden=false;} for(const rank of p.ranks||[]){if(rank.label==='Unknown rank')continue;const chip=el('span',rank.label,'chip');chip.dataset.staff=String(rank.key.startsWith('org_'));$('ranks').append(chip);} - const holdingHost=$('holdings');if(holdingHost){holdingHost.replaceChildren();const h=p.holdings||{};for(const [title,rows]of [['Leader of · Clans',h.clans],['Owner of · Companies',h.companies],['Registered deeds',h.deeds],['Daughter clans',h.subhouses]]){const box=el('article',null,'profile-holding-box');box.append(el('h3',title));for(const record of rows||[]){const link=el('a',record.name,'profile-holding-link');link.href=record.url+(title==='Registered deeds'?'#ownership-deed':'');if(title==='Registered deeds'){const deed=el('span',null,'profile-deed-icon profile-deed-'+record.kind);deed.setAttribute('aria-hidden','true');link.prepend(deed);}else if(record.emblem){const logo=el('img');logo.src=record.emblem;logo.alt='';logo.width=logo.height=48;link.prepend(logo);}box.append(link);if(record.basis)box.append(el('small',record.basis));}if(!rows?.length)box.append(el('p',h.state==='unavailable'||(title.includes('Companies')?h.companiesState:h.clansState)==='unavailable'?'Register temporarily unavailable.':'No records in this register.','muted'));holdingHost.append(box);}if(h.appointments?.length){const box=el('article',null,'profile-holding-box');box.append(el('h3','Dynastic appointments'));for(const appointment of h.appointments){const link=el('a',appointment.address,'profile-holding-link');link.href=appointment.url;const seal=el('img');seal.src='https://www.dunerealms.com/assets/imperial-seal-128.png';seal.alt='';seal.width=seal.height=64;seal.className='profile-appointment-seal';link.prepend(seal);box.append(link);}holdingHost.append(box);}} + const holdingHost=$('holdings');if(holdingHost){holdingHost.replaceChildren();const h=p.holdings||{};for(const [title,rows]of [['Leader of · Clans',h.clans],['Owner of · Companies',h.companies],['Registered deeds',h.deeds],['Daughter entities',h.subhouses]]){const box=el('article',null,'profile-holding-box');box.append(el('h3',title));for(const record of rows||[]){const link=el('a',record.name,'profile-holding-link');link.href=record.url+(title==='Registered deeds'?'#ownership-deed':'');if(title==='Registered deeds'){const deed=el('span',null,'profile-deed-icon profile-deed-'+record.kind+' profile-deed-entity-'+(record.entityKind||'clan'));deed.setAttribute('aria-hidden','true');link.prepend(deed);}else if(record.emblem){const logo=el('img');logo.src=record.emblem;logo.alt='';logo.width=logo.height=48;link.prepend(logo);}box.append(link);if(record.basis)box.append(el('small',record.basis));}if(!rows?.length)box.append(el('p',h.state==='unavailable'||(title.includes('Companies')?h.companiesState:h.clansState)==='unavailable'?'Register temporarily unavailable.':'No records in this register.','muted'));holdingHost.append(box);}if(h.appointments?.length){const box=el('article',null,'profile-holding-box');box.append(el('h3','Dynastic appointments'));for(const appointment of h.appointments){const link=el('a',appointment.address,'profile-holding-link');link.href=appointment.url;const seal=el('img');seal.src='https://www.dunerealms.com/assets/imperial-seal-128.png';seal.alt='';seal.width=seal.height=64;seal.className='profile-appointment-seal';link.prepend(seal);box.append(link);}holdingHost.append(box);}} const functions=p.functions||[]; for(const f of functions){const card=el('article',null,'profile-function');card.append(el('strong',f.roleLabel),el('span',f.scopeLabel));$('department').append(card);} if(!functions.length)$('department').append(el('p','No staff functions listed.','muted')); diff --git a/website/node/server.mjs b/website/node/server.mjs index fc83131b..a0d79459 100644 --- a/website/node/server.mjs +++ b/website/node/server.mjs @@ -1,3 +1,4 @@ +import {createCompanyEmblems} from '../control-panel/company-emblems.mjs'; import {initializeCompanyDeeds} from './company-deeds.mjs'; import {createPublicOrganisations} from './public-organisations.mjs'; import {createPublicClans} from './public-clans.mjs'; @@ -59,6 +60,7 @@ export function createApplication(db,settings={}) { const publicModeration={'/api/public/bans':()=>publicBanCards(db),'/api/public/appeals':()=>publicAppealCards(db,request),'/api/public/ban-list':()=>publicBanList(db,request),'/api/public/account-bans':()=>publicAccountBans(db)}; if(Object.hasOwn(publicModeration,url.pathname))return request.method==='GET'?publicModeration[url.pathname]():new Response('Method not allowed',{status:405}); if(url.pathname.startsWith('/memorial/')||['/memorial.css','/memorial.js'].includes(url.pathname))return memorials(request); + if(url.pathname.startsWith('/api/company-emblems/'))return createCompanyEmblems(db)(request); if(/^\/api\/public\/(companies|political-houses)(?:\/|$)/.test(url.pathname))return publicOrganisations(request); if(url.pathname.startsWith('/api/public/clans/'))return publicClans(request); if(/^\/(?:clans\/[a-z0-9]{2,6}|(?:companies|political-houses)(?:\/[a-z0-9_-]{1,64})?)\/?$/i.test(url.pathname)||['/organisation-public.js','/clans.css','/clan-directory-view.mjs','/clan-public.css','/clan-public.js','/clan-dynasty.js','/dynastic-address.mjs','/clan-dynasty.css','/dune-date.js','/dune-date.mjs'].includes(url.pathname)){ diff --git a/website/scripts/provision-unicorp-royal-mail.mjs b/website/scripts/provision-unicorp-royal-mail.mjs new file mode 100644 index 00000000..28b099e1 --- /dev/null +++ b/website/scripts/provision-unicorp-royal-mail.mjs @@ -0,0 +1,8 @@ +import {pathToFileURL} from 'node:url'; +import {applyUnicorpRoyalMailbox,reconcileRoyalCompanyMail} from '../node/company-royal-mail.mjs'; +export async function runUnicorpRoyalMailbox({db,keys,broker,apply=false}){const result=await applyUnicorpRoyalMailbox(db,keys,{apply});if(apply&&result.companyId){await reconcileRoyalCompanyMail(db,broker);return{...result,mailboxState:(await db.prepare('SELECT state FROM site_company_royal_mail WHERE company_id=?').bind(result.companyId).first()).state};}return result;} +if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href){ + if(process.argv.slice(2).some(a=>a!=='--apply'))throw Error('Usage: provision-unicorp-royal-mail.mjs [--apply]'); + const {openDatabase}=await import('../node/mysql.mjs'),{openOrganisationKeyService}=await import('../node/organisation-key-service.mjs'),{internalMailBroker}=await import('../node/internal-mail.mjs'); + const db=await openDatabase(process.env);try{console.log(JSON.stringify(await runUnicorpRoyalMailbox({db,keys:await openOrganisationKeyService(db,process.env),broker:internalMailBroker,apply:process.argv.includes('--apply')})));}finally{await db.close();} +} diff --git a/website/tests/character-identity.test.mjs b/website/tests/character-identity.test.mjs index 402406ff..45677f87 100644 --- a/website/tests/character-identity.test.mjs +++ b/website/tests/character-identity.test.mjs @@ -12,6 +12,8 @@ test('public holdings distinguish clan leadership, dynastic appointment and comp const owner=await memberHoldings(db,{id:'owner',username:'unimatrix999',display_name:'Thomas-Alexander'});assert.equal(owner.address,'Duke Thomas-Alexander of Unimatrix-Artreides');assert.equal(owner.clans.length,1);assert.equal(owner.subhouses.length,1);assert.deepEqual(owner.companies.map(c=>c.id),['founding','shares']);assert.equal(owner.companies[1].basis,'Shareholder');assert(!JSON.stringify(owner).includes('balance')); const heir=await memberHoldings(db,{id:'heir',username:'mr_blueray',display_name:'Blue'});assert.equal(heir.address,'Ducal Heir Blue of Unimatrix-Artreides');assert.equal(heir.clans[0].id,'child'); db.sqlite.exec("UPDATE site_clan_members SET joined_at=2 WHERE user_id='heir'");assert.equal((await memberHoldings(db,{id:'heir',username:'mr_blueray',display_name:'Blue'})).appointments.some(a=>a.role==='heir'),false); + db.sqlite.exec("CREATE TABLE site_company_deeds(company_id TEXT,owner_account_id TEXT,charter_kind TEXT);CREATE TABLE site_company_relations(company_id TEXT,parent_company_id TEXT);INSERT INTO site_company_deeds VALUES('founding','owner','original');INSERT INTO site_company_relations VALUES('ceo','founding');");db.companyDeedsEnabled=true; + const updated=await memberHoldings(db,{id:'owner',username:'unimatrix999',display_name:'Thomas-Alexander'});assert(updated.deeds.some(d=>d.entityKind==='company'&&d.id==='founding'&&d.kind==='original'&&d.url==='https://www.dunerealms.com/companies/founding'));assert(updated.subhouses.some(d=>d.entityKind==='company'&&d.id==='ceo'));assert(updated.subhouses.some(d=>d.id==='child')); }finally{db.close();} }); diff --git a/website/tests/company-emblems.test.mjs b/website/tests/company-emblems.test.mjs new file mode 100644 index 00000000..f1cc7c66 --- /dev/null +++ b/website/tests/company-emblems.test.mjs @@ -0,0 +1,5 @@ +import test from 'node:test';import assert from 'node:assert/strict';import {companyFixture} from './company-deed-fixture.mjs';import {createCompanyEmblems} from '../control-panel/company-emblems.mjs';import {createCompanyWorkspace} from '../node/company-workspace.mjs';import {readPublicOrganisations} from '../node/public-organisations.mjs'; +test('company emblem follows the deed, rejects stale or foreign writes, and appears in CP and public register',async()=>{const f=await companyFixture();try{const id=await f.create(),api=createCompanyEmblems(f.db,{authenticate:async()=>f.currentUser(),normalize:async()=>Buffer.from('webp-image')}),call=(method='GET',version=0,origin='https://cp.dunerealms.com')=>api(new Request('https://cp.dunerealms.com/api/company-emblems/'+id,{method,headers:{origin,'if-match':'"'+version+'"','content-type':'image/png'},...(method==='POST'?{body:new Uint8Array([1,2])}:{})})); +assert.equal((await call()).status,302);f.actor('Other');assert.equal((await call('POST')).status,403);f.actor('Owner');assert.equal((await call('POST',0,'https://wrong.example')).status,403);assert.equal((await call('POST')).status,200);assert.equal(await(await call()).text(),'webp-image');assert.equal((await call('POST')).status,409); +const workspace=createCompanyWorkspace(f.db,{authenticate:async()=>f.currentUser()}),data=await(await workspace(new Request('https://cp.dunerealms.com/api/companies/workspace'))).json();assert.equal(data.companies[0].hasEmblem,true);assert.equal(data.companies[0].emblemVersion,1);assert.match(data.companies[0].emblem,/company-emblems/);assert.match((await readPublicOrganisations(f.db,'company'))[0].emblem,/company-emblems/);assert.equal((await call('DELETE',1)).status,200);assert.equal((await call()).status,302);assert.equal((await f.db.first("SELECT COUNT(*) n FROM corrino_company_events WHERE action LIKE 'emblem-%'")).n,2); +}finally{f.db.close();}}); diff --git a/website/tests/company-mail.test.mjs b/website/tests/company-mail.test.mjs new file mode 100644 index 00000000..d90d2cdd --- /dev/null +++ b/website/tests/company-mail.test.mjs @@ -0,0 +1,6 @@ +import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto';import {companyFixture} from './company-deed-fixture.mjs';import {ownCompanyMailbox,ensureCompanyMailbox} from '../node/internal-mail-companies.mjs';import {clanMailboxId} from '../node/internal-mail-clans.mjs';import {createInternalMail} from '../node/internal-mail.mjs'; +test('company correspondence reuses the original Clan mailbox without broadening Clan access',async()=>{const f=await companyFixture();try{const companyId=await f.create(),clanId=randomUUID();f.db.sqlite.exec('ALTER TABLE site_clans ADD COLUMN tag TEXT;ALTER TABLE site_clan_members ADD COLUMN minecraft_uuid TEXT;');await f.db.query('INSERT INTO site_clans(id,name,tag,owner_id,active) VALUES(?,?,?,?,1)',[clanId,'Original Clan','OLD',f.people.Owner.id]);await f.db.query("INSERT INTO site_clan_members(clan_id,user_id,clan_role) VALUES(?,?,'owner')",[clanId,f.people.Owner.id]);let calls=[];const broker=async p=>{calls.push(p);return{ok:true,address:p.userId+'.internal@dunerealms.com',total:3,messages:[]};};const source=await ownCompanyMailbox(f.db,f.people.Owner,companyId);assert.equal(source.clanId,clanId);const mailbox=await ensureCompanyMailbox(source,broker,f.db);assert.equal(mailbox.userId,clanMailboxId(clanId));assert.equal(calls[0].mailboxKind,'clan');assert.equal(calls[0].resourceId,clanId);assert.equal(await ownCompanyMailbox(f.db,f.people.Other,companyId),null); +const api=createInternalMail(f.db,{getIdentity:async()=>f.currentUser(),eligible:async()=>true,broker}),call=(path,body)=>api(new Request('https://cp.dunerealms.com/api/internal-mail/'+path,{method:'POST',headers:{origin:'https://cp.dunerealms.com','content-type':'application/json'},body:JSON.stringify({scope:'company',companyId,...body})}));assert.equal((await call('messages/list',{folder:'INBOX',limit:1,unread:true})).status,200);assert.equal(calls.at(-1).userId,clanMailboxId(clanId));assert.equal((await call('password/reveal',{})).status,403);f.actor('Other');calls=[];assert.equal((await call('messages/list',{})).status,403);assert.equal(calls.length,0); +}finally{f.db.close();}}); + +test('created subsidiaries inherit and pin mother mail, while bought or conquered subsidiaries keep their origin',async()=>{const f=await companyFixture();try{const {companyMailboxClan}=await import('../node/internal-mail-companies.mjs');const mother=await f.create(),home=randomUUID(),foreign=randomUUID();await f.db.query('INSERT INTO site_clans(id,name,owner_id,active) VALUES(?,?,?,1)',[home,'Home',f.people.Owner.id]);assert.equal(await companyMailboxClan(f.db,mother),home);await f.db.query('INSERT INTO site_clans(id,name,owner_id,active) VALUES(?,?,?,1)',[foreign,'Foreign',f.people.Other.id]);for(const [origin,n] of [['created',0],['purchased',1],['conquered',2]]){const id=randomUUID();await f.db.query("INSERT INTO corrino_companies(id,slug,name,description,founded_by,status,created_at,updated_at) VALUES(?,?,?,'',?,'active',1,1)",[id,'child-'+n,'Child '+n,f.people.Other.id]);await f.db.query('INSERT INTO site_company_relations(company_id,parent_company_id,relation_origin,updated_at) VALUES(?,?,?,1)',[id,mother,origin]);assert.equal(await companyMailboxClan(f.db,id),origin==='created'?home:foreign);if(origin==='created'){await f.db.query("UPDATE site_company_relations SET relation_origin='purchased' WHERE company_id=?",[id]);assert.equal(await companyMailboxClan(f.db,id),home);}}}finally{f.db.close();}}); diff --git a/website/tests/company-royal-mail.test.mjs b/website/tests/company-royal-mail.test.mjs new file mode 100644 index 00000000..40fc4d71 --- /dev/null +++ b/website/tests/company-royal-mail.test.mjs @@ -0,0 +1,3 @@ +import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto';import {companyFixture} from './company-deed-fixture.mjs';import {runUnicorpRoyalMailbox} from '../scripts/provision-unicorp-royal-mail.mjs';import {readRoyalCompanyMailbox} from '../node/company-royal-mail.mjs';import {ownCompanyMailbox,ensureCompanyMailbox} from '../node/internal-mail-companies.mjs';import {STAFF_OFFICE_ACCOUNT_ID} from '../node/organisation-keys.mjs'; +test('Unicorp Royal mailbox script checks the original key, applies one staff key and provisions a separate inbox idempotently',async()=>{const f=await companyFixture();try{const runtimeDb={prepare:f.db.prepare,query:f.db.query.bind(f.db),transaction:f.db.transaction.bind(f.db)};const id=await f.create();await f.db.query("UPDATE corrino_companies SET slug='unicorp',name='Unicorp' WHERE id=?",[id]);await f.db.query("UPDATE site_accounts SET username='unimatrix999' WHERE id=?",[f.people.Owner.id]);const brokerCalls=[],broker=async input=>{brokerCalls.push(input);return{ok:true,address:'unicorp.internal@dunerealms.com'};};await assert.rejects(runUnicorpRoyalMailbox({db:runtimeDb,keys:f.keys,broker,apply:true}),/original Company deed/);const key=await f.keys.issue({accountId:f.people.Owner.id,keyType:'company-founding',scopeId:'original'});assert.equal((await f.call(id,{action:'upgrade',code:key.code,version:1,requestId:randomUUID(),confirmed:true})).status,200);const plan=await runUnicorpRoyalMailbox({db:runtimeDb,keys:f.keys,broker});assert.equal(plan.desiredCharter,'royal');assert.equal(brokerCalls.length,0);const applied=await runUnicorpRoyalMailbox({db:runtimeDb,keys:f.keys,broker,apply:true});assert.equal(applied.mailboxState,'active');assert.equal(applied.changed,true);const source=await readRoyalCompanyMailbox(runtimeDb,id);assert(source.mailbox_id);const company=await ownCompanyMailbox(f.db,f.people.Owner,id);assert.equal(company.separate,true);assert.equal((await ensureCompanyMailbox(company,broker,f.db)).userId,source.mailbox_id);assert.equal((await runUnicorpRoyalMailbox({db:runtimeDb,keys:f.keys,broker,apply:true})).changed,false);assert.equal(brokerCalls.length,1);const staff=await f.keys.list(STAFF_OFFICE_ACCOUNT_ID);assert.equal(staff.length,1);assert.equal(staff[0].status,'used');assert.equal(staff[0].targetId,id);assert.equal((await f.db.first('SELECT charter_kind FROM site_company_deeds WHERE company_id=?',[id])).charter_kind,'royal');assert.equal((await f.db.first("SELECT COUNT(*) n FROM corrino_company_events WHERE action='staff-royal-upgrade'")).n,1);await f.db.query('UPDATE organisation_keys SET revoked_at=? WHERE id=?',[Date.now(),staff[0].id]);assert.equal(await readRoyalCompanyMailbox(runtimeDb,id),null); +}finally{f.db.close();}}); diff --git a/website/tests/cp-v2-post-menu.test.mjs b/website/tests/cp-v2-post-menu.test.mjs index 103f5bcc..e3da3313 100644 --- a/website/tests/cp-v2-post-menu.test.mjs +++ b/website/tests/cp-v2-post-menu.test.mjs @@ -7,7 +7,7 @@ import {nativeServiceURL} from '../control-panel/public/cp-v2/cp-v2-native-servi test('left Post menu contains exactly the authorised inboxes, followed by Request inbox',()=>{ const data={eligible:true,clan:{name:'House Unimatrix'},faction:{name:'House Korenholt'},imperial:true,staff:true}; - const items=mailboxMenu(data);assert.deepEqual(items.map(row=>row.id),['mail-inbox','clan-inbox','faction-inbox','imperial-inbox','staff-inbox','mail-request']);assert.equal(items[1].label,'House Unimatrix');assert.equal(items[2].label,'House Korenholt'); + const items=mailboxMenu(data);assert.deepEqual(items.map(row=>row.id),['mail-inbox','clan-inbox','faction-inbox','imperial-inbox','staff-inbox','mail-request']);assert.equal(items[1].label,'Clan / Company');assert.equal(items.find(i=>i.id==='imperial-inbox').label,'Office mail');assert.equal(items[2].label,'House Korenholt'); assert.deepEqual(mailboxMenu({eligible:true}).map(row=>row.id),['mail-inbox','mail-request']);assert.throws(()=>mailboxMenu({eligible:false})); }); test('each inbox opens only its fixed scope and moves the redundant tabs out of the embedded client',()=>{ diff --git a/website/tests/political-office-charters.test.mjs b/website/tests/political-office-charters.test.mjs new file mode 100644 index 00000000..fc9b68ec --- /dev/null +++ b/website/tests/political-office-charters.test.mjs @@ -0,0 +1,3 @@ +import test from 'node:test';import assert from 'node:assert/strict';import {companyFixture} from './company-deed-fixture.mjs';import {ensurePoliticalOfficeCharters,politicalOfficeId} from '../node/political-office-charters.mjs';import {PUBLIC_OFFICES} from '../node/public-government.mjs';import {STAFF_OFFICE_ACCOUNT_ID} from '../node/organisation-keys.mjs'; +test('protected offices receive one automatically applied staff Royal charter, including vacant offices',async()=>{const f=await companyFixture();try{const first=await ensurePoliticalOfficeCharters(f.db,f.keys);assert.equal(first.applied,PUBLIC_OFFICES.length);assert.equal((await ensurePoliticalOfficeCharters(f.db,f.keys)).applied,0);const keys=await f.keys.list(STAFF_OFFICE_ACCOUNT_ID);assert.equal(keys.length,PUBLIC_OFFICES.length);assert(keys.every(k=>k.keyType==='staff-office-royal'&&k.status==='used'&&k.code===null));for(const o of PUBLIC_OFFICES){const deed=await f.db.first('SELECT * FROM political_office_charters WHERE office_key=?',[o.key]);assert.equal(deed.charter_kind,'royal');assert.equal(deed.organisation_id,politicalOfficeId(o.key));assert(keys.some(k=>k.id===deed.staff_key_id&&k.targetId===deed.organisation_id));}assert.equal((await f.keys.list(f.people.Owner.id)).length,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM political_office_terms')).n,0);await assert.rejects(f.keys.issue({accountId:f.people.Owner.id,keyType:'staff-office-royal',scopeId:'office:emperor',authorize:async()=>{}}),/system issuer/); +}finally{f.db.close();}}); From 706f66849c56033013807c57b46d8b45c673c677 Mon Sep 17 00:00:00 2001 From: unimatrix Date: Wed, 18 Nov 2026 01:42:26 +0000 Subject: [PATCH 2/2] Resolve authorised Unicorp rollout by its registered owner and unique name --- docs/design/COMPANY-CLONE-PARITY.md | 2 +- website/node/company-royal-mail.mjs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/design/COMPANY-CLONE-PARITY.md b/docs/design/COMPANY-CLONE-PARITY.md index 231bd0bf..3cdce4e8 100644 --- a/docs/design/COMPANY-CLONE-PARITY.md +++ b/docs/design/COMPANY-CLONE-PARITY.md @@ -13,7 +13,7 @@ the mother's mailbox; acquired entities retain their previous mailbox origin. Company creation triggers provisioning and the existing reconciler retries it. No message contents are moved or deleted. Full transfer execution is separate work. -Unicorp's explicitly authorised rollout checks its exact slug/name, active deed, +Unicorp's explicitly authorised rollout checks its unique name, active deed, owner unimatrix999 and previously consumed original COM key. One staff Company Royal key upgrades its deed and queues a separate mailbox. The mail reconciler provisions it; repeats create no duplicate key or mailbox. Revocation or lost diff --git a/website/node/company-royal-mail.mjs b/website/node/company-royal-mail.mjs index 053618a1..e184b61a 100644 --- a/website/node/company-royal-mail.mjs +++ b/website/node/company-royal-mail.mjs @@ -2,7 +2,7 @@ import {createHash,randomUUID} from 'node:crypto'; import {STAFF_OFFICE_ACCOUNT_ID,OrganisationKeyError} from './organisation-keys.mjs'; export const COMPANY_ROYAL_MAIL_SCHEMA=`CREATE TABLE IF NOT EXISTS site_company_royal_mail (company_id CHAR(36) PRIMARY KEY,royal_key_id CHAR(36) NOT NULL UNIQUE,mailbox_id CHAR(36) NOT NULL UNIQUE,state VARCHAR(12) NOT NULL,updated_at BIGINT NOT NULL)`; export function separateCompanyMailboxId(id){const h=createHash('sha256').update('dunerealms:royal-company-mail:'+id).digest('hex');return h.slice(0,8)+'-'+h.slice(8,12)+'-4'+h.slice(13,16)+'-8'+h.slice(17,20)+'-'+h.slice(20,32);} -const targetSql="SELECT c.id,c.name,c.slug,c.status,d.owner_account_id,d.charter_kind,d.original_key_id FROM corrino_companies c JOIN site_company_deeds d ON d.company_id=c.id JOIN site_accounts a ON a.id=d.owner_account_id WHERE c.slug='unicorp' AND LOWER(c.name)='unicorp' AND LOWER(a.username)='unimatrix999' AND a.password_hash NOT LIKE '!%'"; +const targetSql="SELECT c.id,c.name,c.slug,c.status,d.owner_account_id,d.charter_kind,d.original_key_id FROM corrino_companies c JOIN site_company_deeds d ON d.company_id=c.id JOIN site_accounts a ON a.id=d.owner_account_id WHERE LOWER(c.name)='unicorp' AND LOWER(a.username)='unimatrix999' AND a.password_hash NOT LIKE '!%'"; const first=(db,sql,args=[])=>typeof db.first==='function'?db.first(sql,args):db.prepare(sql).bind(...args).first(); async function verifyOriginal(tx,c){ const original=c&&await first(tx,"SELECT id FROM organisation_keys WHERE id=? AND key_type='company-founding' AND target_id=? AND used_at IS NOT NULL AND revoked_at IS NULL",[c.original_key_id,c.id]);