diff --git a/docs/design/HOME-BLOCK-WEB-UPGRADE.md b/docs/design/HOME-BLOCK-WEB-UPGRADE.md new file mode 100644 index 00000000..d2f73f02 --- /dev/null +++ b/docs/design/HOME-BLOCK-WEB-UPGRADE.md @@ -0,0 +1,42 @@ +# One Home Block upgrade command, two entry points + +The temporary web Upgrade claims button is functional with an explicitly fake +WorldGuard/bank provider. It reviews the next sequential tier and confirms an +idempotent server command. Fake organisation credit pays the fake Tax treasury; +real land, account balances and clan tier records are untouched. State is +temporary, bounded and resets on process restart/expiry. + +Shared business handler: `node/claim-command-service.mjs`. HTTP authentication +adapter: `control-panel/claim-home-block-route.mjs`. Web entry: +`cp-v2-home-block.mjs`. Keep this same business command for the future ingame +right-click; add authenticated game proof rather than copying the upgrade logic. + +- GET `/api/v1/claims/home-blocks` returns the authorised owner's simulated block. +- POST `/api/v1/claims/home-blocks/{id}/commands` accepts action + `claim.tier.upgrade`, requestId, expectedRevision, targetTier, tariffVersion, + expectedUnlockMinor and confirmed=true. Actor/organisation/recipient are derived + by the server, never supplied as arbitrary request overrides. +- Lock one block command at a time. Exact retries return the existing receipt; + stale versions, changed prices and skipped tiers fail. Basic stops before KC_T0 + until its trusted charter context confirms an original key. +- Capacity upgrades do not automatically claim spare chunks. The fake region + snapshot retains the existing claimed area. Real bank/game adapters must + coordinate durable confirmation and reconciliation; pending is not applied. + +Current website access is the linked ordinary clan owner. Delegated mother-house +authority, company/royal providers, real settlement and real WorldGuard changes +remain later work. The real payer is always the relevant organisation, including +the original daughter when the mother acts. Upkeep/unlocks route to +`sys_tax_treasury` through existing banking components later. + +Broader agreed boundaries: clans are for PvP, companies for economic roleplay. +Companies may contract clans for protection/operations without gaining PvP or +bypassing conquest eligibility. Financial identities remain separate over time. +Basic has no internal organisation Exchange; Keyed unlocks it. Personal Exchange +access is unaffected. Kits may be Exchange products with buyer-owned redeem codes; +resale needs an authoritative entitlement transfer, not merely sharing a code. +These future Exchange/kit rules are recorded, not implemented by this batch. + +Focused checks cover repeat requests, concurrent clicks, stale/forged commands, +Basic eligibility, test Tax routing and a working browser confirmation at desktop, +tablet and mobile widths. Comprehensive game/transfer tests remain the later run. diff --git a/website/control-panel/claim-home-block-route.mjs b/website/control-panel/claim-home-block-route.mjs new file mode 100644 index 00000000..fac600ca --- /dev/null +++ b/website/control-panel/claim-home-block-route.mjs @@ -0,0 +1,25 @@ +import {identity} from '../node/auth.mjs'; +import {accessFor} from '../node/permissions.mjs'; +import {createClaimSimulation,ClaimCommandError} from '../node/claim-command-service.mjs'; +const json=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}}); +export function createClaimHomeBlockRoute(db,settings={},deps={}){ + const simulation=deps.service||createClaimSimulation(),authenticate=deps.authenticate||(r=>identity(r,db)),access=deps.access||(u=>accessFor(db,u)),origin=new URL(settings.CP_ORIGIN||'https://cp.dunerealms.com').origin; + return async request=>{ + const url=new URL(request.url),command=url.pathname.match(/^\/api\/v1\/claims\/home-blocks\/([a-f0-9-]{36})\/commands$/i); + if(url.search||(!command&&url.pathname!=='/api/v1/claims/home-blocks'))return json({message:'Not found.'},404); + if(request.method!==(command?'POST':'GET'))return json({message:'Method not allowed.'},405); + const user=await authenticate(request);if(!user)return json({message:'Sign in to open your Home Block.'},401); + if(!(await access(user)).nodes.includes('web.menu.game'))return json({message:'Game access is required.'},403); + if(settings.CLAIM_WEB_SIMULATION_ENABLED==='false')return json({enabled:false,message:'The Home Block simulation is disabled.'}); + const clan=await db.prepare("SELECT c.id,c.name,i.institution_key FROM site_clans c JOIN site_clan_members m ON m.clan_id=c.id AND m.user_id=c.owner_id AND m.clan_role='owner' JOIN site_game_links l ON l.user_id=m.user_id AND l.minecraft_uuid=m.minecraft_uuid LEFT JOIN site_clan_institutions i ON i.clan_id=c.id WHERE c.active=1 AND c.owner_id=?").bind(user.id).first(); + if(!clan||clan.institution_key)return json({enabled:false,message:'A linked owner of an ordinary clan can use this web simulation.'},command?403:200); + let charter='basic';if(settings.CLAN_KEYS_ENABLED==='true'){const row=await db.prepare('SELECT charter_kind FROM site_clan_charters WHERE clan_id=?').bind(clan.id).first();if(row?.charter_kind==='original')charter='original';} + const context={userId:user.id,organisationId:clan.id,name:clan.name,kind:'clan',charter}; + try{ + if(!command){const homeBlock=await simulation.read(context);return json({enabled:true,simulation:homeBlock.simulation,homeBlock});} + if(request.headers.get('origin')!==origin||!/^application\/json(?:\s*;|$)/i.test(request.headers.get('content-type')||''))return json({message:'Request origin or format rejected.'},403); + let body;try{body=await request.json();}catch{return json({message:'Invalid command.'},400);} + return json(await simulation.upgrade(context,command[1],body)); + }catch(error){return json({message:error instanceof ClaimCommandError?error.message:'The Home Block could not be confirmed.'},error instanceof ClaimCommandError?error.status:503);} + }; +} diff --git a/website/control-panel/public/cp-v2/cp-v2-claims.mjs b/website/control-panel/public/cp-v2/cp-v2-claims.mjs index be37431e..93e1a6a0 100644 --- a/website/control-panel/public/cp-v2/cp-v2-claims.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-claims.mjs @@ -1,14 +1,16 @@ +import {createDeedArtwork} from './cp-v2-deed-art.mjs'; +import {createHomeBlockUpgrade} from './cp-v2-home-block.mjs'; import {element as el} from './cp-v2-page-template.mjs'; import {claimTariffs,claimMoney,CLAIM_TARIFF_VERSION,BASIC_POLITICAL_NOTICE,ORGANISATION_TRANSFER_NOTICE} from './cp-v2-claim-tariffs.mjs'; export function mountClaims(host,{kind='clan',name='Your organisation'}={}){ const root=el('section',undefined,'claims-workspace'),hero=el('div',undefined,'claims-banner');hero.append(el('small','LAND & ESTATES'),el('h2',name+' · Claims'),el('p',kind==='company'?'Company premises and Charter Beacons.':'Clan estates, Home Standards and outposts.')); root.append(hero,el('p','Land claims are coming soon. No land is reserved and no payment is taken from this page.','claims-notice')); - const rules=el('div',undefined,'claims-grid');for(const [title,copy]of [['One shared claim budget','Every chunk is 16 × 16 blocks. Limits count all chunks claimed by your organisation, not a radius or a separate allowance for each estate.'],['Basic → Keyed → Royal','Start Basic. Your original organisation key enables mother-house status; Royal status requires a political appointment and its new POL-key.'],['Upgrade at your Home Block','Claim-tier upgrades are performed ingame by right-clicking your Home Block. This website displays information; it does not buy or apply claim upgrades.'],['Subhouse rights & costs','The mother house controls subordinate claim rights and management. The original organisation pays upkeep and upgrades, even when the mother performs the upgrade. Rights are never counted twice. Planned payment authority reuses Imperial Postbank mandates; bank-account ownership does not transfer.'],['WorldGuard bridge','Future game protection uses the central API and a DuneProtect/WorldGuard adapter. No regions are created or resized by this preview.']]){const card=el('article',undefined,'claims-card');card.append(el('h3',title),el('p',copy));rules.append(card);}root.append(rules); + const rules=el('div',undefined,'claims-grid');for(const [title,copy]of [['One shared claim budget','Every chunk is 16 × 16 blocks. Limits count all chunks claimed by your organisation, not a radius or a separate allowance for each estate.'],['Basic → Keyed → Royal','Start Basic. Your original organisation key enables mother-house status; Royal status requires a political appointment and its new POL-key.'],['Upgrade at your Home Block','Claim-tier upgrades are performed ingame by right-clicking your Home Block. The temporary web button simulates that same command using fake data until the game bridge is ready.'],['Subhouse rights & costs','The mother house controls subordinate claim rights and management. The original organisation pays upkeep and upgrades, even when the mother performs the upgrade. Rights are never counted twice. Planned payment authority reuses Imperial Postbank mandates; bank-account ownership does not transfer.'],['WorldGuard bridge','Future game protection uses the central API and a DuneProtect/WorldGuard adapter. No regions are created or resized by this preview.']]){const card=el('article',undefined,'claims-card');card.append(el('h3',title),el('p',copy));rules.append(card);}root.append(rules);const homeBlock=kind==='clan'?createHomeBlockUpgrade():null;if(homeBlock)root.append(homeBlock.root); const charter=el('section',undefined,'claims-card'),choice=el('select'),label=el('label','Tariff reference · this does not assign your organisation a tier'),tableWrap=el('div',undefined,'claim-preview-scroll'),table=el('table',undefined,'claim-preview-table');choice.setAttribute('aria-label','Claim tariff reference');for(const [value,title]of kind==='company'?[['company','Company tariffs']]:[['clan','Clan tariffs'],['protected','Protected House tariffs']]){const option=el('option',title);option.value=value;choice.append(option);}label.append(choice);tableWrap.tabIndex=0;tableWrap.setAttribute('role','region');tableWrap.setAttribute('aria-label','Planned claim tier prices');tableWrap.append(table);charter.append(el('h3','Claim charter & capacity'),el('p','Current tier, used chunks, available capacity, Home Block and payment status: not connected yet.'),label,tableWrap,el('p','Upkeep is monthly; unlock prices are paid once per sequential tier. Company capacity/costs × 1.5; protected capacity × 1.5 and costs × 0.5. Capacity rounds down to whole chunks.'));const rates=el('a','Open the full Rates & Charges guide →');rates.href='https://www.dunerealms.com/rates-and-charges.html#claims';rates.target='_top';charter.append(rates,el('small','Published preview · '+CLAIM_TARIFF_VERSION)); - function paint(){const head=el('thead'),heading=el('tr'),body=el('tbody');for(const text of ['Tier','Total chunks','Monthly upkeep','One-time unlock','Status requirement']){const cell=el('th',text);cell.scope='col';heading.append(cell);}head.append(heading);for(const row of claimTariffs(choice.value)){const tr=el('tr');tr.append(el('th',row.code),el('td',row.chunks),el('td',claimMoney(row.upkeepMinor)),el('td',claimMoney(row.unlockMinor)),el('td',row.requirement||'Previous tier'));body.append(tr);}table.replaceChildren(head,body);}choice.onchange=paint;paint();root.append(charter); + function paint(){const head=el('thead'),heading=el('tr'),body=el('tbody');for(const text of ['Tier','Total chunks','Monthly upkeep','One-time unlock','Status requirement']){const cell=el('th',text);cell.scope='col';heading.append(cell);}head.append(heading);for(const row of claimTariffs(choice.value)){const tr=el('tr');tr.append(el('th',row.code),el('td',row.chunks),el('td',claimMoney(row.upkeepMinor)),el('td',claimMoney(row.unlockMinor)),el('td',row.requirement||'Previous tier'));body.append(tr);}table.replaceChildren(head,body);}choice.onchange=()=>{paint();deed.replaceWith(deed=createDeedArtwork(choice.value));};let deed=createDeedArtwork(kind);paint();charter.prepend(deed);root.append(charter); const policy=el('section',undefined,'claims-card');policy.append(el('h3','Rights & planned Transfer of Power'),el('p',BASIC_POLITICAL_NOTICE),el('p',ORGANISATION_TRANSFER_NOTICE),el('p','Claim upkeep and unlocks go to the Tax treasury. Transfer and loan workflows are planned; no transaction is performed here.'));root.append(policy); const grid=el('div',undefined,'claims-grid'); for(const [title,copy,action]of [['Estates','Your registered land and ownership records will appear here.','View estates'],['Home Block & anchors','Your Home Block, location and WorldGuard synchronisation status will appear here. Right-click the Home Block ingame to upgrade claim capacity.','View Home Block'],['Boundaries','Preview estate borders and check neighbouring claims. The game bridge applies verified protection changes.','View boundaries'],['Upkeep & payments','Your applied tier, monthly upkeep and payment history will appear here. Claim upgrades are initiated ingame.','View upkeep']]){ const card=el('article',undefined,'claims-card'),button=el('button',action);button.type='button';button.disabled=true;button.title='Coming soon';card.append(el('h3',title),el('p',copy),el('strong','Coming soon'),button);grid.append(card); - }root.append(grid);host.replaceChildren(root);return()=>root.remove(); + }root.append(grid);host.replaceChildren(root);return()=>{homeBlock?.dispose();root.remove();}; } diff --git a/website/control-panel/public/cp-v2/cp-v2-code-redemption.mjs b/website/control-panel/public/cp-v2/cp-v2-code-redemption.mjs index 4d56fa0a..f1dbb112 100644 --- a/website/control-panel/public/cp-v2/cp-v2-code-redemption.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-code-redemption.mjs @@ -1,34 +1,35 @@ -import {element as el} from './cp-v2-page-template.mjs'; - -// Presentation only. Recognising a format never verifies ownership or grants a right. -export function describeRedemption(value){ - const code=String(value||'').trim().toUpperCase(); - const types=[ - [/^DRK-[A-Z2-7]{32}$/,'kit','Kit delivery','Requests your kit delivery. The game confirms arrival.','Redeem kit',true], - [/^DRQ-[A-F0-9]{40}$/,'discovery','Discovery reward','Claims your earned discovery reward. The service checks eligibility before crediting.','Claim reward',true], - [/^(?:DRU|UP)-[A-F0-9]{48}$/,'token','Upgrade Token','Apply this token to a saved kit in Imperial Tailor.','Open Imperial Tailor',false,'#realm/kits-exchange'], - [/^CLAN-[A-F0-9]{48}$/,'clan','Clan founding right','Upgrades your existing Basic clan to an Original House that can become a mother house. A Royal House requires a separate political appointment.','Clan upgrades coming soon',false], - [/^COM-[A-F0-9]{48}$/,'company','Company founding right','Upgrades your existing Basic company using its separate original founding right.','Company upgrades coming soon',false], - [/^POL-[A-F0-9]{48}$/,'politics','Political appointment','Applies the specific appointment recorded by a political decision. The decision determines the organisation and title.','Political appointments coming soon',false] - ]; - for(const [pattern,kind,title,description,action,available,href] of types)if(pattern.test(code))return {code,kind,title,description,action,available,href}; - throw Error('Enter a complete private code. Community commands are used in game.'); -} - -export function createCodeRedemption(){ - let reviewed=null,locked=false; - const root=el('section',undefined,'code-redemption'),hero=el('header',undefined,'reward-code-banner'),art=el('img');art.src='https://www.dunerealms.com/assets/imperial-seal-128.png';art.alt='';const heading=el('div');heading.append(el('small','SPOST · IMPERIAL CODE OFFICE'),el('h4','Present your code. Open your next chapter.'),el('p','Your SPost counter for rewards, founding rights and political appointments.'));hero.append(art,heading); - const layout=el('div',undefined,'code-redemption-layout'),form=el('form',undefined,'code-redemption-card'),entry=el('fieldset'),legend=el('legend','1 · Enter your private code'),label=el('label','Code'),input=el('input');input.type='text';input.autocomplete='off';input.spellcheck=false;input.autocapitalize='characters';input.required=true;input.maxLength=80;input.placeholder='Paste your complete code';input.setAttribute('aria-describedby','redemption-code-help');const help=el('p','Keep your code private. Checking its format does not use it.','code-redemption-muted');help.id='redemption-code-help';label.append(input);const inspect=el('button','Review code');inspect.type='button';entry.append(legend,label,help,inspect); - const preview=el('fieldset',undefined,'code-redemption-preview');preview.hidden=true;preview.append(el('legend','2 · Review & confirm'));const badge=el('span',undefined,'reward-kind'),title=el('h5'),effect=el('p'),verification=el('p','Format recognised. Ownership and eligibility are checked when you submit.','code-redemption-muted'),check=el('input');check.type='checkbox';const consent=el('label',undefined,'code-redemption-consent');consent.append(check,el('span','I understand this action and want to use my code.'));const submit=el('button','Confirm redemption');submit.type='submit';submit.disabled=true;const destination=el('a');destination.hidden=true;preview.append(badge,title,effect,verification,consent,submit,destination);const result=el('p',undefined,'code-redemption-result');result.setAttribute('role','status');result.setAttribute('aria-live','polite');form.append(entry,preview,result); - const guide=el('aside',undefined,'code-redemption-card code-redemption-guide');guide.append(el('small','WHAT CAN YOU PRESENT?'),el('h5','Your code chooses the route.')); - for(const [kind,name,copy] of [['kit','Kits & discoveries','Existing DRK and DRQ codes can be redeemed here.'],['clan','House & company charters','Create your Basic clan first. CLAN and COM codes will unlock the later mother-house and company upgrades.'],['politics','Political appointments','POL codes come from an approved decision. Founding alone does not confer a Royal title.'],['token','Upgrade Tokens','DRU tokens are applied to a saved kit in Imperial Tailor.']]){const card=el('div',undefined,'code-redemption-guide-item');card.append(el('span',name,'reward-kind reward-kind-'+kind),el('p',copy));guide.append(card);}const register=el('a','← View your codes');register.href='#';register.onclick=e=>{e.preventDefault();root.dispatchEvent(new CustomEvent('show-code-register',{bubbles:true}));};guide.append(register);layout.append(form,guide);root.append(hero,layout); - function sync(){submit.disabled=locked||!reviewed?.available||!check.checked;inspect.disabled=locked;input.disabled=locked;check.disabled=locked;} - function invalidate(){reviewed=null;check.checked=false;preview.hidden=true;result.textContent='';sync();} - input.oninput=invalidate;check.onchange=sync; - inspect.onclick=()=>{if(locked)return;try{reviewed=describeRedemption(input.value);check.checked=false;badge.className='reward-kind reward-kind-'+reviewed.kind;badge.textContent=reviewed.available?'Ready to submit':'Dedicated route';title.textContent=reviewed.title;effect.textContent=reviewed.description;submit.textContent=reviewed.action;submit.hidden=!reviewed.available;consent.hidden=!reviewed.available;destination.hidden=!reviewed.href;if(reviewed.href){destination.href=reviewed.href;destination.textContent=reviewed.action;}verification.textContent=reviewed.available?'Format recognised. Ownership and eligibility are checked when you submit.':reviewed.href?'Continue in the dedicated workshop to choose your kit.':'This route is being connected. Your code has not been used.';preview.hidden=false;result.textContent='';sync();}catch(error){invalidate();result.textContent=error.message;input.focus();}}; - return {root,form,input,check,submit,result,setLocked(value){locked=!!value;sync();},reset(){form.reset();invalidate();},reviewedCode(){if(!reviewed?.available||describeRedemption(input.value).code!==reviewed.code||!check.checked)throw Error('Review your code and confirm the action first.');return reviewed.code;}}; -} - -export function createCodeOfficeBranding(){ - const footer=el('footer',undefined,'code-office-provider'),brands=el('div',undefined,'code-office-provider-brands'),logo=el('img');logo.src='https://www.dunerealms.com/assets/spost-logo-v1.svg';logo.alt='SPost';logo.width=130;logo.height=43;const group=el('a');group.href='https://www.dunerealms.com/corrino-group.html';const art=el('img');art.src='https://www.dunerealms.com/assets/corrino-group-v4.png';art.alt='Corrino Group';art.width=116;art.height=42;group.append(el('span','part of'),art);brands.append(logo,group);footer.append(el('span','Code services provided by'),brands);return footer; -} +import {createDeedArtwork} from './cp-v2-deed-art.mjs'; +import {element as el} from './cp-v2-page-template.mjs'; + +// Presentation only. Recognising a format never verifies ownership or grants a right. +export function describeRedemption(value){ + const code=String(value||'').trim().toUpperCase(); + const types=[ + [/^DRK-[A-Z2-7]{32}$/,'kit','Kit delivery','Requests your kit delivery. The game confirms arrival.','Redeem kit',true], + [/^DRQ-[A-F0-9]{40}$/,'discovery','Discovery reward','Claims your earned discovery reward. The service checks eligibility before crediting.','Claim reward',true], + [/^(?:DRU|UP)-[A-F0-9]{48}$/,'token','Upgrade Token','Apply this token to a saved kit in Imperial Tailor.','Open Imperial Tailor',false,'#realm/kits-exchange'], + [/^CLAN-[A-F0-9]{48}$/,'clan','Clan founding right','Upgrades your existing Basic clan to an Original House that can become a mother house. A Royal House requires a separate political appointment.','Clan upgrades coming soon',false], + [/^COM-[A-F0-9]{48}$/,'company','Company founding right','Upgrades your existing Basic company using its separate original founding right.','Company upgrades coming soon',false], + [/^POL-[A-F0-9]{48}$/,'politics','Political appointment','Applies the specific appointment recorded by a political decision. The decision determines the organisation and title.','Political appointments coming soon',false] + ]; + for(const [pattern,kind,title,description,action,available,href] of types)if(pattern.test(code))return {code,kind,title,description,action,available,href}; + throw Error('Enter a complete private code. Community commands are used in game.'); +} + +export function createCodeRedemption(){ + let reviewed=null,locked=false; + const root=el('section',undefined,'code-redemption'),hero=el('header',undefined,'reward-code-banner'),art=el('img');art.src='https://www.dunerealms.com/assets/imperial-seal-128.png';art.alt='';const heading=el('div');heading.append(el('small','SPOST · IMPERIAL CODE OFFICE'),el('h4','Present your code. Open your next chapter.'),el('p','Your SPost counter for rewards, founding rights and political appointments.'));hero.append(art,heading); + const layout=el('div',undefined,'code-redemption-layout'),form=el('form',undefined,'code-redemption-card'),entry=el('fieldset'),legend=el('legend','1 · Enter your private code'),label=el('label','Code'),input=el('input');input.type='text';input.autocomplete='off';input.spellcheck=false;input.autocapitalize='characters';input.required=true;input.maxLength=80;input.placeholder='Paste your complete code';input.setAttribute('aria-describedby','redemption-code-help');const help=el('p','Keep your code private. Checking its format does not use it.','code-redemption-muted');help.id='redemption-code-help';label.append(input);const inspect=el('button','Review code');inspect.type='button';entry.append(legend,label,help,inspect); + const preview=el('fieldset',undefined,'code-redemption-preview');preview.hidden=true;preview.append(el('legend','2 · Review & confirm'));const badge=el('span',undefined,'reward-kind'),title=el('h5'),effect=el('p'),verification=el('p','Format recognised. Ownership and eligibility are checked when you submit.','code-redemption-muted'),check=el('input');check.type='checkbox';const consent=el('label',undefined,'code-redemption-consent');consent.append(check,el('span','I understand this action and want to use my code.'));const submit=el('button','Confirm redemption');submit.type='submit';submit.disabled=true;const destination=el('a');destination.hidden=true;preview.append(badge,title,effect,verification,consent,submit,destination);const result=el('p',undefined,'code-redemption-result');result.setAttribute('role','status');result.setAttribute('aria-live','polite');form.append(entry,preview,result); + const guide=el('aside',undefined,'code-redemption-card code-redemption-guide');guide.append(el('small','WHAT CAN YOU PRESENT?'),el('h5','Your code chooses the route.')); + for(const [kind,name,copy] of [['kit','Kits & discoveries','Existing DRK and DRQ codes can be redeemed here.'],['clan','House & company charters','Create your Basic clan first. CLAN and COM codes will unlock the later mother-house and company upgrades.'],['politics','Political appointments','POL codes come from an approved decision. Founding alone does not confer a Royal title.'],['token','Upgrade Tokens','DRU tokens are applied to a saved kit in Imperial Tailor.']]){const card=el('div',undefined,'code-redemption-guide-item');card.append(el('span',name,'reward-kind reward-kind-'+kind),el('p',copy));guide.append(card);}const register=el('a','← View your codes');register.href='#';register.onclick=e=>{e.preventDefault();root.dispatchEvent(new CustomEvent('show-code-register',{bubbles:true}));};guide.append(createDeedArtwork('keys'),register);layout.append(form,guide);root.append(hero,layout); + function sync(){submit.disabled=locked||!reviewed?.available||!check.checked;inspect.disabled=locked;input.disabled=locked;check.disabled=locked;} + function invalidate(){reviewed=null;check.checked=false;preview.hidden=true;result.textContent='';sync();} + input.oninput=invalidate;check.onchange=sync; + inspect.onclick=()=>{if(locked)return;try{reviewed=describeRedemption(input.value);check.checked=false;badge.className='reward-kind reward-kind-'+reviewed.kind;badge.textContent=reviewed.available?'Ready to submit':'Dedicated route';title.textContent=reviewed.title;effect.textContent=reviewed.description;submit.textContent=reviewed.action;submit.hidden=!reviewed.available;consent.hidden=!reviewed.available;destination.hidden=!reviewed.href;if(reviewed.href){destination.href=reviewed.href;destination.textContent=reviewed.action;}verification.textContent=reviewed.available?'Format recognised. Ownership and eligibility are checked when you submit.':reviewed.href?'Continue in the dedicated workshop to choose your kit.':'This route is being connected. Your code has not been used.';preview.hidden=false;result.textContent='';sync();}catch(error){invalidate();result.textContent=error.message;input.focus();}}; + return {root,form,input,check,submit,result,setLocked(value){locked=!!value;sync();},reset(){form.reset();invalidate();},reviewedCode(){if(!reviewed?.available||describeRedemption(input.value).code!==reviewed.code||!check.checked)throw Error('Review your code and confirm the action first.');return reviewed.code;}}; +} + +export function createCodeOfficeBranding(){ + const footer=el('footer',undefined,'code-office-provider'),brands=el('div',undefined,'code-office-provider-brands'),logo=el('img');logo.src='https://www.dunerealms.com/assets/spost-logo-v1.svg';logo.alt='SPost';logo.width=130;logo.height=43;const group=el('a');group.href='https://www.dunerealms.com/corrino-group.html';const art=el('img');art.src='https://www.dunerealms.com/assets/corrino-group-v4.png';art.alt='Corrino Group';art.width=116;art.height=42;group.append(el('span','part of'),art);brands.append(logo,group);footer.append(el('span','Code services provided by'),brands);return footer; +} diff --git a/website/control-panel/public/cp-v2/cp-v2-deed-art.mjs b/website/control-panel/public/cp-v2/cp-v2-deed-art.mjs new file mode 100644 index 00000000..094a17dc --- /dev/null +++ b/website/control-panel/public/cp-v2/cp-v2-deed-art.mjs @@ -0,0 +1,9 @@ +import {element as el} from './cp-v2-page-template.mjs'; +export function createDeedArtwork(kind='clan') { + const variants={clan:['organisation-deeds-clan-tiers-v1.png','Basic, Keyed and Royal clan deeds'],company:['organisation-deeds-company-tiers-v1.png','Basic, Keyed and Royal company deeds'],protected:['organisation-deeds-protected-v1.png','Veiled Concord and Vaerkring protected institution charters'],keys:['organisation-deed-keys-v1.png','Silver and gold sealed charter keys']}; + const [file,description]=variants[kind]||variants.clan; + const figure=el('figure',undefined,'organisation-deed-art'),image=el('img'); + image.src='https://cp.dunerealms.com/assets/'+file;image.alt=description;image.loading='lazy';image.decoding='async'; + figure.append(image,el('figcaption',description+' · Design reference; artwork does not confirm ownership or eligibility.')); + return figure; +} diff --git a/website/control-panel/public/cp-v2/cp-v2-home-block.mjs b/website/control-panel/public/cp-v2/cp-v2-home-block.mjs new file mode 100644 index 00000000..5291f8c8 --- /dev/null +++ b/website/control-panel/public/cp-v2/cp-v2-home-block.mjs @@ -0,0 +1,14 @@ +import {element as el} from './cp-v2-page-template.mjs'; +import {createUserAPI} from './cp-v2-user-api.mjs'; +import {claimMoney,claimTariffs} from './cp-v2-claim-tariffs.mjs'; +export function createHomeBlockUpgrade({fetcher=fetch}={}){ + const controller=new AbortController(),{request}=createUserAPI(fetcher,controller.signal);let active=true,busy=false,state=null,requestId=null; + const notice=el('p','Opening the Home Block provider…','claims-notice'); + const root=el('section',undefined,'claims-card home-block-upgrade'),status=el('p','Opening your Home Block…'),facts=el('dl'),review=el('button','Upgrade claims'),form=el('form'),quote=el('p'),check=el('input'),consent=el('label',' I confirm this claim upgrade in the displayed mode.'),submit=el('button','Confirm upgrade'),refresh=el('button','Refresh Home Block');status.setAttribute('role','status');review.type=refresh.type='button';submit.type='submit';check.type='checkbox';consent.prepend(check);form.hidden=true;form.append(quote,consent,submit);root.append(el('h3','Home Block · Upgrade claims'),notice,status,facts,review,form,refresh); + function lock(value){busy=value;review.disabled=value||!state?.next||!!state.next.blocked;submit.disabled=value||!check.checked;refresh.disabled=value;check.disabled=value;} + function render(){facts.replaceChildren();if(!state){review.hidden=true;return;}notice.textContent=state.simulation?'WEB SIMULATION · Fake Home Block, WorldGuard regions and test credit. Your real land, organisation bank balance and claim tier are unchanged. Simulation progress is temporary.':'Home Block claim upgrades · confirm the quoted cost before submitting.';const tier=claimTariffs(state.kind).find(t=>t.code===state.tier);for(const [label,value]of [['Paying organisation',state.name],[state.simulation?'Simulation tier':'Claim tier',state.tier],['Claim capacity',state.usedChunks+' used / '+state.capacity+' total chunks'],['Home Block',state.position.x+', '+state.position.y+', '+state.position.z],['Monthly upkeep',claimMoney(tier?.upkeepMinor||0)],...(state.simulation?[['Test organisation credit',claimMoney(state.testCreditMinor)],['Test Tax treasury',claimMoney(state.testTaxMinor)]]:[]),[state.simulation?'Fake region revision':'Region revision',String(state.revision)]])facts.append(el('dt',label),el('dd',value));review.hidden=false;status.textContent=state.next?.blocked||(!state.next?state.simulation?'Maximum tier reached in this simulation.':'Maximum claim tier reached.':'Right-click flow ready. Use Upgrade claims to review the next tier.');lock(false);} + async function load(){if(busy)return;lock(true);try{const result=await request('/api/v1/claims/home-blocks');if(!active)return;state=result.enabled?result.homeBlock:null;form.hidden=true;check.checked=false;render();if(!result.enabled)status.textContent=result.message||'Home Block unavailable.';}catch(error){if(active)status.textContent=error.message;}finally{if(active)lock(false);}} + review.onclick=()=>{if(busy||!state?.next||state.next.blocked)return;requestId=crypto.randomUUID();quote.textContent='Upgrade '+state.tier+' → '+state.next.code+': '+state.next.chunks+' total chunks, '+claimMoney(state.next.unlockMinor)+' once and '+claimMoney(state.next.upkeepMinor)+' monthly. '+(state.simulation?'The test unlock payment goes to the test Tax treasury.':'Unlock payment goes to the Tax treasury.');check.checked=false;form.hidden=false;lock(false);};check.onchange=()=>lock(busy); + form.onsubmit=async event=>{event.preventDefault();if(busy||!check.checked||!state?.next||!requestId)return;lock(true);status.textContent=state.simulation?'Applying the simulated Home Block command…':'Submitting the Home Block upgrade…';try{const result=await request('/api/v1/claims/home-blocks/'+encodeURIComponent(state.id)+'/commands',{action:'claim.tier.upgrade',confirmed:true,requestId,expectedRevision:state.revision,targetTier:state.next.code,tariffVersion:state.tariffVersion,expectedUnlockMinor:state.next.unlockMinor});if(!active)return;if(result.ok!==true||result.simulation!==state.simulation||result.status!=='applied')throw Error('The upgrade is pending or unconfirmed. Refresh before retrying.');busy=false;await load();if(active)status.textContent=result.simulation?'Simulation upgraded successfully. Fake region capacity and test payment are updated; real land and money are unchanged.':'Claim upgrade confirmed by the game/payment provider.';}catch(error){if(active)status.textContent=error.message+' Refresh before retrying; the same request reference prevents a duplicate upgrade.';}finally{if(active)lock(false);}}; + refresh.onclick=()=>void load();void load();return {root,dispose(){active=false;controller.abort();root.remove();}}; +} diff --git a/website/control-panel/public/cp-v2/cp-v2-rewards.mjs b/website/control-panel/public/cp-v2/cp-v2-rewards.mjs index 97ab55c0..71ddc1ee 100644 --- a/website/control-panel/public/cp-v2/cp-v2-rewards.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-rewards.mjs @@ -1,38 +1,40 @@ -import {createCPV2Page,element as el} from './cp-v2-page-template.mjs'; -import {createCodeRedemption,createCodeOfficeBranding} from './cp-v2-code-redemption.mjs'; -import {createUserAPI} from './cp-v2-user-api.mjs'; -import {kitReceiptStatus,groupKitReceipts} from '../kit-receipt-status.mjs'; - -export function privateKitCodes(orders){return groupKitReceipts(orders).purchases.filter(row=>kitReceiptStatus(row).canRedeem&&typeof row.code==='string'&&/^DRK-[A-Z2-7]{32}$/.test(row.code));} -export function redemptionRequest(value,confirmed){ - if(confirmed!==true)throw Error('Confirm that you want to redeem this private code.'); - const code=String(value||'').trim().toUpperCase(); - if(/^DRK-[A-Z2-7]{32}$/.test(code))return {path:'/api/kits/redeem',body:{code},kind:'kit'}; - if(/^DRQ-[A-F0-9]{40}$/.test(code))return {path:'/api/quest/rewards/claim',body:{code},kind:'discovery'}; - if(/^DRU-/.test(code))throw Error('Use Upgrade Tokens inside your saved Legendary Player Kit in Imperial Tailor.'); - throw Error('Enter a complete kit (DRK) or discovery (DRQ) code. Community commands are redeemed in game.'); -} -function table(target,head,rows){const wrap=el('div',undefined,'cp-v2-company-table-wrap'),t=el('table',undefined,'cp-v2-company-table'),thead=el('thead'),heading=el('tr'),tbody=el('tbody');for(const label of head){const th=el('th',label);th.scope='col';heading.append(th);}thead.append(heading);for(const values of rows){const tr=el('tr');for(const value of values){const td=el('td');if(typeof value==='object'&&value!==null)td.append(value);else td.textContent=String(value??'—');tr.append(td);}tbody.append(tr);}if(!rows.length){const tr=el('tr'),td=el('td','No records in this view.');td.colSpan=head.length;tr.append(td);tbody.append(tr);}t.append(thead,tbody);wrap.append(t);target.replaceChildren(wrap);} -export function mountRewards(host,{fetcher=fetch,initialTab}={}){ - let active=true,busy=false,uncertain=false,orders=[];const controller=new AbortController(),{request}=createUserAPI(fetcher,controller.signal); - const codes=el('section'),community=el('section'),tokens=el('section'),refresh=el('button','Refresh codes'),status=el('p','Opening your private rewards register…');status.setAttribute('role','status');refresh.type='button';codes.append(refresh); - const directory=el('section',undefined,'reward-code-directory'),filter=el('input'),typeFilter=el('select'),listing=el('div'),groups=new Map();filter.type='search';filter.placeholder='Search codes, rewards or references';filter.setAttribute('aria-label','Search your codes');typeFilter.setAttribute('aria-label','Filter code type');for(const [value,label] of [['all','All code types'],['kit','Kits'],['token','Upgrade Tokens'],['clan','Clan founding'],['company','Company founding'],['community','Community rewards']]){const option=el('option',label);option.value=value;typeFilter.append(option);}const controls=el('div',undefined,'reward-code-controls');controls.append(filter,typeFilter);const banner=el('header',undefined,'reward-code-banner'),crest=el('img');crest.src='https://www.dunerealms.com/assets/imperial-seal-128.png';crest.alt='';const copy=el('div');copy.append(el('small','SPOST · PRIVATE ENTITLEMENT REGISTER'),el('h4','Your codes. Your next chapter.'),el('p','Kits KIT-… · Upgrades UP-… · Clans CLAN-… · Companies COM-…'));banner.append(crest,copy);directory.append(banner,controls,listing);codes.append(status,directory); - function paintCodes(){const q=filter.value.trim().toLowerCase(),rows=[];for(const [kind,group] of groups){if(typeFilter.value!=='all'&&typeFilter.value!==kind)continue;for(const row of group.rows){if(q&&!([group.title,...row.map(v=>typeof v==='object'?v.textContent:v)].join(' ').toLowerCase().includes(q)))continue;rows.push([el('span',group.title,'reward-kind reward-kind-'+kind),...row]);}}table(listing,['Type','Reward / entitlement','Reference / amount','Status','Private code / action'],rows);} - function setCodes(kind,title,rows){groups.set(kind,{title,rows:rows.length?rows:[[title+' register','—','No records','—']]});paintCodes();} - for(const [kind,title] of [['clan','Clan founding'],['company','Company founding']]){const action=el('button','Use founding code — coming soon');action.type='button';action.disabled=true;setCodes(kind,title,[[title+' code · '+(kind==='clan'?'CLAN-…':'COM-…'),'Once per account','Not issued — preview',action]]);}for(const [kind,title] of [['kit','Kit'],['token','Upgrade Token'],['community','Community reward']])setCodes(kind,title,[[title+' register','—','Loading…','—']]);filter.oninput=typeFilter.onchange=paintCodes;const tailor=el('a','Apply Upgrade Tokens in Imperial Tailor →');tailor.href='#realm/kits-exchange';directory.append(tailor);directory.append(el('p','Founding codes are coming soon. New formats: KIT-…, UP-…, CLAN-… and COM-…. Existing DRK/DRU codes remain valid.','reward-code-note')); - const desk=createCodeRedemption(),{form,input,check,result}=desk,redemption=desk.root; - const {root,activate}=createCPV2Page({shellHost:host,title:'Codes & founding rights',description:'Your private rewards, founding rights and political appointments.',artwork:'imperial-seal-128.png',tabs:[{id:'unclaimed-codes',label:'Your codes',content:codes},{id:'redeem',label:'Redeem a code',content:redemption}]});root.append(createCodeOfficeBranding());host.replaceChildren(root);redemption.addEventListener('show-code-register',()=>activate('unclaimed-codes'));if(initialTab==='redeem')activate(initialTab); - function codeCell(code,command=false){const details=el('details');details.append(el('summary',command?'Show private command':'Show private code'),el('code',code));const copy=el('button','Copy');copy.type='button';copy.onclick=async()=>{try{await navigator.clipboard.writeText(code);if(active)copy.textContent='Copied';}catch{if(active)copy.textContent='Select and copy the code above';}};details.append(copy);return details;} - function render(){setCodes('kit','Kit',privateKitCodes(orders).map(row=>[row.name,row.orderId,kitReceiptStatus(row).label,codeCell(row.code)]));} - async function load(){if(busy)return;busy=true;refresh.disabled=true;desk.setLocked(true);status.textContent='Loading current private entitlements…'; - try{const session=await request('/api/auth/session');if(!session.authenticated)throw Error('Sign in to open your private rewards.');if(session.user?.username?.toLowerCase()==='dev')throw Error('The Dev service exemption does not receive player rewards.'); - const data=await Promise.allSettled([request('/api/kits/orders'),request('/api/community/rewards'),request('/api/kits/upgrade-tokens')]);if(!active)return; - if(data[0].status==='fulfilled'){orders=data[0].value.orders;groupKitReceipts(orders);render();uncertain=false;}else{orders=[];setCodes('kit','Kit',[['Kit register','—',data[0].reason.message,'—']]);} - community.replaceChildren();if(data[1].status==='fulfilled'){const d=data[1].value;if(!Array.isArray(d.available)||!Array.isArray(d.history))setCodes('community','Community reward',[['Community register','—','Community reward records could not be confirmed.','—']]);else{setCodes('community','Community reward',[...d.available,...d.history].map(row=>[row.month==='season-tavren-ii'?'Tavren II Aedrecht':row.month,row.reward_amount+' DM',row.delivered_at?'Delivered':row.delivery_ready===false?'Delivery not available':'Available',row.personal_code&&row.delivery_ready!==false&&/^[a-z0-9-]{8,128}$/i.test(row.personal_code)?codeCell('/communitycode '+row.personal_code,true):'—']));if(!d.linked)community.append(el('p','Link your Minecraft identity to see earned community rewards.'));}}else setCodes('community','Community reward',[['Community register','—',data[1].reason.message,'—']]); - tokens.replaceChildren();if(data[2].status==='fulfilled'&&Array.isArray(data[2].value.tokens)){setCodes('token','Upgrade Token',data[2].value.tokens.map(row=>['Upgrade Token',new Date(row.createdAt).toLocaleString(),row.usedAt?'Used':'Available',!row.usedAt&&/^DRU-[A-F0-9]{48}$/.test(row.code||'')?codeCell(row.code):'—']));const workshop=el('a','Apply tokens in Imperial Tailor →');workshop.href='#realm/kits-exchange';tokens.append(workshop);}else setCodes('token','Upgrade Token',[['Token register','—',data[2].reason?.message||'Upgrade Token records could not be confirmed.','—']]); - status.textContent=data.every(row=>row.status==='fulfilled')?'Your private reward records are loaded.':'Some reward services are unavailable. Other records remain visible.'; - }catch(error){if(active){status.textContent=error.message;groups.clear();paintCodes();orders=[];community.replaceChildren();tokens.replaceChildren();uncertain=true;}}finally{busy=false;if(active){refresh.disabled=false;desk.setLocked(uncertain);}} - } - form.onsubmit=async event=>{event.preventDefault();if(busy||uncertain)return;let payload;try{payload=redemptionRequest(desk.reviewedCode(),check.checked);}catch(error){result.textContent=error.message;return;}busy=true;refresh.disabled=true;desk.setLocked(true);result.textContent='Presenting your code…';try{const d=await request(payload.path,payload.body);if(!active)return;if(payload.kind==='discovery'&&(d.ok!==true||typeof d.credited!=='boolean'||d.amount!==1000))throw Object.assign(Error('Discovery credit was not confirmed.'),{uncertain:true});if(payload.kind==='kit'&&!['queued','delivered','pending','claimed','redeemed','pending_delivery'].includes(d.status))throw Object.assign(Error('The delivery result was not confirmed.'),{uncertain:true});desk.reset();busy=false;await load();if(active)result.textContent=payload.kind==='kit'?(d.status==='delivered'?'Delivery is already confirmed by the game.':'Delivery requested. Join a planetary server with four empty inventory slots; the game confirms arrival.'):(d.credited?'Your earned 1,000 DM reward was credited.':'This reward was already redeemed; no duplicate credit was made.');}catch(error){if(active){uncertain=!!error.uncertain;result.textContent=error.message+(uncertain?' Refresh your codes and check the result before retrying.':'');}}finally{busy=false;if(active){refresh.disabled=false;desk.setLocked(uncertain);}}}; - refresh.onclick=()=>void load();void load();return()=>{active=false;controller.abort();input.value='';orders=[];root.remove();}; -} +import {createDeedArtwork} from './cp-v2-deed-art.mjs'; +import {createCPV2Page,element as el} from './cp-v2-page-template.mjs'; +import {createCodeRedemption,createCodeOfficeBranding} from './cp-v2-code-redemption.mjs'; +import {createUserAPI} from './cp-v2-user-api.mjs'; +import {kitReceiptStatus,groupKitReceipts} from '../kit-receipt-status.mjs'; + +export function privateKitCodes(orders){return groupKitReceipts(orders).purchases.filter(row=>kitReceiptStatus(row).canRedeem&&typeof row.code==='string'&&/^DRK-[A-Z2-7]{32}$/.test(row.code));} +export function redemptionRequest(value,confirmed){ + if(confirmed!==true)throw Error('Confirm that you want to redeem this private code.'); + const code=String(value||'').trim().toUpperCase(); + if(/^DRK-[A-Z2-7]{32}$/.test(code))return {path:'/api/kits/redeem',body:{code},kind:'kit'}; + if(/^DRQ-[A-F0-9]{40}$/.test(code))return {path:'/api/quest/rewards/claim',body:{code},kind:'discovery'}; + if(/^DRU-/.test(code))throw Error('Use Upgrade Tokens inside your saved Legendary Player Kit in Imperial Tailor.'); + throw Error('Enter a complete kit (DRK) or discovery (DRQ) code. Community commands are redeemed in game.'); +} +function table(target,head,rows){const wrap=el('div',undefined,'cp-v2-company-table-wrap'),t=el('table',undefined,'cp-v2-company-table'),thead=el('thead'),heading=el('tr'),tbody=el('tbody');for(const label of head){const th=el('th',label);th.scope='col';heading.append(th);}thead.append(heading);for(const values of rows){const tr=el('tr');for(const value of values){const td=el('td');if(typeof value==='object'&&value!==null)td.append(value);else td.textContent=String(value??'—');tr.append(td);}tbody.append(tr);}if(!rows.length){const tr=el('tr'),td=el('td','No records in this view.');td.colSpan=head.length;tr.append(td);tbody.append(tr);}t.append(thead,tbody);wrap.append(t);target.replaceChildren(wrap);} +export function mountRewards(host,{fetcher=fetch,initialTab}={}){ + let active=true,busy=false,uncertain=false,orders=[];const controller=new AbortController(),{request}=createUserAPI(fetcher,controller.signal); + const codes=el('section'),community=el('section'),tokens=el('section'),refresh=el('button','Refresh codes'),status=el('p','Opening your private rewards register…');status.setAttribute('role','status');refresh.type='button';codes.append(refresh); + const directory=el('section',undefined,'reward-code-directory'),filter=el('input'),typeFilter=el('select'),listing=el('div'),groups=new Map();filter.type='search';filter.placeholder='Search codes, rewards or references';filter.setAttribute('aria-label','Search your codes');typeFilter.setAttribute('aria-label','Filter code type');for(const [value,label] of [['all','All code types'],['kit','Kits'],['token','Upgrade Tokens'],['clan','Clan founding'],['company','Company founding'],['community','Community rewards']]){const option=el('option',label);option.value=value;typeFilter.append(option);}const controls=el('div',undefined,'reward-code-controls');controls.append(filter,typeFilter);const banner=el('header',undefined,'reward-code-banner'),crest=el('img');crest.src='https://www.dunerealms.com/assets/imperial-seal-128.png';crest.alt='';const copy=el('div');copy.append(el('small','SPOST · PRIVATE ENTITLEMENT REGISTER'),el('h4','Your codes. Your next chapter.'),el('p','Kits KIT-… · Upgrades UP-… · Clans CLAN-… · Companies COM-…'));banner.append(crest,copy);directory.append(banner,controls,listing);codes.append(status,directory); + function paintCodes(){const q=filter.value.trim().toLowerCase(),rows=[];for(const [kind,group] of groups){if(typeFilter.value!=='all'&&typeFilter.value!==kind)continue;for(const row of group.rows){if(q&&!([group.title,...row.map(v=>typeof v==='object'?v.textContent:v)].join(' ').toLowerCase().includes(q)))continue;rows.push([el('span',group.title,'reward-kind reward-kind-'+kind),...row]);}}table(listing,['Type','Reward / entitlement','Reference / amount','Status','Private code / action'],rows);} + function setCodes(kind,title,rows){groups.set(kind,{title,rows:rows.length?rows:[[title+' register','—','No records','—']]});paintCodes();} + for(const [kind,title] of [['clan','Clan founding'],['company','Company founding']]){const action=el('button','Use founding code — coming soon');action.type='button';action.disabled=true;setCodes(kind,title,[[title+' code · '+(kind==='clan'?'CLAN-…':'COM-…'),'Once per account','Not issued — preview',action]]);}for(const [kind,title] of [['kit','Kit'],['token','Upgrade Token'],['community','Community reward']])setCodes(kind,title,[[title+' register','—','Loading…','—']]);filter.oninput=typeFilter.onchange=paintCodes;const tailor=el('a','Apply Upgrade Tokens in Imperial Tailor →');tailor.href='#realm/kits-exchange';directory.append(tailor);directory.append(el('p','Founding codes are coming soon. New formats: KIT-…, UP-…, CLAN-… and COM-…. Existing DRK/DRU codes remain valid.','reward-code-note')); + codes.prepend(createDeedArtwork('keys')); + const desk=createCodeRedemption(),{form,input,check,result}=desk,redemption=desk.root; + const {root,activate}=createCPV2Page({shellHost:host,title:'Codes & founding rights',description:'Your private rewards, founding rights and political appointments.',artwork:'imperial-seal-128.png',tabs:[{id:'unclaimed-codes',label:'Your codes',content:codes},{id:'redeem',label:'Redeem a code',content:redemption}]});root.append(createCodeOfficeBranding());host.replaceChildren(root);redemption.addEventListener('show-code-register',()=>activate('unclaimed-codes'));if(initialTab==='redeem')activate(initialTab); + function codeCell(code,command=false){const details=el('details');details.append(el('summary',command?'Show private command':'Show private code'),el('code',code));const copy=el('button','Copy');copy.type='button';copy.onclick=async()=>{try{await navigator.clipboard.writeText(code);if(active)copy.textContent='Copied';}catch{if(active)copy.textContent='Select and copy the code above';}};details.append(copy);return details;} + function render(){setCodes('kit','Kit',privateKitCodes(orders).map(row=>[row.name,row.orderId,kitReceiptStatus(row).label,codeCell(row.code)]));} + async function load(){if(busy)return;busy=true;refresh.disabled=true;desk.setLocked(true);status.textContent='Loading current private entitlements…'; + try{const session=await request('/api/auth/session');if(!session.authenticated)throw Error('Sign in to open your private rewards.');if(session.user?.username?.toLowerCase()==='dev')throw Error('The Dev service exemption does not receive player rewards.'); + const data=await Promise.allSettled([request('/api/kits/orders'),request('/api/community/rewards'),request('/api/kits/upgrade-tokens')]);if(!active)return; + if(data[0].status==='fulfilled'){orders=data[0].value.orders;groupKitReceipts(orders);render();uncertain=false;}else{orders=[];setCodes('kit','Kit',[['Kit register','—',data[0].reason.message,'—']]);} + community.replaceChildren();if(data[1].status==='fulfilled'){const d=data[1].value;if(!Array.isArray(d.available)||!Array.isArray(d.history))setCodes('community','Community reward',[['Community register','—','Community reward records could not be confirmed.','—']]);else{setCodes('community','Community reward',[...d.available,...d.history].map(row=>[row.month==='season-tavren-ii'?'Tavren II Aedrecht':row.month,row.reward_amount+' DM',row.delivered_at?'Delivered':row.delivery_ready===false?'Delivery not available':'Available',row.personal_code&&row.delivery_ready!==false&&/^[a-z0-9-]{8,128}$/i.test(row.personal_code)?codeCell('/communitycode '+row.personal_code,true):'—']));if(!d.linked)community.append(el('p','Link your Minecraft identity to see earned community rewards.'));}}else setCodes('community','Community reward',[['Community register','—',data[1].reason.message,'—']]); + tokens.replaceChildren();if(data[2].status==='fulfilled'&&Array.isArray(data[2].value.tokens)){setCodes('token','Upgrade Token',data[2].value.tokens.map(row=>['Upgrade Token',new Date(row.createdAt).toLocaleString(),row.usedAt?'Used':'Available',!row.usedAt&&/^DRU-[A-F0-9]{48}$/.test(row.code||'')?codeCell(row.code):'—']));const workshop=el('a','Apply tokens in Imperial Tailor →');workshop.href='#realm/kits-exchange';tokens.append(workshop);}else setCodes('token','Upgrade Token',[['Token register','—',data[2].reason?.message||'Upgrade Token records could not be confirmed.','—']]); + status.textContent=data.every(row=>row.status==='fulfilled')?'Your private reward records are loaded.':'Some reward services are unavailable. Other records remain visible.'; + }catch(error){if(active){status.textContent=error.message;groups.clear();paintCodes();orders=[];community.replaceChildren();tokens.replaceChildren();uncertain=true;}}finally{busy=false;if(active){refresh.disabled=false;desk.setLocked(uncertain);}} + } + form.onsubmit=async event=>{event.preventDefault();if(busy||uncertain)return;let payload;try{payload=redemptionRequest(desk.reviewedCode(),check.checked);}catch(error){result.textContent=error.message;return;}busy=true;refresh.disabled=true;desk.setLocked(true);result.textContent='Presenting your code…';try{const d=await request(payload.path,payload.body);if(!active)return;if(payload.kind==='discovery'&&(d.ok!==true||typeof d.credited!=='boolean'||d.amount!==1000))throw Object.assign(Error('Discovery credit was not confirmed.'),{uncertain:true});if(payload.kind==='kit'&&!['queued','delivered','pending','claimed','redeemed','pending_delivery'].includes(d.status))throw Object.assign(Error('The delivery result was not confirmed.'),{uncertain:true});desk.reset();busy=false;await load();if(active)result.textContent=payload.kind==='kit'?(d.status==='delivered'?'Delivery is already confirmed by the game.':'Delivery requested. Join a planetary server with four empty inventory slots; the game confirms arrival.'):(d.credited?'Your earned 1,000 DM reward was credited.':'This reward was already redeemed; no duplicate credit was made.');}catch(error){if(active){uncertain=!!error.uncertain;result.textContent=error.message+(uncertain?' Refresh your codes and check the result before retrying.':'');}}finally{busy=false;if(active){refresh.disabled=false;desk.setLocked(uncertain);}}}; + refresh.onclick=()=>void load();void load();return()=>{active=false;controller.abort();input.value='';orders=[];root.remove();}; +} diff --git a/website/control-panel/public/cp-v2/v2.css b/website/control-panel/public/cp-v2/v2.css index 3795c3bc..79ba2f29 100644 --- a/website/control-panel/public/cp-v2/v2.css +++ b/website/control-panel/public/cp-v2/v2.css @@ -259,3 +259,7 @@ .claim-preview-scroll{overflow:auto;max-width:100%;margin:18px 0;border:1px solid #9f874f;border-radius:10px}.claim-preview-table{width:100%;border-collapse:collapse;text-align:left;min-width:570px}.claim-preview-table th,.claim-preview-table td{padding:12px;border-bottom:1px solid #45634b}.claim-preview-table thead{background:#284c3a;color:#efd28b}.claims-workspace>.claims-card{margin:24px 0}.claims-card>small{display:block;margin-top:14px;color:#bfd0c2}.claims-card select{display:block;max-width:100%;padding:12px;margin-top:10px} .claims-workspace>.claims-card{padding:24px;background:linear-gradient(135deg,#193c31,#122c27);border:1px solid #9f874f;border-radius:14px}.claims-workspace .claims-card h3{color:#efd28b}.claims-workspace>.claims-card>p{line-height:1.7}.claims-workspace>.claims-card>a{color:#efd28b}@media(max-width:500px){.claims-workspace>.claims-card{padding:16px}} + +.home-block-upgrade dl{display:grid;grid-template-columns:minmax(130px,1fr) minmax(0,2fr);gap:8px 20px}.home-block-upgrade dt{font-weight:bold;color:#e7cd8e}.home-block-upgrade dd{margin:0;overflow-wrap:anywhere}.home-block-upgrade button{padding:12px 18px;border:1px solid #c8aa63;border-radius:8px;background:#aa8c45;color:#10271f;font-weight:bold;margin:10px 10px 0 0}.home-block-upgrade button:disabled{opacity:.5;cursor:not-allowed}.home-block-upgrade form{margin:22px 0;padding:18px;border:1px solid #927f4d;border-radius:10px;background:#0c271e}.home-block-upgrade form label{display:flex;align-items:flex-start;gap:10px}.home-block-upgrade [hidden]{display:none!important}@media(max-width:500px){.home-block-upgrade dl{grid-template-columns:1fr}.home-block-upgrade dd{margin-bottom:10px}.home-block-upgrade button{width:100%;margin-right:0}} + +.organisation-deed-art{margin:1rem 0;padding:1rem;border:1px solid #8e7945;border-radius:14px;background:linear-gradient(135deg,#142f2d,#122326);text-align:center;min-width:0}.organisation-deed-art img{display:block;width:100%;max-width:850px;height:auto;max-height:310px;object-fit:contain;margin:auto}.organisation-deed-art figcaption{margin-top:.75rem;font-size:.85rem;color:#d6cbab;line-height:1.5} diff --git a/website/control-panel/server.mjs b/website/control-panel/server.mjs index 1b4fac2d..5ad94764 100644 --- a/website/control-panel/server.mjs +++ b/website/control-panel/server.mjs @@ -1,322 +1,325 @@ -export const PANEL_CSP="default-src 'self'; script-src 'self'; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; connect-src 'self' https://usercontent.luckperms.net https://metadata.luckperms.net wss://usersockets.luckperms.net; img-src 'self' data:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self' https://www.dunerealms.com https://dunerealms.com https://clans.dunerealms.com https://corp.dunerealms.com https://corp.dunerealms.com"; -// Company artwork is served by the canonical public asset host. -export const COMPANY_CSP=PANEL_CSP.replace("img-src 'self' data:","img-src 'self' data: https://www.dunerealms.com"); -import {createElectionDirectory} from './election-directory.mjs'; -import {createMenuBadges} from '../node/menu-badges.mjs'; -import {startCentralScheduler} from '../node/postbank-payments.mjs'; -import {createPostbankApi} from '../node/postbank-api.mjs'; -import {openPostbankDatabase} from '../node/postbank-db.mjs'; -import {createItemRegister} from './item-register.mjs'; -import {createManagedTransfers} from './managed-bank-transfer.mjs'; -import {createOfficialBank} from './official-bank.mjs'; -import {createBankBeneficiaries} from './bank-beneficiaries.mjs'; -import {createBankTransfers} from './bank-transfers.mjs'; -import {createHosting} from '../node/hosting.mjs'; -import {initializeOfficeLedger,startOfficeLedger} from './election-office-ledger.mjs'; -import {createMailAccounts} from '../node/mail-accounts.mjs'; -import {createElectionVoting,startElectionClock} from './election-voting.mjs'; -import {initializeBallots} from './election-ballots.mjs'; -import {initializeRounds} from './election-rounds.mjs'; -import {createImperialCharters,initializeCharters} from './imperial-charters.mjs'; -import {createProclamations,initializeProclamations} from './proclamations.mjs'; -import {createElectoralRoll} from '../node/electoral-roll.mjs'; -import {createElectionApplications} from './election-application-route.mjs'; -import {initializeApplications} from './election-applications.mjs'; -import {createInternalMail,startInternalMailSync,initializeInternalMailAccess,syncClanMailRegistry} from '../node/internal-mail.mjs'; -import {createPoliticsPreview} from './politics-preview.mjs'; -import {createPublicGovernment} from '../node/public-government.mjs'; -import{createAdminRegistration}from '../node/admin-registration.mjs'; -import{firstLoginGate,firstLoginState,initializeFirstLogin,createFirstLoginTerms}from '../node/first-login.mjs'; -import {createContactEmail,initializeContactEmails} from '../node/contact-email.mjs'; -import {isOwnerRank} from '../node/permissions.mjs'; -import {createBanEvidence,initializeBanEvidence} from './ban-evidence.mjs'; -import {createUpgradeTokens} from './upgrade-tokens.mjs'; -import {createKitCatalogueBridge} from '../node/kit-catalogue.mjs'; -import {createKitStudio} from './kit-studio.mjs'; -import {startModerationSync} from './moderation.mjs'; -import {createKitMarket} from './kit-market.mjs'; -import {createImperialAtelier} from './imperial-atelier.mjs'; -import {createGameRanks,initializeGameRanks} from '../node/game-ranks.mjs'; -import {createBanking} from './banking.mjs'; -import {createClanShop,initializeClanShop} from './clan-shop.mjs'; -import {createQuests} from './quests.mjs'; -import {createClans,initializeClans} from './clans.mjs'; -import {createClanEmblems} from './clan-emblems.mjs'; -import {createGameTickets} from './game-tickets.mjs'; -import {createQuestRewards} from './quest-rewards.mjs'; -import {openGameMysqlPool} from '../node/game-mysql-pool.mjs'; -import {retiredTicketResponse} from '../node/retired-tickets.mjs'; -import {createGitIdentityRoute,initializeGitIdentities,startGitIdentitySync,gitProxyIdentity} from '../node/git-identity.mjs'; -import {createMailIdentityRoute,initializeMailIdentities} from '../node/mail-identity.mjs'; -import {createProfile} from '../node/profile.mjs'; -import {createWorldStatus} from '../node/world-status.mjs'; -import {createMemorials} from '../node/memorials.mjs'; -import {createMemberProfiles} from '../node/member-profiles.mjs'; -import {createAvatars} from '../node/avatar.mjs'; -import {createTailorAppearance} from '../node/tailor-appearance.mjs'; -import {createBadgeAdmin} from '../node/badge-admin.mjs'; -import {createManualSealRoute} from '../node/manual-seal-route.mjs'; -import {createCompanyAdmin} from '../node/company-admin.mjs'; -import {initializeCompanyRegistry} from '../node/company-registry.mjs'; -import {initializeShareLedger} from '../node/share-ledger.mjs'; -import {initializeSealEntitlements} from '../node/seal-entitlement-store.mjs'; -import {initializeSealCatalog,createSealCatalogAdmin} from '../node/seal-catalog-admin.mjs'; -import {initializeBadges} from '../node/community-badges.mjs'; -import {createBanRegister} from './ban-register.mjs'; -import {createRankAdmin} from '../node/rank-admin.mjs'; -import {createOverview} from './overview.mjs'; -import {createStaffManual} from './staff-manual.mjs'; -import {createLuckPerms} from './luckperms.mjs'; -import {createCommunityAdmin} from './community-admin.mjs'; -import {createExchange} from './exchange.mjs'; -import {createIntegrationSSO} from '../node/integration-sso.mjs'; -import {createBanBridge} from './ban-bridge.mjs'; -import {sharedErrorResponse} from '../node/shared-errors.mjs'; -import {initializeNews} from '../node/news.mjs'; -import {initializeStaffBureau} from '../node/staff-bureau-schema.mjs'; -import {createStaffBureauReadApi} from '../node/staff-bureau-read-api.mjs'; -import {initializeOrganisation} from '../node/organisation-model.mjs'; -import {createLifeStatus,initializeLifeStatus} from '../node/life-status.mjs'; -import {createCitizenDirectory} from '../node/citizen-directory.mjs'; -import {createOrganisationManagement} from '../node/organisation-management.mjs'; -import {initializeRanks,initializeCommunityAccess,initializeQuestAccess,initializeBankAccess,can,accessFor} from '../node/permissions.mjs'; -import {createServer} from 'node:http'; -import {companyCPDocument} from './company-cp-shell.mjs'; -import {createCompanyWorkspace} from '../node/company-workspace.mjs'; -import {clanCPDocument} from './clan-cp-shell.mjs'; -import {politicsCPDocument} from './politics-cp-shell.mjs'; -import {createV1PersonalBank} from './api-v1-personal-bank.mjs'; -import {readFile} from 'node:fs/promises'; -import {pathToFileURL} from 'node:url'; -import {accountSchema} from './imperial-accounts.mjs'; -import {openDatabase} from '../node/mysql.mjs'; -import {createAuth} from '../node/auth.mjs'; -import {identity} from '../node/auth.mjs'; -import {createHonourRoute} from '../node/honour-route.mjs'; -import {panelBodyLimit} from './request-limits.mjs'; -import {initializeHonours} from '../node/honours.mjs'; -import {createBankClientApi} from '../node/bank-clients.mjs'; -import {createInventoryHandler,createSalesHistoryHandler} from './inventory/inventory-api.mjs'; -import {createMarketBridge} from './inventory/market-bridge.mjs'; -import {createGameLink,json} from '../node/game-link.mjs'; -import {createCommunityRewards} from '../node/community-rewards.mjs'; -import {createAccountAdmin} from '../node/account-admin.mjs'; -import {createServerControl} from './server-control.mjs'; -const types={'.html':'text/html; charset=utf-8','.js':'text/javascript; charset=utf-8','.mjs':'text/javascript; charset=utf-8','.css':'text/css; charset=utf-8'}; -const sharedAssets=new Set(['spost-logo-v1.svg','postbank-transfer-hall-v1.png','corrino-group-v4.png','corrino-group-v3.svg','corrino-charter-v2.png','corrino-founding-marks-v1.png','consortium-corrini-v1.png','corrino-charter-v1.png','corrino-founder-v1.png','imperial-postbank-v2.png','spost-company-v1.png','vaerkring-company-v1.png','imperial-postbank-v1.png','corrino-group-logo.svg','spicepost-logo-v2.svg','spicepost-logo.svg','imperial-post-seal-v2.png','imperial-post-seal.svg','imperial-post-office-v1.png','mail-stamp-imperial.svg','mail-stamp-faction.svg','mail-stamp-staff.svg','mail-stamp-clan.svg','mail-stamp-personal.svg','imperial-post-logo.svg','ornament.webp','guild.webp','minecraft-hero.webp','menu-0.webp','reward-gold-ingot-transparent-v1.png','menu-5.webp','menu-6.webp','menu-9.webp','menu-12.webp','item-23.webp','dunemark-icon-64.png','arrakis-lore-frieze.svg']); -export function createPanel(db,settings={},dependencies={}){ - const itemRegister=createItemRegister(db); - const worldStatus=dependencies.worldStatus||createWorldStatus(settings); - const origin=new URL(settings.CP_ORIGIN||'https://cp.dunerealms.com').origin; - const contactEmail=createContactEmail(db,{origin,...dependencies.contactEmail}); - const internalMail=createInternalMail(db,{origin,settings,...dependencies.internalMail}); - const terms=createFirstLoginTerms(db,origin); - const auth=createAuth(db,origin,{...settings,trackFirstLogin:true}),links=createGameLink(db,settings,origin),rewards=createCommunityRewards(db,settings,origin); - const hosting=createHosting(db,{origin});const mailAccounts=createMailAccounts(db);const mailIdentity=createMailIdentityRoute(db,{origin}),gitIdentity=createGitIdentityRoute(db,settings,origin); - const adminRegistration=createAdminRegistration(db,origin);const admin=createAccountAdmin(db,origin),profile=createProfile(db,settings,origin),avatars=createAvatars(db,settings); - 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 companyWorkspace=createCompanyWorkspace(db); - const manual=createStaffManual(db); - const staffBureauRead=createStaffBureauReadApi(db); - const citizenDirectory=createCitizenDirectory(db);const lifeStatus=createLifeStatus(db,{origin}); - const organisationManagement=createOrganisationManagement(db,{origin}); - const luckperms=createLuckPerms(db,settings,dependencies.luckperms); - const servers=createServerControl(db,settings,dependencies.serverControl); - const pool=dependencies.inventoryPool||{async query(){throw Error('Inventory database is not configured');}}; - const community=createCommunityAdmin(db,settings,{pool}); - const exchange=createExchange(db,pool); - const clans=createClans(db,{origin,onClanCreated:()=>syncClanMailRegistry(db),onClanDeleted:()=>syncClanMailRegistry(db)}),gameTickets=createGameTickets(db,settings); - const clanEmblems=createClanEmblems(db,{origin}); - const questRewards=createQuestRewards(db,settings,pool); - const gameRanks=createGameRanks(db,settings); - const kitStudio=createKitStudio(db,settings,dependencies.kitStudio); - const upgradeTokens=createUpgradeTokens(db,settings,dependencies.upgradeTokens); - const publicKitCatalogue=createKitCatalogueBridge(settings,{db}); - const kitMarket=createKitMarket(db,settings,dependencies.kitMarket); - const imperialAtelier=createImperialAtelier(db,settings,dependencies.imperialAtelier); - const bankBeneficiaries=createBankBeneficiaries(db,dependencies.bankBeneficiaries); - const officialBank=createOfficialBank(db,settings,dependencies.officialBank); - const managedTransfers=createManagedTransfers(db,settings,dependencies.managedTransfers); - const bankTransfers=createBankTransfers(db,settings,dependencies.bankTransfers); - const banking=createBanking(db,settings,dependencies.banking); - const postbank=createPostbankApi(db,dependencies.bankDatabase||null,settings,dependencies.postbank); - const bankClient=createBankClientApi(db,dependencies.bankClient); - const v1PersonalBank=createV1PersonalBank(banking,{enabled:process.env.DUNE_API_V1_BANK_STAGING==='true'}); - const quests=createQuests(db,settings,dependencies.quests),clanShop=createClanShop(db,settings,dependencies.clanShop); - const sso=createIntegrationSSO(db,settings); - const overview=createOverview(db);const menuBadges=createMenuBadges(db,settings); - const banBridge=createBanBridge(db,settings,dependencies.bans); - const banRegister=createBanRegister(db,settings,dependencies.bans); - const electionDirectory=createElectionDirectory(db,dependencies.electionDirectory); - const electionVoting=createElectionVoting(db,settings,dependencies.electionVoting); - const imperialCharters=createImperialCharters(db,settings); - const proclamations=createProclamations(db,settings); - const electoralRoll=createElectoralRoll(db); - const electionApplications=createElectionApplications(db,settings,dependencies.electionApplications); - const politicsPreview=createPoliticsPreview(db,settings,dependencies.politicsPreview); - const publicGovernment=createPublicGovernment(db); - const banEvidence=createBanEvidence(db,settings,dependencies.banEvidence); - const inventoryOptions={authenticate:request=>identity(request,db),verifiedMinecraftUuid:async accountId=>(await db.prepare('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?').bind(accountId).first())?.minecraft_uuid||null,pool,logger:dependencies.logger||console}; - const inventory=createInventoryHandler(inventoryOptions),sales=createSalesHistoryHandler(inventoryOptions); - const market=(settings.EXCHANGE_READ_TOKEN||'').length>=32?createMarketBridge({pool,readToken:settings.EXCHANGE_READ_TOKEN}):null; - return async request=>{const retiredTickets=retiredTicketResponse(request);if(retiredTickets)return retiredTickets; - const path=new URL(request.url).pathname; - if(path==='/api/public/government')return publicGovernment(request); - if(['/api/menu-badges','/api/staff/menu-badges'].includes(path))return menuBadges(request); - if(['/v2/cp-v2-menu-badges.mjs','/v2/cp-v2-dunemark-collection.mjs','/v2/dunemark-catalogue.mjs'].includes(path))return new Response(await readFile(new URL('./public/cp-v2/'+path.slice(4),import.meta.url)),{headers:{'Content-Type':'text/javascript; charset=utf-8','Cache-Control':'no-store'}}); - if(path==='/api/items/catalogue')return itemRegister(request); - if(path==='/api/worlds')return request.method==='GET'?worldStatus():new Response('Method not allowed',{status:405}); - const onboarding=await firstLoginGate(request,db);if(onboarding)return onboarding; - if(settings.POSTBANK_ENABLED==='true'&&path.startsWith('/api/bank/'))return postbank(request); - if(settings.POSTBANK_ENABLED==='true'&&path==='/api/v1/me/bank')return json({message:'The game-linked bank has been retired from this website.'},410); - if(path==='/api/politics/directory')return electionDirectory(request); - if(['/api/politics/ballot/house','/api/politics/ballot/imperial','/api/politics/ballot/bene','/api/politics/ballot/guild','/api/politics/ballot/clan_delegate'].includes(path))return electionVoting(request); - if(path==='/api/politics/charters')return imperialCharters(request); - if(path==='/api/politics/proclamations')return proclamations(request); - if(path==='/api/politics/electoral-roll')return electoralRoll(request); - if(path==='/api/politics/applications')return electionApplications(request); - if(path==='/api/politics/preview')return politicsPreview(request); - if(path==='/api/admin/register-user')return adminRegistration(request); - if(path==='/api/admin/life-status')return lifeStatus(request); - if(path==='/api/admin/citizens'||path.startsWith('/api/admin/citizens/'))return citizenDirectory(request); - if(path.startsWith('/api/admin/organisation/'))return organisationManagement(request); - if(path==='/api/account/email')return contactEmail(request); - if(path.startsWith('/api/people/'))return memberProfiles(request); - if(path==='/profile-login'&&request.method==='GET'){ - const username=new URL(request.url).searchParams.get('username');if(!/^[a-z0-9_]{3,32}$/.test(username||'')||!await db.prepare("SELECT id FROM site_accounts WHERE username=? AND password_hash NOT LIKE '!%'").bind(username).first())return new Response('Profile not found',{status:404}); - return Response.redirect(await identity(request,db)?'https://www.dunerealms.com/people/'+username:origin+'/?return_to='+encodeURIComponent('/profile-login?username='+username),302); - } - if(path==='/memorial-login'&&request.method==='GET'){ - const slug=new URL(request.url).searchParams.get('slug');if(!/^[a-z0-9-]{3,64}$/.test(slug||'')||!await db.prepare('SELECT slug FROM site_memorials WHERE slug=?').bind(slug).first())return new Response('Memorial not found',{status:404}); - return Response.redirect(await identity(request,db)?'https://www.dunerealms.com/memorial/'+slug:origin+'/?return_to='+encodeURIComponent('/memorial-login?slug='+slug),302); - } - if(path.startsWith('/api/memorials/')){ - const from=request.headers.get('origin'),allowed='https://www.dunerealms.com';if(from&&from!==allowed)return new Response(null,{status:403}); - const headers={'Access-Control-Allow-Origin':allowed,'Access-Control-Allow-Credentials':'true','Access-Control-Allow-Methods':'GET, POST, OPTIONS','Access-Control-Allow-Headers':'Content-Type','Vary':'Origin','Cache-Control':'no-store'}; - if(request.method==='OPTIONS')return new Response(null,{status:204,headers}); - const result=await memorials(request),out=new Headers(result.headers);for(const[k,v]of Object.entries(headers))out.set(k,v);return new Response(result.body,{status:result.status,headers:out}); - } - if(path==='/api/game/tickets')return gameTickets(request); - if(['/api/game/quest/discover','/api/quest/rewards','/api/quest/rewards/claim'].includes(path))return questRewards(request); - if(path==='/api/imperial-atelier')return imperialAtelier(request); - if(path==='/internal/kits/catalogue')return publicKitCatalogue(request); - if(['/api/kits/studio','/api/kits/server-studio'].includes(path))return kitStudio(request); - if(path==='/api/kits/upgrade-tokens')return upgradeTokens(request); - if(path.startsWith('/api/kits/'))return kitMarket(request); - if(path==='/api/ranks/game')return gameRanks(request); - if(path==='/api/bank/beneficiaries')return bankBeneficiaries(request); - if(path==='/api/bank/official')return officialBank(request); - if(path==='/api/bank/managed-transfer')return managedTransfers(request); - if(path==='/api/bank/transfer-own'||path==='/api/bank/remittance')return bankTransfers(request); - if(path==='/api/bank/client')return bankClient(request); - if(path==='/api/bank/personal'||path==='/api/bank/staff'||path==='/api/bank/faction')return banking(request); - if(path==='/api/v1/me/bank')return v1PersonalBank(request); - 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==='/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); - if(path.startsWith('/api/internal-mail/'))return internalMail(request); - if(path==='/api/git/me')return gitIdentity(request); - if(['/api/mail/me','/api/mail/password','/api/mail/signature','/api/mail/template'].includes(path))return mailIdentity(request); - if(['/api/account/profile','/api/account/avatar','/api/account/avatar/remove'].includes(path))return profile(request); - if(path.startsWith('/api/avatars/'))return avatars(request); - if(path==='/api/tailor/appearance'||path==='/api/tailor/skin')return tailorAppearance(request); - if(path==='/api/badges')return badges(request); - if(path==='/api/seals/manual')return manualSeals(request); - if(path==='/api/seals/catalog'||path.startsWith('/api/seals/artwork/'))return sealCatalog(request); - if(path==='/api/companies/workspace')return companyWorkspace(request); - if(path==='/api/companies/manage')return companyAdmin(request); - if(path.startsWith('/api/v1/staff/'))return staffBureauRead(request); - if(path==='/api/ban-register')return banRegister(request); - if(path==='/api/ban-evidence'||path==='/api/ban-evidence/file')return banEvidence(request); - if(path==='/api/public/bans'&&request.method==='GET')return banBridge.publicBans(); - if(path==='/api/overview'||path==='/api/overview/staff')return overview(request); - const sharedError=await sharedErrorResponse(request);if(sharedError)return sharedError; - if(path==='/internal/integrations/ban')return banBridge.handle(request); - if(path==='/sso/authorize'||path.startsWith('/internal/integrations/'))return sso(request); - if(path==='/api/exchange/listings')return exchange(request); - if(path.startsWith('/api/cp/'))return community(request); - if(path.startsWith('/luckperms-editor/')){ - const user=await identity(request,db);if(!user)return json({message:'Sign in first.'},401); - if(!isOwnerRank((await accessFor(db,user)).rank)||!await can(db,user,'web.menu.luckperms')||!await can(db,user,'web.luckperms.edit'))return json({message:'LuckPerms editor access is restricted to Owners with web.luckperms.edit.'},403); - if(!['GET','HEAD'].includes(request.method))return json({message:'Method not allowed'},405); - let file=path.slice('/luckperms-editor/'.length); - if(!file||/^editor(?:\/[A-Za-z0-9_-]{3,200})?\/?$/.test(file))file='index.html'; - if(!/^[A-Za-z0-9_./-]+$/.test(file)||file.includes('..'))return json({message:'Not found'},404); - const extension=file.slice(file.lastIndexOf('.')),mime={...types,'.svg':'image/svg+xml','.png':'image/png','.ico':'image/x-icon','.woff':'font/woff','.woff2':'font/woff2','.ttf':'font/ttf','.txt':'text/plain; charset=utf-8'}[extension]; - if(!mime)return json({message:'Not found'},404); - try{return new Response(request.method==='HEAD'?null:await readFile(new URL('./native-editor/'+file,import.meta.url)),{headers:{'Content-Type':mime,'Cache-Control':'private, no-store','Content-Security-Policy':PANEL_CSP}});}catch{return json({message:'Native LuckPerms editor build is unavailable.'},404);} - } - if(path.startsWith('/api/luckperms/'))return luckperms(request); - if(path==='/api/staff/manual')return manual(request); - if(path==='/api/ranks/honour')return honours(request); - if(path==='/api/game/permissions'||path==='/api/ranks'||path.startsWith('/api/ranks/'))return ranks(request); - const menu=path==='/api/inventory'||path==='/api/exchange/sales-history'?'web.menu.inventory':(path==='/api/game-link'||path.startsWith('/api/game-link/')&&path!=='/api/game-link/consume')?'web.menu.game':path==='/api/community/rewards'?'web.menu.rewards':null; - if(menu){const user=await identity(request,db);if(!user)return json({message:'Sign in first.'},401);if(!await can(db,user,menu))return json({message:'Permission required: '+menu},403);} - if(path==='/api/servers'||path.startsWith('/api/servers/'))return servers(request); - if(path==='/api/inventory')return inventory(request); - if(path==='/api/exchange/sales-history')return sales(request); - if(path==='/internal/exchange/listings')return market?market(request):new Response('Not configured',{status:503,headers:{'Cache-Control':'no-store'}}); - if(path.startsWith('/api/admin/'))return admin(request); - if(path==='/healthz'){await db.prepare('SELECT 1 AS ok').first();return json({status:'ok'});} - if(path==='/api/welcome'&&request.method==='GET'){const allowed=new Set(['https://corp.dunerealms.com','https://www.dunerealms.com','https://dunerealms.com','https://forums.dunerealms.com','https://support.dunerealms.com','https://clans.dunerealms.com','https://wiki.dunerealms.com','https://cp.dunerealms.com']);const origin=request.headers.get('origin');if(origin&&!allowed.has(origin))return new Response(null,{status:403});const user=await identity(request,db);return new Response(JSON.stringify({username:user?.username||null}),{headers:{'Content-Type':'application/json','Cache-Control':'no-store','Vary':'Origin',...(origin?{'Access-Control-Allow-Origin':origin,'Access-Control-Allow-Credentials':'true'}:{})}});} - if(path==='/api/auth/terms')return terms(request); - if(path==='/api/auth/session'&&request.method==='GET'){const response=await auth(request),data=await response.json();if(data.user)data.user.firstLogin=await firstLoginState(db,await identity(request,db));return json(data);} - if(path.startsWith('/api/auth/'))return auth(request); - if(path==='/api/game-link'||path.startsWith('/api/game-link/'))return links(request); - if(path.startsWith('/api/community/'))return rewards(request); - if(!['GET','HEAD'].includes(request.method))return new Response('Method not allowed',{status:405}); - if(/^\/kit-textures\/(?:entity\/(?:banner\/[a-z_]+|equipment\/(?:humanoid|humanoid_leggings)\/netherite)|trims\/(?:color_palettes\/[a-z_]+|entity\/(?:humanoid|humanoid_leggings)\/[a-z_]+))\.png$/.test(path)){ - try{return new Response(request.method==='HEAD'?null:await readFile(new URL('../web/assets/'+path.slice(1),import.meta.url)),{headers:{'Content-Type':'image/png','Cache-Control':'public, max-age=86400'}});}catch{return new Response('Texture not found',{status:404});} - } - if(path.startsWith('/assets/')&&sharedAssets.has(path.slice(8))){const file=path.slice(8);return new Response(request.method==='HEAD'?null:await readFile(new URL('../web/assets/'+file,import.meta.url)),{headers:{'Content-Type':file.endsWith('.svg')?'image/svg+xml':file.endsWith('.png')?'image/png':'image/webp','Cache-Control':'public, max-age=3600'}});} - if(path==='/federal-reserve'||path==='/federal-reserve/')return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/reserve-ledger.html',import.meta.url)),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}}); - // V2 shell is public; private data and writes retain their authenticated API gates. - if(path==='/company-cp')return new Response(request.method==='HEAD'?null:companyCPDocument(await readFile(new URL('./public/cp-v2/index.html',import.meta.url),'utf8')),{headers:{'Content-Security-Policy':COMPANY_CSP,'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}}); - if(path==='/clan-cp')return new Response(request.method==='HEAD'?null:clanCPDocument(await readFile(new URL('./public/cp-v2/index.html',import.meta.url),'utf8')),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}}); - if(path==='/politics-cp')return new Response(request.method==='HEAD'?null:politicsCPDocument(await readFile(new URL('./public/cp-v2/index.html',import.meta.url),'utf8')),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}}); - // All authored cp-v2 browser modules share this bounded public directory. - // New components must not require a second, manually maintained route list. - if(/^\/(?:v2|cp-v2)\/cp-v2-[a-z0-9-]+\.(?:mjs|css)$/.test(path)){ - try{const bytes=await readFile(new URL('./public/cp-v2/'+path.slice(path.lastIndexOf('/')+1),import.meta.url));return new Response(request.method==='HEAD'?null:bytes,{headers:{'Content-Type':path.endsWith('.css')?'text/css; charset=utf-8':'text/javascript; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}});}catch(error){if(error.code==='ENOENT')return new Response('Not found',{status:404});throw error;} - } - if(['/v2/citizen-directory.mjs','/v2/citizen-directory.css','/v2/organisation-permissions.mjs'].includes(path))return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/'+path.slice('/v2/'.length),import.meta.url)),{headers:{'Content-Type':path.endsWith('.css')?'text/css; charset=utf-8':'text/javascript; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}}); - if(['/','/index.html','/v2','/v2/','/v2/cp-v2-politics-pages.mjs','/v2/cp-v2-auth.mjs','/v2/cp-v2-access.mjs','/v2/citizens-registry.mjs','/v2/cp-v2-page-template.mjs','/v2/imperial-permissions.mjs','/v2/honours-seals.mjs','/v2/cp-v2-planned-pages.mjs','/v2/cp-v2-choam-pages.mjs','/v2/cp-v2-bureau-pages.mjs','/v2/cp-v2-service-pages.mjs','/v2/cp-v2-newsroom.mjs','/v2/cp-v2-moderation.mjs','/v2/cp-v2-native-services.mjs','/v2/cp-v2-exchange-authority.mjs','/v2/cp-v2-crysknife.mjs','/v2/cp-v2-post-menu.mjs','/v2/cp-v2-postbank-foundation.mjs','/v2/cp-v2-postbank-payments.mjs','/v2/cp-v2-postbank-admin.mjs','/v2/cp-v2-authorisations.mjs','/v2/cp-v2-tax-treasury.mjs','/v2/cp-v2-reserve-ledger.mjs','/v2/cp-v2-reserve-entry.mjs','/v2/cp-v2-postbank-credit.mjs','/v2/cp-v2-postbank-beneficiaries.mjs','/v2/cp-v2-postbank-statement-archive.mjs','/v2/cp-v2-bank-pages.mjs','/v2/cp-v2-post-pages.mjs','/v2/cp-v2-code-redemption.mjs','/v2/cp-v2-rewards.mjs','/v2/cp-v2-user-commerce.mjs','/v2/cp-v2-user-pages.mjs','/v2/cp-v2-user-api.mjs','/v2/cp-v2-security.mjs','/v2/cp-v2-passport.mjs','/v2/cp-v2-personal-records.mjs','/v2/cp-v2-design-pages.mjs','/v2/cp-v2-design-catalog.mjs','/v2/cp-v2-forge-pages.mjs','/v2/cp-v2-hosting.mjs','/v2/cp-v2-community-treasury.mjs','/v2/cp-v2-item-register.mjs','/v2/cp-v2-kit-directorate.mjs','/v2/cp-v2-campaigns.mjs','/v2/cp-v2-imperial-revenue.mjs','/v2/cp-v2-read-register.mjs','/v2/cp-v2-bureau-data.mjs','/v2/cp-v2-company-actions.mjs','/v2/v2.css','/v2/v2.js'].includes(path)){ - const moduleFile=path.endsWith('.mjs')||path.endsWith('.js'); - const file=path.endsWith('.mjs')?path.slice('/v2/'.length):path.endsWith('.js')?'v2.js':path.endsWith('.css')?'v2.css':'index.html'; - return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/'+file,import.meta.url)),{headers:{'Content-Type':moduleFile?'text/javascript; charset=utf-8':file.endsWith('.css')?'text/css; charset=utf-8':'text/html; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}}); - } - const file=path==='/'?'index.html':path==='/servers'?'servers.html':path.slice(1); - if(!['user-service.html','user-service-entry.mjs','user-service.css','kit-receipt-status.mjs','clan-center.html','clan-center-entry.mjs','clan-center.css','bank-transfer-view.mjs','bank-dashboard.mjs','mail-service-ui.mjs','mail-workspace.css','hosting-control.mjs','internal-mail.mjs','internal-mail.css','election-voting-view.mjs','imperial-charters-view.mjs','proclamations-view.mjs','electoral-roll-view.mjs','election-applications-view.mjs','election-rules.mjs','political-catalog.mjs','menu-ribbons.mjs','council-preview.mjs','politics.mjs','crysknife.mjs','x-news-draft.mjs','terms.html','admin-registration.mjs','mail-signature.mjs','webmail.mjs','git-control.mjs','git-control.css','site-profile.mjs','site-profile.css','servers.html','servers.js','servers.css','pages.mjs','user-page-hero.mjs','commerce-settings.mjs','shop-management.mjs','center-portals.mjs','panel-layout.mjs','embed-size.mjs','dev-request-access.mjs','center-portals.css','overview.mjs','overview.css','page-groups.mjs','ban-register.mjs','moderation-form-response.mjs','ban-record-cards.css','ban-evidence.mjs','ban-evidence.css','ranks.mjs','ranks.css','staff-manual.mjs','luckperms.mjs','community-admin.mjs','native-community.mjs','exchange.mjs','exchange.css','clans.mjs','clan-shop.mjs','house-tailor.mjs','banking.mjs','banking.css','game-ranks.mjs','upgrade-shop.mjs','kit-generator.mjs','kit-design-model.mjs','kit-equipment-editor.mjs','kit-texture-preview.mjs','kit-generator.css','kit-market.mjs','kit-market.css','kit-cart.mjs','imperial-atelier.mjs','quests.mjs','quests.css','clans.css','clan-request-gate.mjs','clan-directory-model.mjs','clan-profile-panels.mjs','organisation-settings.mjs','organisation-settings.css','organisation-dashboard.mjs','organisation-dashboard.css','organisation-activity.mjs','clan-dashboard-data.mjs','quest-rewards.mjs','quest-rewards.css','inventory/inventory-view.mjs','inventory/inventory-mount.mjs','inventory/inventory.css'].includes(file))return new Response('Not found',{status:404}); - return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/'+file,import.meta.url)),{headers:{'Content-Type':types[file.slice(file.lastIndexOf('.'))],'Cache-Control':'no-store'}}); - }; -} -export async function startPanel(settings=process.env){ - let inventoryPool=null; - if(settings.DUNE_INVENTORY_DATABASE_URL){ - if(settings.DUNE_INVENTORY_DATABASE_URL.startsWith('mysql:'))inventoryPool=await openGameMysqlPool(settings.DUNE_INVENTORY_DATABASE_URL); - else{const {Pool}=await import('pg');inventoryPool=new Pool({connectionString:settings.DUNE_INVENTORY_DATABASE_URL,max:3,connectionTimeoutMillis:5000,idleTimeoutMillis:30000});} - inventoryPool.on('error',()=>console.error('Inventory database connection unavailable.')); - } - const bankDatabase=await openPostbankDatabase(settings); - const db=await openDatabase(settings);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 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 initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);const handle=createPanel(db,settings,{inventoryPool,bankDatabase}),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),stopCentralScheduler=startCentralScheduler(db,bankDatabase,settings); - 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"}; - const server=createServer(async(req,res)=>{try{ - req.setTimeout(req.url==='/api/internal-mail/messages/send'?120000:30000);const bodyLimit=panelBodyLimit(req.method,req.url);let length=0;const chunks=[];for await(const chunk of req){length+=chunk.length;if(length>bodyLimit){res.writeHead(413,{...security,'Content-Type':'application/json'});res.end(JSON.stringify({message:'The upload exceeds the permitted request size.'}));return;}chunks.push(chunk);} - if(!req.url?.startsWith('/')||req.url.startsWith('//')){res.writeHead(400,security);res.end();return;} - const result=await handle(new Request(origin+req.url,{method:req.method,headers:req.headers,...(!['GET','HEAD'].includes(req.method)?{body:Buffer.concat(chunks)}:{})})); - const headers=new Headers(security);result.headers.forEach((value,key)=>headers.set(key,value)); - res.writeHead(result.status,Object.fromEntries(headers));res.end(Buffer.from(await result.arrayBuffer())); - }catch(error){console.error('Panel request failed:',error.code||error.name);res.writeHead(503,security);res.end('{"message":"The account panel is temporarily unavailable."}');}}); - server.headersTimeout=10000;server.requestTimeout=30000; - await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(Number(settings.CP_PORT||3003),'127.0.0.1',resolve);}); - process.once('SIGTERM',()=>{stopOfficeLedger();stopElectionClock();stopBanSync();stopInternalMail();stopCentralScheduler();server.close(async()=>{await Promise.allSettled([db.close(),bankDatabase?.close(),inventoryPool?.end()]);process.exit(0);});});console.log('Account panel listening on localhost');return server; -} -if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href)await startPanel(); - +import {createClaimHomeBlockRoute} from './claim-home-block-route.mjs'; +export const PANEL_CSP="default-src 'self'; script-src 'self'; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; connect-src 'self' https://usercontent.luckperms.net https://metadata.luckperms.net wss://usersockets.luckperms.net; img-src 'self' data:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self' https://www.dunerealms.com https://dunerealms.com https://clans.dunerealms.com https://corp.dunerealms.com https://corp.dunerealms.com"; +// Company artwork is served by the canonical public asset host. +export const COMPANY_CSP=PANEL_CSP.replace("img-src 'self' data:","img-src 'self' data: https://www.dunerealms.com"); +import {createElectionDirectory} from './election-directory.mjs'; +import {createMenuBadges} from '../node/menu-badges.mjs'; +import {startCentralScheduler} from '../node/postbank-payments.mjs'; +import {createPostbankApi} from '../node/postbank-api.mjs'; +import {openPostbankDatabase} from '../node/postbank-db.mjs'; +import {createItemRegister} from './item-register.mjs'; +import {createManagedTransfers} from './managed-bank-transfer.mjs'; +import {createOfficialBank} from './official-bank.mjs'; +import {createBankBeneficiaries} from './bank-beneficiaries.mjs'; +import {createBankTransfers} from './bank-transfers.mjs'; +import {createHosting} from '../node/hosting.mjs'; +import {initializeOfficeLedger,startOfficeLedger} from './election-office-ledger.mjs'; +import {createMailAccounts} from '../node/mail-accounts.mjs'; +import {createElectionVoting,startElectionClock} from './election-voting.mjs'; +import {initializeBallots} from './election-ballots.mjs'; +import {initializeRounds} from './election-rounds.mjs'; +import {createImperialCharters,initializeCharters} from './imperial-charters.mjs'; +import {createProclamations,initializeProclamations} from './proclamations.mjs'; +import {createElectoralRoll} from '../node/electoral-roll.mjs'; +import {createElectionApplications} from './election-application-route.mjs'; +import {initializeApplications} from './election-applications.mjs'; +import {createInternalMail,startInternalMailSync,initializeInternalMailAccess,syncClanMailRegistry} from '../node/internal-mail.mjs'; +import {createPoliticsPreview} from './politics-preview.mjs'; +import {createPublicGovernment} from '../node/public-government.mjs'; +import{createAdminRegistration}from '../node/admin-registration.mjs'; +import{firstLoginGate,firstLoginState,initializeFirstLogin,createFirstLoginTerms}from '../node/first-login.mjs'; +import {createContactEmail,initializeContactEmails} from '../node/contact-email.mjs'; +import {isOwnerRank} from '../node/permissions.mjs'; +import {createBanEvidence,initializeBanEvidence} from './ban-evidence.mjs'; +import {createUpgradeTokens} from './upgrade-tokens.mjs'; +import {createKitCatalogueBridge} from '../node/kit-catalogue.mjs'; +import {createKitStudio} from './kit-studio.mjs'; +import {startModerationSync} from './moderation.mjs'; +import {createKitMarket} from './kit-market.mjs'; +import {createImperialAtelier} from './imperial-atelier.mjs'; +import {createGameRanks,initializeGameRanks} from '../node/game-ranks.mjs'; +import {createBanking} from './banking.mjs'; +import {createClanShop,initializeClanShop} from './clan-shop.mjs'; +import {createQuests} from './quests.mjs'; +import {createClans,initializeClans} from './clans.mjs'; +import {createClanEmblems} from './clan-emblems.mjs'; +import {createGameTickets} from './game-tickets.mjs'; +import {createQuestRewards} from './quest-rewards.mjs'; +import {openGameMysqlPool} from '../node/game-mysql-pool.mjs'; +import {retiredTicketResponse} from '../node/retired-tickets.mjs'; +import {createGitIdentityRoute,initializeGitIdentities,startGitIdentitySync,gitProxyIdentity} from '../node/git-identity.mjs'; +import {createMailIdentityRoute,initializeMailIdentities} from '../node/mail-identity.mjs'; +import {createProfile} from '../node/profile.mjs'; +import {createWorldStatus} from '../node/world-status.mjs'; +import {createMemorials} from '../node/memorials.mjs'; +import {createMemberProfiles} from '../node/member-profiles.mjs'; +import {createAvatars} from '../node/avatar.mjs'; +import {createTailorAppearance} from '../node/tailor-appearance.mjs'; +import {createBadgeAdmin} from '../node/badge-admin.mjs'; +import {createManualSealRoute} from '../node/manual-seal-route.mjs'; +import {createCompanyAdmin} from '../node/company-admin.mjs'; +import {initializeCompanyRegistry} from '../node/company-registry.mjs'; +import {initializeShareLedger} from '../node/share-ledger.mjs'; +import {initializeSealEntitlements} from '../node/seal-entitlement-store.mjs'; +import {initializeSealCatalog,createSealCatalogAdmin} from '../node/seal-catalog-admin.mjs'; +import {initializeBadges} from '../node/community-badges.mjs'; +import {createBanRegister} from './ban-register.mjs'; +import {createRankAdmin} from '../node/rank-admin.mjs'; +import {createOverview} from './overview.mjs'; +import {createStaffManual} from './staff-manual.mjs'; +import {createLuckPerms} from './luckperms.mjs'; +import {createCommunityAdmin} from './community-admin.mjs'; +import {createExchange} from './exchange.mjs'; +import {createIntegrationSSO} from '../node/integration-sso.mjs'; +import {createBanBridge} from './ban-bridge.mjs'; +import {sharedErrorResponse} from '../node/shared-errors.mjs'; +import {initializeNews} from '../node/news.mjs'; +import {initializeStaffBureau} from '../node/staff-bureau-schema.mjs'; +import {createStaffBureauReadApi} from '../node/staff-bureau-read-api.mjs'; +import {initializeOrganisation} from '../node/organisation-model.mjs'; +import {createLifeStatus,initializeLifeStatus} from '../node/life-status.mjs'; +import {createCitizenDirectory} from '../node/citizen-directory.mjs'; +import {createOrganisationManagement} from '../node/organisation-management.mjs'; +import {initializeRanks,initializeCommunityAccess,initializeQuestAccess,initializeBankAccess,can,accessFor} from '../node/permissions.mjs'; +import {createServer} from 'node:http'; +import {companyCPDocument} from './company-cp-shell.mjs'; +import {createCompanyWorkspace} from '../node/company-workspace.mjs'; +import {clanCPDocument} from './clan-cp-shell.mjs'; +import {politicsCPDocument} from './politics-cp-shell.mjs'; +import {createV1PersonalBank} from './api-v1-personal-bank.mjs'; +import {readFile} from 'node:fs/promises'; +import {pathToFileURL} from 'node:url'; +import {accountSchema} from './imperial-accounts.mjs'; +import {openDatabase} from '../node/mysql.mjs'; +import {createAuth} from '../node/auth.mjs'; +import {identity} from '../node/auth.mjs'; +import {createHonourRoute} from '../node/honour-route.mjs'; +import {panelBodyLimit} from './request-limits.mjs'; +import {initializeHonours} from '../node/honours.mjs'; +import {createBankClientApi} from '../node/bank-clients.mjs'; +import {createInventoryHandler,createSalesHistoryHandler} from './inventory/inventory-api.mjs'; +import {createMarketBridge} from './inventory/market-bridge.mjs'; +import {createGameLink,json} from '../node/game-link.mjs'; +import {createCommunityRewards} from '../node/community-rewards.mjs'; +import {createAccountAdmin} from '../node/account-admin.mjs'; +import {createServerControl} from './server-control.mjs'; +const types={'.html':'text/html; charset=utf-8','.js':'text/javascript; charset=utf-8','.mjs':'text/javascript; charset=utf-8','.css':'text/css; charset=utf-8'}; +const sharedAssets=new Set(['organisation-deed-keys-v1.png','organisation-deeds-clan-tiers-v1.png','organisation-deeds-company-tiers-v1.png','organisation-deeds-protected-v1.png','spost-logo-v1.svg','postbank-transfer-hall-v1.png','corrino-group-v4.png','corrino-group-v3.svg','corrino-charter-v2.png','corrino-founding-marks-v1.png','consortium-corrini-v1.png','corrino-charter-v1.png','corrino-founder-v1.png','imperial-postbank-v2.png','spost-company-v1.png','vaerkring-company-v1.png','imperial-postbank-v1.png','corrino-group-logo.svg','spicepost-logo-v2.svg','spicepost-logo.svg','imperial-post-seal-v2.png','imperial-post-seal.svg','imperial-post-office-v1.png','mail-stamp-imperial.svg','mail-stamp-faction.svg','mail-stamp-staff.svg','mail-stamp-clan.svg','mail-stamp-personal.svg','imperial-post-logo.svg','ornament.webp','guild.webp','minecraft-hero.webp','menu-0.webp','reward-gold-ingot-transparent-v1.png','menu-5.webp','menu-6.webp','menu-9.webp','menu-12.webp','item-23.webp','dunemark-icon-64.png','arrakis-lore-frieze.svg']); +export function createPanel(db,settings={},dependencies={}){ + const itemRegister=createItemRegister(db); + const worldStatus=dependencies.worldStatus||createWorldStatus(settings); + const origin=new URL(settings.CP_ORIGIN||'https://cp.dunerealms.com').origin; + const contactEmail=createContactEmail(db,{origin,...dependencies.contactEmail}); + const internalMail=createInternalMail(db,{origin,settings,...dependencies.internalMail}); + const terms=createFirstLoginTerms(db,origin); + const auth=createAuth(db,origin,{...settings,trackFirstLogin:true}),links=createGameLink(db,settings,origin),rewards=createCommunityRewards(db,settings,origin); + const homeBlockClaims=createClaimHomeBlockRoute(db,settings); + const hosting=createHosting(db,{origin});const mailAccounts=createMailAccounts(db);const mailIdentity=createMailIdentityRoute(db,{origin}),gitIdentity=createGitIdentityRoute(db,settings,origin); + const adminRegistration=createAdminRegistration(db,origin);const admin=createAccountAdmin(db,origin),profile=createProfile(db,settings,origin),avatars=createAvatars(db,settings); + 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 companyWorkspace=createCompanyWorkspace(db); + const manual=createStaffManual(db); + const staffBureauRead=createStaffBureauReadApi(db); + const citizenDirectory=createCitizenDirectory(db);const lifeStatus=createLifeStatus(db,{origin}); + const organisationManagement=createOrganisationManagement(db,{origin}); + const luckperms=createLuckPerms(db,settings,dependencies.luckperms); + const servers=createServerControl(db,settings,dependencies.serverControl); + const pool=dependencies.inventoryPool||{async query(){throw Error('Inventory database is not configured');}}; + const community=createCommunityAdmin(db,settings,{pool}); + const exchange=createExchange(db,pool); + const clans=createClans(db,{origin,onClanCreated:()=>syncClanMailRegistry(db),onClanDeleted:()=>syncClanMailRegistry(db)}),gameTickets=createGameTickets(db,settings); + const clanEmblems=createClanEmblems(db,{origin}); + const questRewards=createQuestRewards(db,settings,pool); + const gameRanks=createGameRanks(db,settings); + const kitStudio=createKitStudio(db,settings,dependencies.kitStudio); + const upgradeTokens=createUpgradeTokens(db,settings,dependencies.upgradeTokens); + const publicKitCatalogue=createKitCatalogueBridge(settings,{db}); + const kitMarket=createKitMarket(db,settings,dependencies.kitMarket); + const imperialAtelier=createImperialAtelier(db,settings,dependencies.imperialAtelier); + const bankBeneficiaries=createBankBeneficiaries(db,dependencies.bankBeneficiaries); + const officialBank=createOfficialBank(db,settings,dependencies.officialBank); + const managedTransfers=createManagedTransfers(db,settings,dependencies.managedTransfers); + const bankTransfers=createBankTransfers(db,settings,dependencies.bankTransfers); + const banking=createBanking(db,settings,dependencies.banking); + const postbank=createPostbankApi(db,dependencies.bankDatabase||null,settings,dependencies.postbank); + const bankClient=createBankClientApi(db,dependencies.bankClient); + const v1PersonalBank=createV1PersonalBank(banking,{enabled:process.env.DUNE_API_V1_BANK_STAGING==='true'}); + const quests=createQuests(db,settings,dependencies.quests),clanShop=createClanShop(db,settings,dependencies.clanShop); + const sso=createIntegrationSSO(db,settings); + const overview=createOverview(db);const menuBadges=createMenuBadges(db,settings); + const banBridge=createBanBridge(db,settings,dependencies.bans); + const banRegister=createBanRegister(db,settings,dependencies.bans); + const electionDirectory=createElectionDirectory(db,dependencies.electionDirectory); + const electionVoting=createElectionVoting(db,settings,dependencies.electionVoting); + const imperialCharters=createImperialCharters(db,settings); + const proclamations=createProclamations(db,settings); + const electoralRoll=createElectoralRoll(db); + const electionApplications=createElectionApplications(db,settings,dependencies.electionApplications); + const politicsPreview=createPoliticsPreview(db,settings,dependencies.politicsPreview); + const publicGovernment=createPublicGovernment(db); + const banEvidence=createBanEvidence(db,settings,dependencies.banEvidence); + const inventoryOptions={authenticate:request=>identity(request,db),verifiedMinecraftUuid:async accountId=>(await db.prepare('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?').bind(accountId).first())?.minecraft_uuid||null,pool,logger:dependencies.logger||console}; + const inventory=createInventoryHandler(inventoryOptions),sales=createSalesHistoryHandler(inventoryOptions); + const market=(settings.EXCHANGE_READ_TOKEN||'').length>=32?createMarketBridge({pool,readToken:settings.EXCHANGE_READ_TOKEN}):null; + return async request=>{const retiredTickets=retiredTicketResponse(request);if(retiredTickets)return retiredTickets; + const path=new URL(request.url).pathname; + if(path==='/api/public/government')return publicGovernment(request); + if(['/api/menu-badges','/api/staff/menu-badges'].includes(path))return menuBadges(request); + if(['/v2/cp-v2-menu-badges.mjs','/v2/cp-v2-dunemark-collection.mjs','/v2/dunemark-catalogue.mjs'].includes(path))return new Response(await readFile(new URL('./public/cp-v2/'+path.slice(4),import.meta.url)),{headers:{'Content-Type':'text/javascript; charset=utf-8','Cache-Control':'no-store'}}); + if(path==='/api/items/catalogue')return itemRegister(request); + if(path==='/api/worlds')return request.method==='GET'?worldStatus():new Response('Method not allowed',{status:405}); + const onboarding=await firstLoginGate(request,db);if(onboarding)return onboarding; + if(settings.POSTBANK_ENABLED==='true'&&path.startsWith('/api/bank/'))return postbank(request); + if(settings.POSTBANK_ENABLED==='true'&&path==='/api/v1/me/bank')return json({message:'The game-linked bank has been retired from this website.'},410); + if(path==='/api/politics/directory')return electionDirectory(request); + if(['/api/politics/ballot/house','/api/politics/ballot/imperial','/api/politics/ballot/bene','/api/politics/ballot/guild','/api/politics/ballot/clan_delegate'].includes(path))return electionVoting(request); + if(path==='/api/politics/charters')return imperialCharters(request); + if(path==='/api/politics/proclamations')return proclamations(request); + if(path==='/api/politics/electoral-roll')return electoralRoll(request); + if(path==='/api/politics/applications')return electionApplications(request); + if(path==='/api/politics/preview')return politicsPreview(request); + if(path==='/api/admin/register-user')return adminRegistration(request); + if(path==='/api/admin/life-status')return lifeStatus(request); + if(path==='/api/admin/citizens'||path.startsWith('/api/admin/citizens/'))return citizenDirectory(request); + if(path.startsWith('/api/admin/organisation/'))return organisationManagement(request); + if(path==='/api/account/email')return contactEmail(request); + if(path.startsWith('/api/people/'))return memberProfiles(request); + if(path==='/profile-login'&&request.method==='GET'){ + const username=new URL(request.url).searchParams.get('username');if(!/^[a-z0-9_]{3,32}$/.test(username||'')||!await db.prepare("SELECT id FROM site_accounts WHERE username=? AND password_hash NOT LIKE '!%'").bind(username).first())return new Response('Profile not found',{status:404}); + return Response.redirect(await identity(request,db)?'https://www.dunerealms.com/people/'+username:origin+'/?return_to='+encodeURIComponent('/profile-login?username='+username),302); + } + if(path==='/memorial-login'&&request.method==='GET'){ + const slug=new URL(request.url).searchParams.get('slug');if(!/^[a-z0-9-]{3,64}$/.test(slug||'')||!await db.prepare('SELECT slug FROM site_memorials WHERE slug=?').bind(slug).first())return new Response('Memorial not found',{status:404}); + return Response.redirect(await identity(request,db)?'https://www.dunerealms.com/memorial/'+slug:origin+'/?return_to='+encodeURIComponent('/memorial-login?slug='+slug),302); + } + if(path.startsWith('/api/memorials/')){ + const from=request.headers.get('origin'),allowed='https://www.dunerealms.com';if(from&&from!==allowed)return new Response(null,{status:403}); + const headers={'Access-Control-Allow-Origin':allowed,'Access-Control-Allow-Credentials':'true','Access-Control-Allow-Methods':'GET, POST, OPTIONS','Access-Control-Allow-Headers':'Content-Type','Vary':'Origin','Cache-Control':'no-store'}; + if(request.method==='OPTIONS')return new Response(null,{status:204,headers}); + const result=await memorials(request),out=new Headers(result.headers);for(const[k,v]of Object.entries(headers))out.set(k,v);return new Response(result.body,{status:result.status,headers:out}); + } + if(path==='/api/game/tickets')return gameTickets(request); + if(['/api/game/quest/discover','/api/quest/rewards','/api/quest/rewards/claim'].includes(path))return questRewards(request); + if(path==='/api/imperial-atelier')return imperialAtelier(request); + if(path==='/internal/kits/catalogue')return publicKitCatalogue(request); + if(['/api/kits/studio','/api/kits/server-studio'].includes(path))return kitStudio(request); + if(path==='/api/kits/upgrade-tokens')return upgradeTokens(request); + if(path.startsWith('/api/kits/'))return kitMarket(request); + if(path==='/api/ranks/game')return gameRanks(request); + if(path==='/api/bank/beneficiaries')return bankBeneficiaries(request); + if(path==='/api/bank/official')return officialBank(request); + if(path==='/api/bank/managed-transfer')return managedTransfers(request); + if(path==='/api/bank/transfer-own'||path==='/api/bank/remittance')return bankTransfers(request); + if(path==='/api/bank/client')return bankClient(request); + if(path==='/api/bank/personal'||path==='/api/bank/staff'||path==='/api/bank/faction')return banking(request); + if(path==='/api/v1/me/bank')return v1PersonalBank(request); + 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==='/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); + if(path.startsWith('/api/internal-mail/'))return internalMail(request); + if(path==='/api/git/me')return gitIdentity(request); + if(['/api/mail/me','/api/mail/password','/api/mail/signature','/api/mail/template'].includes(path))return mailIdentity(request); + if(['/api/account/profile','/api/account/avatar','/api/account/avatar/remove'].includes(path))return profile(request); + if(path.startsWith('/api/avatars/'))return avatars(request); + if(path==='/api/tailor/appearance'||path==='/api/tailor/skin')return tailorAppearance(request); + if(path==='/api/badges')return badges(request); + if(path==='/api/seals/manual')return manualSeals(request); + if(path==='/api/seals/catalog'||path.startsWith('/api/seals/artwork/'))return sealCatalog(request); + if(path==='/api/companies/workspace')return companyWorkspace(request); + if(path==='/api/companies/manage')return companyAdmin(request); + if(path.startsWith('/api/v1/staff/'))return staffBureauRead(request); + if(path==='/api/ban-register')return banRegister(request); + if(path==='/api/ban-evidence'||path==='/api/ban-evidence/file')return banEvidence(request); + if(path==='/api/public/bans'&&request.method==='GET')return banBridge.publicBans(); + if(path==='/api/overview'||path==='/api/overview/staff')return overview(request); + const sharedError=await sharedErrorResponse(request);if(sharedError)return sharedError; + if(path==='/internal/integrations/ban')return banBridge.handle(request); + if(path==='/sso/authorize'||path.startsWith('/internal/integrations/'))return sso(request); + if(path==='/api/v1/claims/home-blocks'||/^\/api\/v1\/claims\/home-blocks\/[a-f0-9-]{36}\/commands$/i.test(path))return homeBlockClaims(request); + if(path==='/api/exchange/listings')return exchange(request); + if(path.startsWith('/api/cp/'))return community(request); + if(path.startsWith('/luckperms-editor/')){ + const user=await identity(request,db);if(!user)return json({message:'Sign in first.'},401); + if(!isOwnerRank((await accessFor(db,user)).rank)||!await can(db,user,'web.menu.luckperms')||!await can(db,user,'web.luckperms.edit'))return json({message:'LuckPerms editor access is restricted to Owners with web.luckperms.edit.'},403); + if(!['GET','HEAD'].includes(request.method))return json({message:'Method not allowed'},405); + let file=path.slice('/luckperms-editor/'.length); + if(!file||/^editor(?:\/[A-Za-z0-9_-]{3,200})?\/?$/.test(file))file='index.html'; + if(!/^[A-Za-z0-9_./-]+$/.test(file)||file.includes('..'))return json({message:'Not found'},404); + const extension=file.slice(file.lastIndexOf('.')),mime={...types,'.svg':'image/svg+xml','.png':'image/png','.ico':'image/x-icon','.woff':'font/woff','.woff2':'font/woff2','.ttf':'font/ttf','.txt':'text/plain; charset=utf-8'}[extension]; + if(!mime)return json({message:'Not found'},404); + try{return new Response(request.method==='HEAD'?null:await readFile(new URL('./native-editor/'+file,import.meta.url)),{headers:{'Content-Type':mime,'Cache-Control':'private, no-store','Content-Security-Policy':PANEL_CSP}});}catch{return json({message:'Native LuckPerms editor build is unavailable.'},404);} + } + if(path.startsWith('/api/luckperms/'))return luckperms(request); + if(path==='/api/staff/manual')return manual(request); + if(path==='/api/ranks/honour')return honours(request); + if(path==='/api/game/permissions'||path==='/api/ranks'||path.startsWith('/api/ranks/'))return ranks(request); + const menu=path==='/api/inventory'||path==='/api/exchange/sales-history'?'web.menu.inventory':(path==='/api/game-link'||path.startsWith('/api/game-link/')&&path!=='/api/game-link/consume')?'web.menu.game':path==='/api/community/rewards'?'web.menu.rewards':null; + if(menu){const user=await identity(request,db);if(!user)return json({message:'Sign in first.'},401);if(!await can(db,user,menu))return json({message:'Permission required: '+menu},403);} + if(path==='/api/servers'||path.startsWith('/api/servers/'))return servers(request); + if(path==='/api/inventory')return inventory(request); + if(path==='/api/exchange/sales-history')return sales(request); + if(path==='/internal/exchange/listings')return market?market(request):new Response('Not configured',{status:503,headers:{'Cache-Control':'no-store'}}); + if(path.startsWith('/api/admin/'))return admin(request); + if(path==='/healthz'){await db.prepare('SELECT 1 AS ok').first();return json({status:'ok'});} + if(path==='/api/welcome'&&request.method==='GET'){const allowed=new Set(['https://corp.dunerealms.com','https://www.dunerealms.com','https://dunerealms.com','https://forums.dunerealms.com','https://support.dunerealms.com','https://clans.dunerealms.com','https://wiki.dunerealms.com','https://cp.dunerealms.com']);const origin=request.headers.get('origin');if(origin&&!allowed.has(origin))return new Response(null,{status:403});const user=await identity(request,db);return new Response(JSON.stringify({username:user?.username||null}),{headers:{'Content-Type':'application/json','Cache-Control':'no-store','Vary':'Origin',...(origin?{'Access-Control-Allow-Origin':origin,'Access-Control-Allow-Credentials':'true'}:{})}});} + if(path==='/api/auth/terms')return terms(request); + if(path==='/api/auth/session'&&request.method==='GET'){const response=await auth(request),data=await response.json();if(data.user)data.user.firstLogin=await firstLoginState(db,await identity(request,db));return json(data);} + if(path.startsWith('/api/auth/'))return auth(request); + if(path==='/api/game-link'||path.startsWith('/api/game-link/'))return links(request); + if(path.startsWith('/api/community/'))return rewards(request); + if(!['GET','HEAD'].includes(request.method))return new Response('Method not allowed',{status:405}); + if(/^\/kit-textures\/(?:entity\/(?:banner\/[a-z_]+|equipment\/(?:humanoid|humanoid_leggings)\/netherite)|trims\/(?:color_palettes\/[a-z_]+|entity\/(?:humanoid|humanoid_leggings)\/[a-z_]+))\.png$/.test(path)){ + try{return new Response(request.method==='HEAD'?null:await readFile(new URL('../web/assets/'+path.slice(1),import.meta.url)),{headers:{'Content-Type':'image/png','Cache-Control':'public, max-age=86400'}});}catch{return new Response('Texture not found',{status:404});} + } + if(path.startsWith('/assets/')&&sharedAssets.has(path.slice(8))){const file=path.slice(8);return new Response(request.method==='HEAD'?null:await readFile(new URL('../web/assets/'+file,import.meta.url)),{headers:{'Content-Type':file.endsWith('.svg')?'image/svg+xml':file.endsWith('.png')?'image/png':'image/webp','Cache-Control':'public, max-age=3600'}});} + if(path==='/federal-reserve'||path==='/federal-reserve/')return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/reserve-ledger.html',import.meta.url)),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}}); + // V2 shell is public; private data and writes retain their authenticated API gates. + if(path==='/company-cp')return new Response(request.method==='HEAD'?null:companyCPDocument(await readFile(new URL('./public/cp-v2/index.html',import.meta.url),'utf8')),{headers:{'Content-Security-Policy':COMPANY_CSP,'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}}); + if(path==='/clan-cp')return new Response(request.method==='HEAD'?null:clanCPDocument(await readFile(new URL('./public/cp-v2/index.html',import.meta.url),'utf8')),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}}); + if(path==='/politics-cp')return new Response(request.method==='HEAD'?null:politicsCPDocument(await readFile(new URL('./public/cp-v2/index.html',import.meta.url),'utf8')),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}}); + // All authored cp-v2 browser modules share this bounded public directory. + // New components must not require a second, manually maintained route list. + if(/^\/(?:v2|cp-v2)\/cp-v2-[a-z0-9-]+\.(?:mjs|css)$/.test(path)){ + try{const bytes=await readFile(new URL('./public/cp-v2/'+path.slice(path.lastIndexOf('/')+1),import.meta.url));return new Response(request.method==='HEAD'?null:bytes,{headers:{'Content-Type':path.endsWith('.css')?'text/css; charset=utf-8':'text/javascript; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}});}catch(error){if(error.code==='ENOENT')return new Response('Not found',{status:404});throw error;} + } + if(['/v2/citizen-directory.mjs','/v2/citizen-directory.css','/v2/organisation-permissions.mjs'].includes(path))return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/'+path.slice('/v2/'.length),import.meta.url)),{headers:{'Content-Type':path.endsWith('.css')?'text/css; charset=utf-8':'text/javascript; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}}); + if(['/','/index.html','/v2','/v2/','/v2/cp-v2-politics-pages.mjs','/v2/cp-v2-auth.mjs','/v2/cp-v2-access.mjs','/v2/citizens-registry.mjs','/v2/cp-v2-page-template.mjs','/v2/imperial-permissions.mjs','/v2/honours-seals.mjs','/v2/cp-v2-planned-pages.mjs','/v2/cp-v2-choam-pages.mjs','/v2/cp-v2-bureau-pages.mjs','/v2/cp-v2-service-pages.mjs','/v2/cp-v2-newsroom.mjs','/v2/cp-v2-moderation.mjs','/v2/cp-v2-native-services.mjs','/v2/cp-v2-exchange-authority.mjs','/v2/cp-v2-crysknife.mjs','/v2/cp-v2-post-menu.mjs','/v2/cp-v2-postbank-foundation.mjs','/v2/cp-v2-postbank-payments.mjs','/v2/cp-v2-postbank-admin.mjs','/v2/cp-v2-authorisations.mjs','/v2/cp-v2-tax-treasury.mjs','/v2/cp-v2-reserve-ledger.mjs','/v2/cp-v2-reserve-entry.mjs','/v2/cp-v2-postbank-credit.mjs','/v2/cp-v2-postbank-beneficiaries.mjs','/v2/cp-v2-postbank-statement-archive.mjs','/v2/cp-v2-bank-pages.mjs','/v2/cp-v2-post-pages.mjs','/v2/cp-v2-code-redemption.mjs','/v2/cp-v2-rewards.mjs','/v2/cp-v2-user-commerce.mjs','/v2/cp-v2-user-pages.mjs','/v2/cp-v2-user-api.mjs','/v2/cp-v2-security.mjs','/v2/cp-v2-passport.mjs','/v2/cp-v2-personal-records.mjs','/v2/cp-v2-design-pages.mjs','/v2/cp-v2-design-catalog.mjs','/v2/cp-v2-forge-pages.mjs','/v2/cp-v2-hosting.mjs','/v2/cp-v2-community-treasury.mjs','/v2/cp-v2-item-register.mjs','/v2/cp-v2-kit-directorate.mjs','/v2/cp-v2-campaigns.mjs','/v2/cp-v2-imperial-revenue.mjs','/v2/cp-v2-read-register.mjs','/v2/cp-v2-bureau-data.mjs','/v2/cp-v2-company-actions.mjs','/v2/v2.css','/v2/v2.js'].includes(path)){ + const moduleFile=path.endsWith('.mjs')||path.endsWith('.js'); + const file=path.endsWith('.mjs')?path.slice('/v2/'.length):path.endsWith('.js')?'v2.js':path.endsWith('.css')?'v2.css':'index.html'; + return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/'+file,import.meta.url)),{headers:{'Content-Type':moduleFile?'text/javascript; charset=utf-8':file.endsWith('.css')?'text/css; charset=utf-8':'text/html; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}}); + } + const file=path==='/'?'index.html':path==='/servers'?'servers.html':path.slice(1); + if(!['user-service.html','user-service-entry.mjs','user-service.css','kit-receipt-status.mjs','clan-center.html','clan-center-entry.mjs','clan-center.css','bank-transfer-view.mjs','bank-dashboard.mjs','mail-service-ui.mjs','mail-workspace.css','hosting-control.mjs','internal-mail.mjs','internal-mail.css','election-voting-view.mjs','imperial-charters-view.mjs','proclamations-view.mjs','electoral-roll-view.mjs','election-applications-view.mjs','election-rules.mjs','political-catalog.mjs','menu-ribbons.mjs','council-preview.mjs','politics.mjs','crysknife.mjs','x-news-draft.mjs','terms.html','admin-registration.mjs','mail-signature.mjs','webmail.mjs','git-control.mjs','git-control.css','site-profile.mjs','site-profile.css','servers.html','servers.js','servers.css','pages.mjs','user-page-hero.mjs','commerce-settings.mjs','shop-management.mjs','center-portals.mjs','panel-layout.mjs','embed-size.mjs','dev-request-access.mjs','center-portals.css','overview.mjs','overview.css','page-groups.mjs','ban-register.mjs','moderation-form-response.mjs','ban-record-cards.css','ban-evidence.mjs','ban-evidence.css','ranks.mjs','ranks.css','staff-manual.mjs','luckperms.mjs','community-admin.mjs','native-community.mjs','exchange.mjs','exchange.css','clans.mjs','clan-shop.mjs','house-tailor.mjs','banking.mjs','banking.css','game-ranks.mjs','upgrade-shop.mjs','kit-generator.mjs','kit-design-model.mjs','kit-equipment-editor.mjs','kit-texture-preview.mjs','kit-generator.css','kit-market.mjs','kit-market.css','kit-cart.mjs','imperial-atelier.mjs','quests.mjs','quests.css','clans.css','clan-request-gate.mjs','clan-directory-model.mjs','clan-profile-panels.mjs','organisation-settings.mjs','organisation-settings.css','organisation-dashboard.mjs','organisation-dashboard.css','organisation-activity.mjs','clan-dashboard-data.mjs','quest-rewards.mjs','quest-rewards.css','inventory/inventory-view.mjs','inventory/inventory-mount.mjs','inventory/inventory.css'].includes(file))return new Response('Not found',{status:404}); + return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/'+file,import.meta.url)),{headers:{'Content-Type':types[file.slice(file.lastIndexOf('.'))],'Cache-Control':'no-store'}}); + }; +} +export async function startPanel(settings=process.env){ + let inventoryPool=null; + if(settings.DUNE_INVENTORY_DATABASE_URL){ + if(settings.DUNE_INVENTORY_DATABASE_URL.startsWith('mysql:'))inventoryPool=await openGameMysqlPool(settings.DUNE_INVENTORY_DATABASE_URL); + else{const {Pool}=await import('pg');inventoryPool=new Pool({connectionString:settings.DUNE_INVENTORY_DATABASE_URL,max:3,connectionTimeoutMillis:5000,idleTimeoutMillis:30000});} + inventoryPool.on('error',()=>console.error('Inventory database connection unavailable.')); + } + const bankDatabase=await openPostbankDatabase(settings); + const db=await openDatabase(settings);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 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 initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);const handle=createPanel(db,settings,{inventoryPool,bankDatabase}),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),stopCentralScheduler=startCentralScheduler(db,bankDatabase,settings); + 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"}; + const server=createServer(async(req,res)=>{try{ + req.setTimeout(req.url==='/api/internal-mail/messages/send'?120000:30000);const bodyLimit=panelBodyLimit(req.method,req.url);let length=0;const chunks=[];for await(const chunk of req){length+=chunk.length;if(length>bodyLimit){res.writeHead(413,{...security,'Content-Type':'application/json'});res.end(JSON.stringify({message:'The upload exceeds the permitted request size.'}));return;}chunks.push(chunk);} + if(!req.url?.startsWith('/')||req.url.startsWith('//')){res.writeHead(400,security);res.end();return;} + const result=await handle(new Request(origin+req.url,{method:req.method,headers:req.headers,...(!['GET','HEAD'].includes(req.method)?{body:Buffer.concat(chunks)}:{})})); + const headers=new Headers(security);result.headers.forEach((value,key)=>headers.set(key,value)); + res.writeHead(result.status,Object.fromEntries(headers));res.end(Buffer.from(await result.arrayBuffer())); + }catch(error){console.error('Panel request failed:',error.code||error.name);res.writeHead(503,security);res.end('{"message":"The account panel is temporarily unavailable."}');}}); + server.headersTimeout=10000;server.requestTimeout=30000; + await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(Number(settings.CP_PORT||3003),'127.0.0.1',resolve);}); + process.once('SIGTERM',()=>{stopOfficeLedger();stopElectionClock();stopBanSync();stopInternalMail();stopCentralScheduler();server.close(async()=>{await Promise.allSettled([db.close(),bankDatabase?.close(),inventoryPool?.end()]);process.exit(0);});});console.log('Account panel listening on localhost');return server; +} +if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href)await startPanel(); + diff --git a/website/node/claim-command-service.mjs b/website/node/claim-command-service.mjs new file mode 100644 index 00000000..abf9a8ac --- /dev/null +++ b/website/node/claim-command-service.mjs @@ -0,0 +1,53 @@ +import {createHash,randomUUID} from 'node:crypto'; +import {claimTariffs,CLAIM_REVENUE_SYSTEM_KEY,CLAIM_TARIFF_VERSION} from '../control-panel/public/cp-v2/cp-v2-claim-tariffs.mjs'; +export class ClaimCommandError extends Error{constructor(message,status=409){super(message);this.status=status;}} +const uuid=s=>typeof s==='string'&&/^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i.test(s); +export function nextClaimUpgrade(state,charter='basic'){ + const rows=claimTariffs(state.kind),index=rows.findIndex(r=>r.code===state.tier),next=rows[index+1]; + if(index<0)throw new ClaimCommandError('Current claim tier is unavailable.'); + if(!next)return null; + if(state.pendingUpgrade)return {...next,blocked:'An upgrade is awaiting game/payment confirmation.'}; + if(next.stage==='Keyed'&&!['original','royal'].includes(charter))return {...next,blocked:'Redeem your original organisation key before unlocking Keyed claim tiers.'}; + if(next.stage==='Royal'&&charter!=='royal')return {...next,blocked:'A verified Royal appointment is required.'}; + return next; +} +// One command contract for web and future authenticated game callers. Persistence +// and bank/WorldGuard coordination belong to adapters, not to either user interface. +export function createClaimCommandService({store,adapter}){ + return { + async read(context){const state=await store.read(context);return {...state,next:nextClaimUpgrade(state,context.charter),tariffVersion:CLAIM_TARIFF_VERSION,provider:adapter.name,simulation:adapter.simulation===true};}, + async upgrade(context,id,input){ + if(!uuid(id)||!input||input.action!=='claim.tier.upgrade'||input.confirmed!==true||!uuid(input.requestId)||!Number.isSafeInteger(input.expectedRevision)||input.expectedRevision<1||typeof input.targetTier!=='string'||Object.keys(input).some(k=>!['action','confirmed','requestId','expectedRevision','targetTier','tariffVersion','expectedUnlockMinor'].includes(k)))throw new ClaimCommandError('Review and confirm a valid claim upgrade.',400); + return store.exclusive(context,id,async state=>{ + const fingerprint=createHash('sha256').update(JSON.stringify([context.userId,context.organisationId,id,input.action,input.targetTier,input.expectedRevision,input.tariffVersion,input.expectedUnlockMinor])).digest('hex'),prior=state.receipts[input.requestId]; + if(prior){if(prior.fingerprint!==fingerprint)throw new ClaimCommandError('This request reference belongs to another command.');return {...prior.result,replayed:true};} + if(state.pendingUpgrade)throw new ClaimCommandError('An upgrade is already pending confirmation.'); + if(state.revision!==input.expectedRevision)throw new ClaimCommandError('The Home Block changed. Refresh before upgrading.'); + const next=nextClaimUpgrade(state,context.charter);if(!next||next.code!==input.targetTier)throw new ClaimCommandError('Only the next sequential claim tier can be unlocked.'); + if(input.tariffVersion!==CLAIM_TARIFF_VERSION||input.expectedUnlockMinor!==next.unlockMinor)throw new ClaimCommandError('The tariff quote changed. Refresh and review the new price.'); + if(next.blocked)throw new ClaimCommandError(next.blocked,403); + // The adapter must authorise payment, protect the region and settle once. A + // real adapter may return pending; never report pending as a completed upgrade. + const applied=await adapter.executeUpgrade({state:structuredClone(state),context,next,requestId:input.requestId,revenueSystemKey:CLAIM_REVENUE_SYSTEM_KEY}); + if(!['applied','pending'].includes(applied.status))throw new ClaimCommandError('The game/payment adapter did not confirm an upgrade.'); + const result={ok:true,status:applied.status,simulation:adapter.simulation===true,homeBlock:applied.state,paidMinor:applied.status==='applied'?next.unlockMinor:0}; + if(applied.status==='applied')Object.assign(state,applied.state);else state.pendingUpgrade={requestId:input.requestId,targetTier:next.code}; + state.receipts[input.requestId]={fingerprint,result};return result; + }); + } + }; +} +export function createClaimSimulation(){ + const states=new Map(),locks=new Map(),limit=500,ttl=2*60*60*1000; + const identity=c=>c.userId+':'+c.organisationId; + const fresh=c=>{const state={id:randomUUID(),organisationId:c.organisationId,name:c.name,kind:c.kind,tier:claimTariffs(c.kind)[0].code,revision:1,capacity:1,usedChunks:1,worldUuid:'00000000-0000-4000-8000-000000000001',serverKey:'simulation-only',position:{x:8,y:64,z:8},testCreditMinor:100000,testTaxMinor:0,worldguardRegions:[],receipts:{},expiresAt:Date.now()+ttl,claimedChunks:[{x:0,z:0}]};state.worldguardRegions=[{id:'fixture_'+state.id.replaceAll('-','')+'_0_0',type:'cuboid',min:{x:0,y:-64,z:0},max:{x:15,y:319,z:15}}];return state;}; + const stateFor=c=>{const key=identity(c);let state=states.get(key);if(state&&state.expiresAt<=Date.now()){states.delete(key);state=null;}if(!state){for(const [k,v]of states)if(v.expiresAt<=Date.now())states.delete(k);if(states.size>=limit)throw new ClaimCommandError('The simulation is busy. Try again later.',503);state=fresh(c);states.set(key,state);}return state;}; + const visible=state=>{const {receipts,expiresAt,...snapshot}=state;return structuredClone(snapshot);}; + const store={async read(c){return visible(stateFor(c));},async exclusive(c,id,work){const key=identity(c),previous=locks.get(key)||Promise.resolve();let release;const held=new Promise(r=>{release=r;});const queued=previous.then(()=>held);locks.set(key,queued);await previous;try{const state=stateFor(c);if(state.id!==id||state.organisationId!==c.organisationId)throw new ClaimCommandError('Home Block access denied.',403);const result=await work(state);return structuredClone(result);}finally{release();if(locks.get(key)===queued)locks.delete(key);}}}; + const adapter={name:'fake-worldguard-and-bank',simulation:true,async executeUpgrade({state,next,revenueSystemKey}){ + if(state.testCreditMinor{ return {id:'fixture_'+state.id.replaceAll('-','')+'_'+x+'_'+z,type:'cuboid',min:{x:x*16,y:-64,z:z*16},max:{x:x*16+15,y:319,z:z*16+15}};}); + return {status:'applied',state:{...visible(state),tier:next.code,capacity:next.chunks,revision:state.revision+1,testCreditMinor:state.testCreditMinor-next.unlockMinor,testTaxMinor:state.testTaxMinor+next.unlockMinor,revenueSystemKey,worldguardRegions}}; + }}; + return createClaimCommandService({store,adapter}); +} diff --git a/website/scripts/build.mjs b/website/scripts/build.mjs index a412c6d4..2529ec23 100644 --- a/website/scripts/build.mjs +++ b/website/scripts/build.mjs @@ -1,50 +1,50 @@ -import {HOUSE_STYLE_CSS} from './house-style.mjs'; -import {bankRatesPage} from './bank-rates-page.mjs'; -import{withCanonicalMenu,MAIN_MENU}from'./main-menu.mjs'; -import{withMenuBadges}from'./menu-updates.mjs'; -import{updatePortalNavigation}from'./portal-navigation.mjs'; -// Package the authored web and worker sources without rewriting their content. -import {readFileSync,writeFileSync,openSync,writeSync,closeSync,readdirSync,statSync,mkdirSync,existsSync,rmSync,cpSync} from 'node:fs';import path from 'node:path';import {fileURLToPath} from 'node:url'; -const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..'),web=path.join(root,'web'),dist=path.join(root,'dist'); -// Fail before packaging if a public menu destination or illustration is missing. -for(const [label,href,icon] of MAIN_MENU){ - const url=new URL(href); - if(url.hostname==='www.dunerealms.com'){ - const relative=url.pathname==='/'?'index.html':decodeURIComponent(url.pathname.slice(1)); - if(!existsSync(path.join(web,relative)))throw Error('Broken public menu link: '+label+' -> '+relative); - } - if(!existsSync(path.join(web,'assets',icon)))throw Error('Missing menu artwork: '+label+' -> '+icon); -} -for(const [page,dependencies] of [['shop.html',['shop-landing.css','shop-embed.js']],['kits.html',['kits.css','kits.js']]]){ - for(const file of dependencies)if(!existsSync(path.join(web,file)))throw Error('Missing '+page+' dependency: '+file); -} -// Menu badges are now published manually through Imperial Bureau. -const homepage=readFileSync(path.join(web,'index.html'),'utf8'); -const legalNotice=homepage.match(/