From 5b8ba631b572a68ed24f26f5e058b77ad36e17f0 Mon Sep 17 00:00:00 2001 From: Dev Date: Thu, 5 Nov 2026 11:51:53 +0100 Subject: [PATCH] Add verified private Support contact email in Account security (348) --- website/control-panel/public/panel.js | 15 +++- website/control-panel/server.mjs | 5 +- website/integrations/contact-email.php | 23 ++++++ .../integrations/osticket/authenticate.php | 2 +- .../osticket/contact-email-policy.php | 32 ++++++++ .../osticket/contact-email-schema.sql | 5 ++ .../osticket/tests/contact-email-test.php | 37 +++++++++ website/node/CONTACT-EMAIL-348.md | 60 ++++++++++++++ website/node/contact-email.mjs | 81 +++++++++++++++++++ website/tests/contact-email.test.mjs | 72 +++++++++++++++++ 10 files changed, 329 insertions(+), 3 deletions(-) create mode 100644 website/integrations/contact-email.php create mode 100644 website/integrations/osticket/contact-email-policy.php create mode 100644 website/integrations/osticket/contact-email-schema.sql create mode 100644 website/integrations/osticket/tests/contact-email-test.php create mode 100644 website/node/CONTACT-EMAIL-348.md create mode 100644 website/node/contact-email.mjs create mode 100644 website/tests/contact-email.test.mjs diff --git a/website/control-panel/public/panel.js b/website/control-panel/public/panel.js index b394ec6b..ca97fc72 100644 --- a/website/control-panel/public/panel.js +++ b/website/control-panel/public/panel.js @@ -10,6 +10,19 @@ function paintAccountHead(image,canvas,skin){ return true; } // End account head renderer. +async function contactEmailSettings(){ + let host=document.getElementById('contact-email-settings'); + if(!host){host=el('section');host.id='contact-email-settings';document.getElementById('password-form').after(host);} + const data=await api('account/email');host.replaceChildren(el('h3','Support notification email'),el('p','Add a private email address for ticket updates. Confirm ownership before it is used. This does not change your sign-in or public profile.')); + const status=el('p',data.email?'Verified contact: '+data.email:'No verified contact email. Read your updates on the Support website.');status.setAttribute('role','status');host.append(status); + const form=el('form'),label=el('label','Email address'),email=el('input');email.name='email';email.type='email';email.autocomplete='email';email.maxLength=254;email.required=true;email.value=data.pendingEmail||data.email||'';label.append(email); + const passwordLabel=el('label','Current website password'),password=el('input');password.name='currentPassword';password.type='password';password.autocomplete='current-password';password.maxLength=256;password.required=true;passwordLabel.append(password); + const send=el('button','Send verification email'),remove=el('button','Remove contact email');send.type=remove.type='submit';remove.formNoValidate=true;remove.hidden=!data.email&&!data.pendingEmail; + form.append(label,passwordLabel,send,remove);host.append(form); + form.onsubmit=event=>{event.preventDefault();const button=event.submitter||send;action(button,async()=>{const result=await api('account/email',{action:button===remove?'remove':'request',email:email.value,currentPassword:password.value});password.value='';await contactEmailSettings();notice(result.message);if(button!==remove)document.getElementById('contact-verification-code')?.focus();});}; + if(data.pendingEmail){const verify=el('form'),codeLabel=el('label','Verification code sent to '+data.pendingEmail),code=el('input');code.id='contact-verification-code';code.name='code';code.autocomplete='one-time-code';code.spellcheck=false;code.required=true;code.minLength=code.maxLength=36;codeLabel.append(code);const confirm=el('button','Confirm email');confirm.type='submit';verify.append(codeLabel,confirm);host.append(verify);verify.onsubmit=event=>{event.preventDefault();action(confirm,async()=>{const result=await api('account/email',{action:'confirm',code:code.value.trim()});await contactEmailSettings();notice(result.message);});};} + if(data.syncPending){const warning=el('p','Support notification sync is pending. Keep checking your tickets online until it succeeds.'),retry=el('button','Retry Support sync');retry.type='button';retry.onclick=()=>action(retry,async()=>{const result=await api('account/email',{action:'sync'});await contactEmailSettings();notice(result.message);});host.append(warning,retry);} +} let mode='login',session=null;const $=id=>document.getElementById(id),notice=message=>{$('notice').textContent=message;}; if(new URLSearchParams(location.search).get('embedded')==='1')document.body.classList.add('embedded'); async function api(path,body){const response=await fetch('/api/'+path,{method:body===undefined?'GET':'POST',headers:{'Content-Type':'application/json'},...(body===undefined?{}:{body:JSON.stringify(body)}),cache:'no-store'});const data=await response.json();if(!response.ok)throw Error(data.message||'Please try again later.');return data;} @@ -27,7 +40,7 @@ $('refresh-rewards').onclick=()=>action($('refresh-rewards'),rewards); $('password-form').onsubmit=event=>{event.preventDefault();action(event.target.querySelector('button'),async()=>{await api('auth/password',Object.fromEntries(new FormData(event.target)));event.target.reset();notice('Password changed. Other sessions have been signed out.');});}; async function campaigns(){const data=await api('community/campaigns');$('campaigns').replaceChildren();for(const row of data.campaigns){const card=el('article');card.className='reward';card.append(el('h3',row.month),el('p',new Intl.NumberFormat(undefined,{style:'currency',currency:'EUR'}).format(row.received_cents/100)+' / '+new Intl.NumberFormat(undefined,{style:'currency',currency:'EUR'}).format(row.target_cents/100)),el('p',row.reward_amount+' Dunemarks per UUID · '+(row.reached_at?'Goal reached':'Not reached')));$('campaigns').append(card);}} for(const [form,endpoint]of [['campaign-form','community/campaigns'],['total-form','community/verify-total']])$(form).onsubmit=event=>{event.preventDefault();action(event.target.querySelector('button'),async()=>{const data=Object.fromEntries(new FormData(event.target));for(const key of ['targetCents','rewardAmount','receivedCents'])if(key in data)data[key]=Number(data[key]);if(!confirm(endpoint.endsWith('verify-total')?'Confirm that this total is verified against payment records? Reaching the target unlocks rewards.':'Create this goal? The target and reward cannot be edited afterward.'))return;await api(endpoint,data);notice('Saved.');await campaigns();});}; -async function load(){const data=await api('auth/session');session=data.user;document.querySelector('.account-summary').textContent=data.authenticated?'Signed in as '+data.user.username+' · '+data.user.rankLabel:'Your dunerealms.com account';$('auth').hidden=data.authenticated;$('dashboard').hidden=!data.authenticated;$('logout').hidden=!data.authenticated;$('welcome').textContent=data.authenticated?'Welcome, '+data.user.username+'.':'Welcome, traveller.';window.dispatchEvent(new CustomEvent('dune:session',{detail:session}));if(data.authenticated){const returnTo=new URLSearchParams(location.search).get('return_to');if((returnTo?.startsWith('/sso/authorize?')||/^\/memorial-login\?slug=[a-z0-9-]{3,64}$/.test(returnTo||'')||/^\/profile-login\?username=[a-z0-9_]{3,32}$/.test(returnTo||''))&&!/[\\\\\r\n]/.test(returnTo)){location.replace(returnTo);return;}const has=node=>data.user.permissions.includes(node);$('staff').hidden=!has('web.menu.administration');$('staff-tab').hidden=!has('web.menu.administration');const work=[];if(has('web.menu.game'))work.push(linking());if(has('web.menu.rewards'))work.push(rewards());if(has('web.menu.servers'))work.push(serverControls());if(has('web.community.manage'))work.push(campaigns());if(has('web.accounts.view'))work.push(accounts());await Promise.allSettled(work);}} +async function load(){const data=await api('auth/session');session=data.user;document.querySelector('.account-summary').textContent=data.authenticated?'Signed in as '+data.user.username+' · '+data.user.rankLabel:'Your dunerealms.com account';$('auth').hidden=data.authenticated;$('dashboard').hidden=!data.authenticated;$('logout').hidden=!data.authenticated;$('welcome').textContent=data.authenticated?'Welcome, '+data.user.username+'.':'Welcome, traveller.';window.dispatchEvent(new CustomEvent('dune:session',{detail:session}));if(data.authenticated){const returnTo=new URLSearchParams(location.search).get('return_to');if((returnTo?.startsWith('/sso/authorize?')||/^\/memorial-login\?slug=[a-z0-9-]{3,64}$/.test(returnTo||'')||/^\/profile-login\?username=[a-z0-9_]{3,32}$/.test(returnTo||''))&&!/[\\\\\r\n]/.test(returnTo)){location.replace(returnTo);return;}const has=node=>data.user.permissions.includes(node);$('staff').hidden=!has('web.menu.administration');$('staff-tab').hidden=!has('web.menu.administration');const work=[contactEmailSettings()];if(has('web.menu.game'))work.push(linking());if(has('web.menu.rewards'))work.push(rewards());if(has('web.menu.servers'))work.push(serverControls());if(has('web.community.manage'))work.push(campaigns());if(has('web.accounts.view'))work.push(accounts());await Promise.allSettled(work);}} async function accounts(){ const [data,catalog]=await Promise.all([api('admin/accounts'),api('ranks').catch(()=>({ranks:[]}))]); const host=$('accounts');host.replaceChildren();host.className='account-admin'; diff --git a/website/control-panel/server.mjs b/website/control-panel/server.mjs index 171f20ee..a6e67f8d 100644 --- a/website/control-panel/server.mjs +++ b/website/control-panel/server.mjs @@ -1,3 +1,4 @@ +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'; @@ -51,6 +52,7 @@ const types={'.html':'text/html; charset=utf-8','.js':'text/javascript; charset= const sharedAssets=new Set(['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 origin=new URL(settings.CP_ORIGIN||'https://cp.dunerealms.com').origin; + const contactEmail=createContactEmail(db,{origin,...dependencies.contactEmail}); const auth=createAuth(db,origin,settings),links=createGameLink(db,settings,origin),rewards=createCommunityRewards(db,settings,origin); const mailIdentity=createMailIdentityRoute(db,{origin}),gitIdentity=createGitIdentityRoute(db,settings,origin); const admin=createAccountAdmin(db,origin),profile=createProfile(db,settings,origin),avatars=createAvatars(db,settings); @@ -83,6 +85,7 @@ export function createPanel(db,settings={},dependencies={}){ 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/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}); @@ -164,7 +167,7 @@ export async function startPanel(settings=process.env){ 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 db=await openDatabase(settings);await initializeBanEvidence(db);await initializeClans(db);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeBadges(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);const handle=createPanel(db,settings,{inventoryPool}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com'; + const db=await openDatabase(settings);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeBadges(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);const handle=createPanel(db,settings,{inventoryPool}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com'; const stopBanSync=startModerationSync(db,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://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{ diff --git a/website/integrations/contact-email.php b/website/integrations/contact-email.php new file mode 100644 index 00000000..73cd8c4d --- /dev/null +++ b/website/integrations/contact-email.php @@ -0,0 +1,23 @@ +4096)throw new RuntimeException();$a=json_decode($raw,true); + require_once '/home/dunerealms/apps/integrations/osticket/contact-email-policy.php'; + if(!is_array($a)||!in_array($a['action']??null,['verify','sync'],true)||!preg_match('/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/',$a['userId']??''))throw new RuntimeException(); + $email=dune_contact_address($a['email']??null); + if($a['action']==='verify'&&($email===null||!preg_match('/^[a-f0-9]{36}$/',$a['code']??'')))throw new RuntimeException(); + if($a['action']==='sync'&&(!is_int($a['version']??null)||$a['version']<0||!preg_match('/^[a-z0-9_]{3,32}$/',$a['username']??'')))throw new RuntimeException(); + require_once '/home/dunerealms/apps/integrations/osticket/main.inc.php'; + if($email!==null&&Email::lookup(['email'=>$email]))throw new RuntimeException('System mailbox cannot be a personal contact'); + if($a['action']==='verify'){ + $existing=User::lookupByEmail($email);$own=User::lookupByEmail($a['userId'].'@accounts.dunerealms.invalid'); + if($existing&&(!$own||$existing->getId()!==$own->getId()))throw new RuntimeException(); + $mailer=$cfg->getDefaultEmail();if(!$mailer||!$mailer->send($email,'Confirm your DuneRealms contact email',"You requested Support ticket notifications at this email address.\n\nPaste this verification code in Account centre > Account security within 15 minutes:\n\n".$a['code']."\n\nhttps://cp.dunerealms.com/#security\n\nIf you did not request this, ignore this message. Your account has not changed.",null,['text'=>true]))throw new RuntimeException(); + }else{ + $alias=$a['userId'].'@accounts.dunerealms.invalid';$user=User::lookupByEmail($alias)?:User::fromVars(['name'=>$a['username'],'email'=>$alias]);if(!$user)throw new RuntimeException(); + $c=json_decode(file_get_contents('/home/dunerealms/.config/integrations.json'),true);$db=new PDO('mysql:host='.$c['host'].';dbname='.$c['database'].';charset=utf8mb4',$c['username'],$c['password'],[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]); + dune_contact_sync($db,$a['userId'],$email,$a['version']); + } + echo json_encode(['ok'=>true]); +}catch(Throwable $e){echo json_encode(['ok'=>false]);exit(1);} diff --git a/website/integrations/osticket/authenticate.php b/website/integrations/osticket/authenticate.php index 48c436ff..133fe101 100644 --- a/website/integrations/osticket/authenticate.php +++ b/website/integrations/osticket/authenticate.php @@ -17,7 +17,7 @@ class DuneClientAuthentication extends ExternalUserAuthenticationBackend { if(!$user->getAccount()){$account=ClientAccount::createForUser($user,['username'=>str_replace('-','',$identity['id']),'backend'=>static::$id]);if(!$account->confirm())return null;} return new ClientSession(new EndUser($user)); } - protected function validate($userid){$identity=dune_ticket_identity();if(!$identity)return false;$user=User::lookup($userid);if(!$user||!$user->getEmail()||strtolower($user->getEmail())!==strtolower($identity['id'].'@accounts.dunerealms.invalid'))return false;return parent::validate($userid);} + protected function validate($userid){$identity=dune_ticket_identity();if(!$identity)return false;$user=User::lookup($userid);if(!$user||!($mapped=User::lookupByEmail($identity['id'].'@accounts.dunerealms.invalid'))||$mapped->getId()!==$user->getId())return false;return parent::validate($userid);} function supportsInteractiveAuthentication(){return false;} } class DuneStaffAuthentication extends StaffAuthenticationBackend { diff --git a/website/integrations/osticket/contact-email-policy.php b/website/integrations/osticket/contact-email-policy.php new file mode 100644 index 00000000..19fa04df --- /dev/null +++ b/website/integrations/osticket/contact-email-policy.php @@ -0,0 +1,32 @@ +254||preg_match('/[\r\n\x00]/',$value)||!filter_var($value,FILTER_VALIDATE_EMAIL)||str_ends_with(strtolower($value),'.invalid'))throw new RuntimeException('Invalid contact address'); + return strtolower($value); +} +function dune_contact_sync(PDO $db,string $websiteId,?string $address,int $version):void { + if(!preg_match('/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/',$websiteId)||$version<0)throw new RuntimeException('Invalid account'); + $address=dune_contact_address($address);$alias=$websiteId.'@accounts.dunerealms.invalid'; + $mysql=$db->getAttribute(PDO::ATTR_DRIVER_NAME)==='mysql'; + $db->beginTransaction();try{ + $q=$db->prepare($mysql?'INSERT IGNORE INTO dune_contact_projection(website_id,version) VALUES(?,-1)':'INSERT OR IGNORE INTO dune_contact_projection(website_id,version) VALUES(?,-1)');$q->execute([$websiteId]); + $q=$db->prepare('SELECT * FROM dune_contact_projection WHERE website_id=?'.($mysql?' FOR UPDATE':''));$q->execute([$websiteId]);$previous=$q->fetch(PDO::FETCH_ASSOC); + if((int)$previous['version']>$version){$db->commit();return;} + if((int)$previous['version']===$version&&$previous['address']!==$address)throw new RuntimeException('Conflicting contact revision'); + $q=$db->prepare('SELECT id,user_id FROM drsupport_user_email WHERE address=?');$q->execute([$alias]);$identity=$q->fetch(PDO::FETCH_ASSOC); + if(!$identity)throw new RuntimeException('Support account is not provisioned'); + $targetId=(int)$identity['id']; + if($address!==null){ + $q=$db->prepare('SELECT id,user_id FROM drsupport_user_email WHERE address=?');$q->execute([$address]);$target=$q->fetch(PDO::FETCH_ASSOC); + if($target&&(int)$target['user_id']!==(int)$identity['user_id'])throw new RuntimeException('Contact address unavailable'); + if(!$target){$q=$db->prepare('INSERT INTO drsupport_user_email(user_id,address) VALUES(?,?)');$q->execute([$identity['user_id'],$address]);$targetId=(int)$db->lastInsertId();}else $targetId=(int)$target['id']; + } + $q=$db->prepare('UPDATE drsupport_user SET default_email_id=? WHERE id=?');$q->execute([$targetId,$identity['user_id']]); + // Remove only the former address created by this feature. Never touch aliases, + // other identities, ticket rows, threads, paid receipts or audit history. + if($previous['address']!==null&&$previous['address']!==$address){$q=$db->prepare('DELETE FROM drsupport_user_email WHERE user_id=? AND address=? AND id<>?');$q->execute([$identity['user_id'],$previous['address'],$identity['id']]);} + $q=$db->prepare('UPDATE dune_contact_projection SET address=?,version=? WHERE website_id=?');$q->execute([$address,$version,$websiteId]); + $db->commit(); + }catch(Throwable $e){if($db->inTransaction())$db->rollBack();throw $e;} +} diff --git a/website/integrations/osticket/contact-email-schema.sql b/website/integrations/osticket/contact-email-schema.sql new file mode 100644 index 00000000..00a12ccd --- /dev/null +++ b/website/integrations/osticket/contact-email-schema.sql @@ -0,0 +1,5 @@ +CREATE TABLE IF NOT EXISTS dune_contact_projection ( + website_id CHAR(36) PRIMARY KEY, + address VARCHAR(254), + version BIGINT NOT NULL DEFAULT -1 +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; diff --git a/website/integrations/osticket/tests/contact-email-test.php b/website/integrations/osticket/tests/contact-email-test.php new file mode 100644 index 00000000..c1fce1cc --- /dev/null +++ b/website/integrations/osticket/tests/contact-email-test.php @@ -0,0 +1,37 @@ +PDO::ERRMODE_EXCEPTION]);$prefix='CREATE TEMPORARY TABLE ';$auto='INTEGER PRIMARY KEY AUTO_INCREMENT';$engine=' ENGINE=InnoDB'; +}else{$db=new PDO('sqlite::memory:',null,null,[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);$prefix='CREATE TABLE ';$auto='INTEGER PRIMARY KEY AUTOINCREMENT';$engine='';} +// Same names deliberately shadow real tables on this private MySQL connection. +$db->exec($prefix.'drsupport_user (id INTEGER PRIMARY KEY,default_email_id INTEGER)'.$engine); +$db->exec($prefix.'drsupport_user_email (id '.$auto.',user_id INTEGER,address VARCHAR(254) UNIQUE)'.$engine); +$db->exec($prefix.'dune_contact_projection (website_id VARCHAR(36) PRIMARY KEY,address VARCHAR(254),version INTEGER NOT NULL DEFAULT -1)'.$engine); +$a='11111111-1111-4111-8111-111111111111';$b='22222222-2222-4222-8222-222222222222'; +$db->prepare('INSERT INTO drsupport_user_email(id,user_id,address) VALUES(1,1,?),(2,2,?),(3,2,?)')->execute([$a.'@accounts.dunerealms.invalid',$b.'@accounts.dunerealms.invalid','other@example.org']); +$db->exec('INSERT INTO drsupport_user VALUES(1,1),(2,2)'); +$value=fn($sql)=>$db->query($sql)->fetchColumn(); +check(dune_contact_address('TRAVELLER@example.org')==='traveller@example.org','Normalization'); +foreach(["a\r\nBcc:b@example.org",'a@accounts.dunerealms.invalid','broken']as$bad){try{dune_contact_address($bad);check(false,'Invalid address accepted');}catch(RuntimeException $e){$count++;}} +dune_contact_sync($db,$a,'first@example.org',2); +check($value('SELECT default_email_id FROM drsupport_user WHERE id=1')!=1,'Notification default switched'); +check($value("SELECT user_id FROM drsupport_user_email WHERE id=1")==1,'Identity alias retained'); +$default=$value('SELECT default_email_id FROM drsupport_user WHERE id=1'); +dune_contact_sync($db,$a,'first@example.org',2);check($value('SELECT default_email_id FROM drsupport_user WHERE id=1')==$default,'Replay idempotent'); +dune_contact_sync($db,$a,null,1);check($value('SELECT default_email_id FROM drsupport_user WHERE id=1')==$default,'Stale removal ignored'); +try{dune_contact_sync($db,$a,'conflict@example.org',2);check(false,'Conflicting revision accepted');}catch(RuntimeException $e){$count++;} +try{dune_contact_sync($db,$a,'other@example.org',3);check(false,'Other account contact accepted');}catch(RuntimeException $e){$count++;} +check($value('SELECT default_email_id FROM drsupport_user WHERE id=1')==$default,'Duplicate rejection rolls back default'); +check($value("SELECT version FROM dune_contact_projection WHERE website_id='$a'")==2,'Duplicate rejection rolls back revision'); +check($value('SELECT default_email_id FROM drsupport_user WHERE id=2')==2,'Other identity unchanged'); +dune_contact_sync($db,$a,'second@example.org',4); +check($value("SELECT COUNT(*) FROM drsupport_user_email WHERE address='first@example.org'")==0,'Old projected address no longer identifies account'); +check($value('SELECT COUNT(*) FROM drsupport_user_email WHERE user_id=1')==2,'Only alias and current contact remain'); +dune_contact_sync($db,$a,null,5); +check($value('SELECT default_email_id FROM drsupport_user WHERE id=1')==1,'Removal restores technical alias'); +check($value('SELECT COUNT(*) FROM drsupport_user_email WHERE user_id=1')==1,'Removal detaches former contact'); +check($value("SELECT COUNT(*) FROM drsupport_user_email WHERE address='other@example.org'")==1,'Unrelated email retained'); +try{dune_contact_sync($db,'33333333-3333-4333-8333-333333333333','missing@example.org',1);check(false,'Missing identity accepted');}catch(RuntimeException $e){$count++;} +check($value("SELECT COUNT(*) FROM dune_contact_projection WHERE website_id='33333333-3333-4333-8333-333333333333'")==0,'Missing identity rolls back projection'); +echo $count.' '.(($argv[2]??'')==='mysql'?'temporary MySQL':'SQLite').' contact projection checks passed; no live identity changed.'.PHP_EOL; diff --git a/website/node/CONTACT-EMAIL-348.md b/website/node/CONTACT-EMAIL-348.md new file mode 100644 index 00000000..be2b5a13 --- /dev/null +++ b/website/node/CONTACT-EMAIL-348.md @@ -0,0 +1,60 @@ +# Ticket 348: private Support notification email + +Account centre → Your Account Portal → Security now includes the contact email +form beneath the password form. Website password confirmation is required to +request or remove an address. The emailed 144-bit code expires after 15 minutes, +is stored only as SHA-256, and can be used once by the signed-in requesting +account. Five failed code attempts invalidate it. Resends are limited by a +persistent cooldown/hourly budget; password and sync attempts are also bounded. +Changing an address preserves the verified former contact until confirmation. + +`/api/account/email` is authenticated, same-origin for mutations and no-store. +It never appears in public profiles, public SSO profile data or account rank +information. Native Support uses its configured outgoing email transport. +Verification messages contain only the code, expiry and account centre link. +System sender addresses, internal `.invalid` identities and email addresses +belonging to a different native user are rejected rather than merging users. + +The Node table is initialized at CP startup. Install +`integrations/osticket/contact-email-schema.sql` in the integrations database +before enabling the helper. Deploy `integrations/contact-email.php` as +`/home/dunerealms/apps/integrations/contact-email.php` and its policy file in +the existing native Support directory. Communication is local stdin/stdout, +bounded by size and timeout; no password or verification code in command-line +arguments or logs. Native `authenticate.php` remains UUID-alias based: compare +the resolved user ID, not the mutable notification address. + +Projection updates are transactional and revision ordered. The immutable +`UUID@accounts.dunerealms.invalid` alias stays attached to the same native UID. +Only the managed contact email becomes that user's notification default. A +previous managed email is detached on change/removal; unrelated addresses, +ticket ownership, threads, attachments, receipts and staff access are untouched. +Native failure leaves an explicit pending status and Retry Support sync button; +it is not reported as successful notification activation. Removal restores the +technical alias, so users must read tickets online until adding another contact. + +## Verification and rollout, 5 November 2026 + +- 14 Node tests passed: confirmation lifecycle, password/origin/authentication, + resend limits across handlers, attempts, expiry/replay/supersession, concurrent + confirmation, mail failure, native retry, removal and public profile regression. +- 20 SQLite and 20 temporary InnoDB checks passed against the actual projection + policy; MySQL tables shadow live names only on the test connection. Includes + collision rollback, stale/replayed revisions, removal and identity isolation. +- Actual native TicketOwner/EndUser/User objects in memory select the changed + default email while the saved UUID alias stays unchanged. No live user changed. +- Native sender has configured active SMTP. This is configuration evidence, + not proof of inbox delivery; no real user's email was set or mailed in testing. +- 8 live HTTP checks passed: private route authentication, initial private state, + origin/password/format/invalid-code gates, unchanged contact and native Dev SSO. + SSO needed its normal warmup route before opening a deep ticket link. +- Live browser: form beside password controls, semantic labels, browser email + validation, visible incorrect-password feedback and no horizontal overflow. +- Backups: `/root/ticket348-before-20261105`. Only CP restarted. Additive empty + tables plus six scoped runtime files installed; no game, payment or rank change. + +Rollback the six files from the preserved baseline and restart only the CP. +If users have subsequently verified addresses, restore their native defaults to +the retained UUID aliases through the current revisioned sync before removing +the feature. Retain contact/projection tables privately for reconciliation; +do not drop them or delete user/ticket/history records as a rollback shortcut. diff --git a/website/node/contact-email.mjs b/website/node/contact-email.mjs new file mode 100644 index 00000000..3e23bbac --- /dev/null +++ b/website/node/contact-email.mjs @@ -0,0 +1,81 @@ +import {createHash,randomBytes,scrypt as rawScrypt,timingSafeEqual} from 'node:crypto'; +import {promisify} from 'node:util'; +import {spawn} from 'node:child_process'; +import {identity} from './auth.mjs'; +import {json} from './game-link.mjs'; +const scrypt=promisify(rawScrypt),hash=s=>createHash('sha256').update(s).digest('hex'); +export const contactSchema=`CREATE TABLE IF NOT EXISTS site_contact_emails ( + user_id CHAR(36) PRIMARY KEY,address VARCHAR(254),verified_at BIGINT, + pending_address VARCHAR(254),code_hash CHAR(64),expires_at BIGINT,attempts INTEGER NOT NULL DEFAULT 0, + requested_at BIGINT NOT NULL DEFAULT 0,window_started_at BIGINT NOT NULL DEFAULT 0,send_count INTEGER NOT NULL DEFAULT 0, + version INTEGER NOT NULL DEFAULT 0,sync_pending INTEGER NOT NULL DEFAULT 0 +)`; +export async function initializeContactEmails(db){await db.prepare(contactSchema).run();} +export function normalizeContactEmail(value){ + if(typeof value!=='string')throw Error('Enter a valid email address.'); + const address=value.trim().toLowerCase(); + // A deliberately conservative mailbox format; never accept headers or internal aliases. + if(address.length>254||!address.match(/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/)||address.split('@')[0].length>64||address.endsWith('.invalid'))throw Error('Enter a valid email address.'); + return address; +} +export function contactBroker(payload){return new Promise((resolve,reject)=>{ + const p=spawn('/usr/bin/php',['/home/dunerealms/apps/integrations/contact-email.php'],{stdio:['pipe','pipe','ignore']});let output='',done=false; + const fail=()=>{if(done)return;done=true;clearTimeout(timer);p.kill();reject(Error('Contact email service unavailable.'));}; + const timer=setTimeout(fail,20000);p.on('error',fail);p.stdin.on('error',fail);p.stdout.on('data',b=>{output+=b;if(output.length>1024)fail();}); + p.on('close',code=>{if(done)return;done=true;clearTimeout(timer);try{const result=JSON.parse(output);if(code||result.ok!==true)throw Error();resolve(result);}catch{reject(Error('Contact email service unavailable.'));}});p.stdin.end(JSON.stringify(payload)); +});} +export function createContactEmail(db,{origin='https://cp.dunerealms.com',broker=contactBroker,now=Date.now,makeCode=()=>randomBytes(18).toString('hex')}={}){ + const passwordAttempts=new Map(); + return async request=>{ + const user=await identity(request,db);if(!user)return json({message:'Sign in first.'},401); + if(request.method==='GET'){ + const row=await db.prepare('SELECT * FROM site_contact_emails WHERE user_id=?').bind(user.id).first(); + return json({email:row?.address||null,verified:!!row?.verified_at,pendingEmail:row?.expires_at>now()?row.pending_address:null,syncPending:!!row?.sync_pending}); + } + if(request.method!=='POST')return json({message:'Method not allowed.'},405); + if(request.headers.get('origin')!==origin)return json({message:'Origin rejected.'},403); + let body;try{body=await request.json();}catch{return json({message:'Invalid request.'},400);} + if(!body||!['request','confirm','remove','sync'].includes(body.action))return json({message:'Invalid request.'},400); + if(['request','remove'].includes(body.action)){ + const time=now();if(passwordAttempts.size>5000)for(const [id,r]of passwordAttempts)if(r.until5000||++limit.count>5)return json({message:'Too many attempts. Try again in 15 minutes.'},429); + if(typeof body.currentPassword!=='string'||body.currentPassword.length>256)return json({message:'Enter your current website password.'},400); + const account=await db.prepare('SELECT password_salt,password_hash FROM site_accounts WHERE id=?').bind(user.id).first(); + const actual=await scrypt(body.currentPassword,account.password_salt,64); + if(!/^[a-f0-9]{128}$/i.test(account.password_hash)||!timingSafeEqual(actual,Buffer.from(account.password_hash,'hex')))return json({message:'Incorrect current password.'},403); + } + await db.prepare('INSERT INTO site_contact_emails(user_id) VALUES(?) ON CONFLICT(user_id) DO UPDATE SET user_id=excluded.user_id').bind(user.id).run(); + const row=await db.prepare('SELECT * FROM site_contact_emails WHERE user_id=?').bind(user.id).first(),time=now(); + if(body.action==='sync'){ + if(!row.sync_pending)return json({message:'Support notification settings are up to date.',syncPending:false}); + const key=user.id+':sync';let limit=passwordAttempts.get(key);if(!limit||limit.until3)return json({message:'Please wait a minute before retrying Support sync.'},429); + } + if(body.action==='request'){ + let address;try{address=normalizeContactEmail(body.email);}catch(e){return json({message:e.message},400);} + if(address===row.address&&!row.sync_pending)return json({message:'This email is already verified.'}); + if(time-row.requested_at<60000||time-row.window_started_at<3600000&&row.send_count>=5)return json({message:'Please wait before requesting another verification email.'},429); + const code=makeCode(),version=row.version+1,windowStart=time-row.window_started_at>=3600000?time:row.window_started_at,count=windowStart===time?1:row.send_count+1; + const updated=await db.prepare('UPDATE site_contact_emails SET pending_address=?,code_hash=?,expires_at=?,attempts=0,requested_at=?,window_started_at=?,send_count=?,version=? WHERE user_id=? AND version=?').bind(address,hash(code),time+900000,time,windowStart,count,version,user.id,row.version).run(); + if(!updated.meta.changes)return json({message:'Email settings changed. Refresh and retry.'},409); + try{await broker({action:'verify',userId:user.id,email:address,code});} + catch{await db.prepare('UPDATE site_contact_emails SET code_hash=NULL,pending_address=NULL,expires_at=NULL WHERE user_id=? AND version=?').bind(user.id,version).run();return json({message:'Verification email could not be sent. Your existing contact address is unchanged. Try again later.'},503);} + return json({message:'Verification email sent. Paste its code below within 15 minutes.'}); + } + if(body.action==='confirm'){ + if(!/^[a-f0-9]{36}$/.test(body.code||'')||!row.code_hash||row.expires_at<=time||row.attempts>=5)return json({message:'Invalid or expired code. Request a new verification email.'},400); + if(!timingSafeEqual(Buffer.from(hash(body.code)),Buffer.from(row.code_hash))){await db.prepare('UPDATE site_contact_emails SET attempts=attempts+1 WHERE user_id=? AND version=? AND code_hash=?').bind(user.id,row.version,row.code_hash).run();return json({message:'Invalid or expired code.'},400);} + const saved=await db.prepare('UPDATE site_contact_emails SET address=pending_address,verified_at=?,pending_address=NULL,code_hash=NULL,expires_at=NULL,version=version+1,sync_pending=1 WHERE user_id=? AND version=? AND code_hash=? AND attempts<5 AND expires_at>?').bind(time,user.id,row.version,row.code_hash,time).run(); + if(!saved.meta.changes)return json({message:'This verification is no longer current. Refresh and retry.'},409); + }else if(body.action==='remove'){ + const saved=await db.prepare('UPDATE site_contact_emails SET address=NULL,verified_at=NULL,pending_address=NULL,code_hash=NULL,expires_at=NULL,version=version+1,sync_pending=1 WHERE user_id=? AND version=?').bind(user.id,row.version).run(); + if(!saved.meta.changes)return json({message:'Email settings changed. Refresh and retry.'},409); + } + const current=await db.prepare('SELECT * FROM site_contact_emails WHERE user_id=?').bind(user.id).first(); + try{await broker({action:'sync',userId:user.id,username:user.username,email:current.address,version:current.version});await db.prepare('UPDATE site_contact_emails SET sync_pending=0 WHERE user_id=? AND version=?').bind(user.id,current.version).run();} + catch{return json({message:'Saved, but Support could not update its notification address. Use Retry Support sync before relying on email notifications.',syncPending:true},202);} + return json({message:current.address?'Email verified. Support ticket notifications will use this address.':'Contact email removed. Read ticket updates on the Support website.',syncPending:false}); + }; +} + diff --git a/website/tests/contact-email.test.mjs b/website/tests/contact-email.test.mjs new file mode 100644 index 00000000..2e9405d7 --- /dev/null +++ b/website/tests/contact-email.test.mjs @@ -0,0 +1,72 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {createHash,scryptSync} from 'node:crypto'; +import {readFileSync} from 'node:fs'; +import {LocalD1} from './d1-adapter.mjs'; +import {contactSchema,createContactEmail,normalizeContactEmail} from '../node/contact-email.mjs'; +const origin='https://cp.dunerealms.com',userId='11111111-1111-4111-8111-111111111111',token='x'.repeat(43),password='A private testing password',salt='a'.repeat(32); +function fixture(){ + const db=new LocalD1(`CREATE TABLE site_accounts(id TEXT,username TEXT,display_name TEXT,role TEXT,password_salt TEXT,password_hash TEXT);CREATE TABLE site_sessions(token_hash TEXT,user_id TEXT,expires_at INTEGER);CREATE TABLE cp_account_ranks(user_id TEXT,rank_key TEXT);${contactSchema}`); + db.sqlite.prepare('INSERT INTO site_accounts VALUES(?,?,?,?,?,?)').run(userId,'traveller','Traveller','user',salt,scryptSync(password,salt,64).toString('hex')); + db.sqlite.prepare('INSERT INTO site_sessions VALUES(?,?,?)').run(createHash('sha256').update(token).digest('hex'),userId,Date.now()+3600000); + const calls=[],state={time:Date.now(),code:'a'.repeat(36),fail:null}; + const app=createContactEmail(db,{now:()=>state.time,makeCode:()=>state.code,broker:async b=>{calls.push(b);if(b.action===state.fail)throw Error('Transport unavailable');return{ok:true};}}); + const req=(body,headers={})=>app(new Request(origin+'/api/account/email',{method:body===undefined?'GET':'POST',headers:{Cookie:'__Host-dune_session='+token,Origin:origin,'Content-Type':'application/json',...headers},...(body===undefined?{}:{body:JSON.stringify(body)})})); + return{db,calls,state,req,request:email=>req({action:'request',email,currentPassword:password}),confirm:()=>req({action:'confirm',code:state.code})}; +} +test('email parsing rejects header injection, internal aliases and malformed addresses',()=>{ + assert.equal(normalizeContactEmail(' Traveller@Example.COM '),'traveller@example.com'); + for(const email of ['x\r\nBcc: y@example.com','a@accounts.dunerealms.invalid','a@localhost','a..b@example.org','a@example..org','','a'.repeat(65)+'@example.com',null,{},'x@-example.com'])assert.throws(()=>normalizeContactEmail(email)); +}); +test('requires an authenticated account, correct origin and current password',async()=>{ + const f=fixture();try{ + assert.equal((await f.req(undefined,{Cookie:''})).status,401); + assert.equal((await f.req({action:'request',email:'a@example.org',currentPassword:password},{Origin:'https://evil.example'})).status,403); + assert.equal((await f.req({action:'request',email:'a@example.org',currentPassword:'wrong'})).status,403); + assert.equal(f.calls.length,0); + }finally{f.db.close();} +}); +test('confirmation alone activates notification email; raw code is not stored or returned',async()=>{ + const f=fixture();try{ + const response=await f.request('traveller@example.org');assert.equal(response.status,200);assert(!(await response.text()).includes(f.state.code)); + let row=await f.db.prepare('SELECT * FROM site_contact_emails').first();assert.equal(row.address,null);assert.notEqual(row.code_hash,f.state.code);assert.equal(f.calls[0].action,'verify'); + assert.equal((await f.confirm()).status,200);row=await f.db.prepare('SELECT * FROM site_contact_emails').first();assert.equal(row.address,'traveller@example.org');assert.equal(row.code_hash,null);assert.equal(row.sync_pending,0); + assert.deepEqual(f.calls[1],{action:'sync',userId,username:'traveller',email:'traveller@example.org',version:2}); + assert.equal((await f.confirm()).status,400); + }finally{f.db.close();} +}); +test('wrong-code attempts are bounded even when the sixth attempt uses the correct code',async()=>{ + const f=fixture();try{await f.request('traveller@example.org');for(let i=0;i<5;i++)assert.equal((await f.req({action:'confirm',code:'b'.repeat(36)})).status,400);assert.equal((await f.confirm()).status,400);assert.equal(f.calls.length,1);}finally{f.db.close();} +}); +test('expired and superseded codes cannot activate an address',async()=>{ + const f=fixture();try{await f.request('first@example.org');f.state.time+=900001;assert.equal((await f.confirm()).status,400);f.state.code='b'.repeat(36);await f.request('second@example.org');assert.equal((await f.req({action:'confirm',code:'a'.repeat(36)})).status,400);assert.equal((await f.confirm()).status,200);assert.equal((await(await f.req()).json()).email,'second@example.org');}finally{f.db.close();} +}); +test('resend cooldown and persistent hourly budget apply across handler instances',async()=>{ + const f=fixture();try{ + await f.request('first@example.org');assert.equal((await f.request('other@example.org')).status,429); + async function requestFresh(){const app=createContactEmail(f.db,{now:()=>f.state.time,broker:async()=>({ok:true})});return app(new Request(origin+'/api/account/email',{method:'POST',headers:{Cookie:'__Host-dune_session='+token,Origin:origin,'Content-Type':'application/json'},body:JSON.stringify({action:'request',email:'first@example.org',currentPassword:password})}));} + for(let i=0;i<4;i++){f.state.time+=60001;assert.equal((await requestFresh()).status,200);} + f.state.time+=60001;assert.equal((await requestFresh()).status,429); + }finally{f.db.close();} +});test('mail failure invalidates pending code and preserves the former verified address',async()=>{ + const f=fixture();try{await f.request('first@example.org');await f.confirm();f.state.time+=60001;f.state.fail='verify';f.state.code='c'.repeat(36);assert.equal((await f.request('other@example.org')).status,503);assert.equal((await f.confirm()).status,400);assert.equal((await(await f.req()).json()).email,'first@example.org');}finally{f.db.close();} +}); +test('native sync failure is honest and retryable without reusing the verification code',async()=>{ + const f=fixture();try{await f.request('first@example.org');f.state.fail='sync';assert.equal((await f.confirm()).status,202);assert.equal((await(await f.req()).json()).syncPending,true);assert.equal((await f.confirm()).status,400);f.state.fail=null;assert.equal((await f.req({action:'sync'})).status,200);assert.equal((await(await f.req()).json()).syncPending,false);}finally{f.db.close();} +}); +test('remove is password-protected, clears pending verification and restores native alias',async()=>{ + const f=fixture();try{await f.request('first@example.org');await f.confirm();assert.equal((await f.req({action:'remove',currentPassword:'wrong'})).status,403);assert.equal((await f.req({action:'remove',currentPassword:password})).status,200);const state=await(await f.req()).json();assert.equal(state.email,null);assert.equal(state.verified,false);assert.equal(f.calls.at(-1).email,null);}finally{f.db.close();} +}); +test('concurrent confirmation grants at most one current revision',async()=>{ + const f=fixture();try{await f.request('first@example.org');const responses=await Promise.all([f.confirm(),f.confirm()]);assert.equal(responses.filter(r=>r.status===200).length,1);assert.equal(f.calls.filter(b=>b.action==='sync').length,1);}finally{f.db.close();} +}); +test('memorial and disabled identities cannot manage contact email',async()=>{ + const f=fixture();try{await f.db.prepare("UPDATE site_accounts SET role='memorial'").run();assert.equal((await f.req()).status,401);await f.db.prepare("UPDATE site_accounts SET role='user',password_hash='!disabled'").run();assert.equal((await f.req()).status,401);}finally{f.db.close();} +}); +test('public profile has no contact address; CP and native identity integrations are explicit',()=>{ + const profile=readFileSync(new URL('../node/profile.mjs',import.meta.url),'utf8');assert(!profile.includes('site_contact_emails')); + const server=readFileSync(new URL('../control-panel/server.mjs',import.meta.url),'utf8');assert(server.includes("if(path==='/api/account/email')return contactEmail(request)"));assert(server.includes('await initializeContactEmails(db)')); + const ui=readFileSync(new URL('../control-panel/public/panel.js',import.meta.url),'utf8');assert(ui.includes('const work=[contactEmailSettings()]'));assert(ui.includes("document.getElementById('password-form').after(host)")); + const auth=readFileSync(new URL('../integrations/osticket/authenticate.php',import.meta.url),'utf8');assert(auth.includes("$mapped=User::lookupByEmail($identity['id'].'@accounts.dunerealms.invalid')"));assert(auth.includes('$mapped->getId()!==$user->getId()')); +}); +