From e3a15fb2ae2c70cbcd935065fa9746e2b4b14f9d Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:55:54 +0100 Subject: [PATCH 1/4] Honor no-reply onboarding override and automatically download new admin account credentials --- .../control-panel/public/admin-registration.mjs | 2 +- website/node/first-login.mjs | 2 +- website/tests/first-login-override.test.mjs | 15 +++++++++++++++ 3 files changed, 17 insertions(+), 2 deletions(-) create mode 100644 website/tests/first-login-override.test.mjs diff --git a/website/control-panel/public/admin-registration.mjs b/website/control-panel/public/admin-registration.mjs index dc970950..83fb0531 100644 --- a/website/control-panel/public/admin-registration.mjs +++ b/website/control-panel/public/admin-registration.mjs @@ -1,6 +1,6 @@ const host=()=>document.getElementById('user-management'); const el=(tag,text)=>{const n=document.createElement(tag);if(text)n.textContent=text;return n;}; -async function mount(){const root=host();if(!root||document.getElementById('admin-registration-tab')||root.dataset.registrationMount)return;root.dataset.registrationMount='loading';const session=await fetch('/api/auth/session',{cache:'no-store'}).then(r=>r.json()).catch(()=>null);if(!session?.user?.ranks?.some(r=>['owners','official_account','web_net_admin','network_admin'].includes(r)))return;const response=await fetch('/api/admin/register-user',{cache:'no-store'});if(!response.ok)return;const data=await response.json();const tab=el('button','Register a user');tab.id='admin-registration-tab';tab.type='button';tab.setAttribute('aria-expanded','false');const panel=el('section');panel.hidden=true;panel.className='rank-create-panel admin-register-panel';panel.append(el('h3','Register a user'));const form=el('form');const field=(label,type,name)=>{const wrap=el('label',label),input=el('input');input.name=name;input.type=type;input.required=true;wrap.append(input);form.append(wrap);return input;};const username=field('Username','text','username');username.pattern='[A-Za-z0-9_]{3,32}';username.maxLength=32;const email=field('Email address · use no_reply if unavailable','text','email');email.maxLength=254;const rankSet=el('fieldset');rankSet.append(el('legend','Website ranks'));for(const rank of data.ranks){const label=el('label'),box=el('input');box.type='checkbox';box.name='rank';box.value=rank.key;box.checked=rank.key==='user';label.append(box,document.createTextNode(rank.label));rankSet.append(label);}form.append(rankSet);const ageWrap=el('label','Declared age group'),age=el('select');age.name='ageBand';age.required=true;for(const[value,label]of [['','Choose the age group declared by the user'],['15plus','15 or older'],['under15','Under 15']]){const option=el('option',label);option.value=value;age.append(option);}ageWrap.append(age);form.append(ageWrap);form.append(el('p','The user must change the temporary password, verify their own email and personally accept the terms at first sign-in.'));const submit=el('button','Create account');submit.type='submit';const status=el('p');status.setAttribute('role','status');const output=el('textarea');output.readOnly=true;output.rows=8;output.hidden=true;output.setAttribute('aria-label','New account credentials');const copy=el('button','Copy account details'),download=el('button','Download text file');copy.type=download.type='button';copy.hidden=download.hidden=true;copy.onclick=async()=>{await navigator.clipboard.writeText(output.value);status.textContent='Account details copied.';};download.onclick=()=>{const url=URL.createObjectURL(new Blob([output.value],{type:'text/plain;charset=utf-8'}));const link=el('a');link.href=url;link.download='DuneRealms-'+username.value.trim()+'.txt';link.click();URL.revokeObjectURL(url);};form.append(submit);panel.append(form,status,output,copy,download);const heading=root.querySelector(':scope>h2');if(heading)heading.after(tab,panel);else root.prepend(tab,panel);tab.onclick=()=>{panel.hidden=!panel.hidden;tab.setAttribute('aria-expanded',String(!panel.hidden));};form.onsubmit=async event=>{event.preventDefault();submit.disabled=true;status.textContent='Creating account…';try{const r=await fetch('/api/admin/register-user',{method:'POST',headers:{'Content-Type':'application/json'},cache:'no-store',body:JSON.stringify({username:username.value,email:email.value.trim(),ageBand:age.value,ranks:[...rankSet.querySelectorAll('input:checked')].map(i=>i.value)})});const result=await r.json();if(!r.ok)throw Error(result.message);output.value=result.credentials;output.hidden=copy.hidden=download.hidden=false;form.hidden=true;status.textContent='Account created. Copy or download these temporary credentials now; they will not be shown again.';output.focus();}catch(e){status.textContent=e.message;submit.disabled=false;}};} +async function mount(){const root=host();if(!root||document.getElementById('admin-registration-tab')||root.dataset.registrationMount)return;root.dataset.registrationMount='loading';const session=await fetch('/api/auth/session',{cache:'no-store'}).then(r=>r.json()).catch(()=>null);if(!session?.user?.ranks?.some(r=>['owners','official_account','web_net_admin','network_admin'].includes(r)))return;const response=await fetch('/api/admin/register-user',{cache:'no-store'});if(!response.ok)return;const data=await response.json();const tab=el('button','Register a user');tab.id='admin-registration-tab';tab.type='button';tab.setAttribute('aria-expanded','false');const panel=el('section');panel.hidden=true;panel.className='rank-create-panel admin-register-panel';panel.append(el('h3','Register a user'));const form=el('form');const field=(label,type,name)=>{const wrap=el('label',label),input=el('input');input.name=name;input.type=type;input.required=true;wrap.append(input);form.append(wrap);return input;};const username=field('Username','text','username');username.pattern='[A-Za-z0-9_]{3,32}';username.maxLength=32;const email=field('Email address · use no_reply if unavailable','text','email');email.maxLength=254;const rankSet=el('fieldset');rankSet.append(el('legend','Website ranks'));for(const rank of data.ranks){const label=el('label'),box=el('input');box.type='checkbox';box.name='rank';box.value=rank.key;box.checked=rank.key==='user';label.append(box,document.createTextNode(rank.label));rankSet.append(label);}form.append(rankSet);const ageWrap=el('label','Declared age group'),age=el('select');age.name='ageBand';age.required=true;for(const[value,label]of [['','Choose the age group declared by the user'],['15plus','15 or older'],['under15','Under 15']]){const option=el('option',label);option.value=value;age.append(option);}ageWrap.append(age);form.append(ageWrap);form.append(el('p','The user must change the temporary password, verify their own email and personally accept the terms at first sign-in.'));const submit=el('button','Create account');submit.type='submit';const status=el('p');status.setAttribute('role','status');const output=el('textarea');output.readOnly=true;output.rows=8;output.hidden=true;output.setAttribute('aria-label','New account credentials');const copy=el('button','Copy account details'),download=el('button','Download text file');copy.type=download.type='button';copy.hidden=download.hidden=true;copy.onclick=async()=>{await navigator.clipboard.writeText(output.value);status.textContent='Account details copied.';};download.onclick=()=>{const url=URL.createObjectURL(new Blob([output.value],{type:'text/plain;charset=utf-8'}));const link=el('a');link.href=url;link.download='DuneRealms-'+username.value.trim()+'.txt';document.body.append(link);link.click();link.remove();setTimeout(()=>URL.revokeObjectURL(url),1000);};form.append(submit);panel.append(form,status,output,copy,download);const heading=root.querySelector(':scope>h2');if(heading)heading.after(tab,panel);else root.prepend(tab,panel);tab.onclick=()=>{panel.hidden=!panel.hidden;tab.setAttribute('aria-expanded',String(!panel.hidden));};form.onsubmit=async event=>{event.preventDefault();submit.disabled=true;status.textContent='Creating account…';try{const r=await fetch('/api/admin/register-user',{method:'POST',headers:{'Content-Type':'application/json'},cache:'no-store',body:JSON.stringify({username:username.value,email:email.value.trim(),ageBand:age.value,ranks:[...rankSet.querySelectorAll('input:checked')].map(i=>i.value)})});const result=await r.json();if(!r.ok)throw Error(result.message);output.value=result.credentials;output.hidden=copy.hidden=download.hidden=false;form.hidden=true;if(typeof result.username==='string')username.value=result.username;try{download.onclick();status.textContent='Account created. Login file download started. Keep these credentials; they will not be shown again.';}catch{status.textContent='Account created. Use Download text file or Copy account details to save the credentials.';}output.focus();}catch(e){status.textContent=e.message;submit.disabled=false;}};} window.addEventListener('dune:session',()=>void mount());void mount(); const readyObserver=new MutationObserver(()=>{if(host()){readyObserver.disconnect();void mount();}});if(!host())readyObserver.observe(document.body,{childList:true,subtree:true}); diff --git a/website/node/first-login.mjs b/website/node/first-login.mjs index 30b38619..e0f98b5a 100644 --- a/website/node/first-login.mjs +++ b/website/node/first-login.mjs @@ -5,7 +5,7 @@ export async function firstLoginState(db,user){ if(!user)return null; const row=await db.prepare('SELECT password_changed FROM site_first_login WHERE user_id=?').bind(user.id).first();if(!row)return null; const email=await db.prepare('SELECT address,verified_at FROM site_contact_emails WHERE user_id=?').bind(user.id).first(); - const passwordRequired=!row.password_changed,emailRequired=!email?.verified_at||!email.address||email.address.toLowerCase()==='no_reply@dunerealms.com'; + const passwordRequired=!Number(row.password_changed),emailOverride=typeof email?.address==='string'&&email.address.trim().toLowerCase()==='no_reply@dunerealms.com',emailRequired=!emailOverride&&(!email?.verified_at||!email.address); const accepted=await db.prepare('SELECT version FROM site_terms_acceptances WHERE user_id=? AND version=?').bind(user.id,TERMS_VERSION).first();const termsRequired=!accepted; return passwordRequired||emailRequired||termsRequired?{passwordRequired,emailRequired,termsRequired}:null; } diff --git a/website/tests/first-login-override.test.mjs b/website/tests/first-login-override.test.mjs new file mode 100644 index 00000000..3888a109 --- /dev/null +++ b/website/tests/first-login-override.test.mjs @@ -0,0 +1,15 @@ +import test from 'node:test';import assert from 'node:assert/strict'; +import {LocalD1} from './d1-adapter.mjs'; +import {firstLoginState,initializeFirstLogin,TERMS_VERSION} from '../node/first-login.mjs'; +test('no_reply explicitly waives email onboarding without claiming verified email or waiving password and terms',async()=>{ + const db=new LocalD1('CREATE TABLE site_contact_emails(user_id TEXT,address TEXT,verified_at INTEGER)'); + try{await initializeFirstLogin(db);db.sqlite.prepare('INSERT INTO site_first_login VALUES(?,?,?)').run('user',0,Date.now());db.sqlite.prepare('INSERT INTO site_contact_emails VALUES(?,?,NULL)').run('user','no_reply@dunerealms.com'); + assert.deepEqual(await firstLoginState(db,{id:'user'}),{passwordRequired:true,emailRequired:false,termsRequired:true}); + db.sqlite.prepare('UPDATE site_first_login SET password_changed=1 WHERE user_id=?').run('user'); + db.sqlite.prepare('INSERT INTO site_terms_acceptances VALUES(?,?,?)').run('user',TERMS_VERSION,Date.now()); + assert.equal(await firstLoginState(db,{id:'user'}),null);assert.equal(db.sqlite.prepare('SELECT verified_at FROM site_contact_emails').get().verified_at,null); + db.sqlite.prepare('UPDATE site_contact_emails SET address=?').run('NO_REPLY@DUNEREALMS.COM');assert.equal(await firstLoginState(db,{id:'user'}),null); + db.sqlite.prepare('UPDATE site_contact_emails SET address=?').run('person@example.test');assert.deepEqual(await firstLoginState(db,{id:'user'}),{passwordRequired:false,emailRequired:true,termsRequired:false}); + db.sqlite.prepare('UPDATE site_contact_emails SET verified_at=?').run(Date.now());assert.equal(await firstLoginState(db,{id:'user'}),null); + }finally{db.close();} +}); From 54c2796a90b96dce99d32a856d8982a3dc70823a Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:56:17 +0100 Subject: [PATCH 2/4] Label the registration age selector for keyboard and assistive access --- website/control-panel/public/admin-registration.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/control-panel/public/admin-registration.mjs b/website/control-panel/public/admin-registration.mjs index 83fb0531..4a5961e9 100644 --- a/website/control-panel/public/admin-registration.mjs +++ b/website/control-panel/public/admin-registration.mjs @@ -1,6 +1,6 @@ const host=()=>document.getElementById('user-management'); const el=(tag,text)=>{const n=document.createElement(tag);if(text)n.textContent=text;return n;}; -async function mount(){const root=host();if(!root||document.getElementById('admin-registration-tab')||root.dataset.registrationMount)return;root.dataset.registrationMount='loading';const session=await fetch('/api/auth/session',{cache:'no-store'}).then(r=>r.json()).catch(()=>null);if(!session?.user?.ranks?.some(r=>['owners','official_account','web_net_admin','network_admin'].includes(r)))return;const response=await fetch('/api/admin/register-user',{cache:'no-store'});if(!response.ok)return;const data=await response.json();const tab=el('button','Register a user');tab.id='admin-registration-tab';tab.type='button';tab.setAttribute('aria-expanded','false');const panel=el('section');panel.hidden=true;panel.className='rank-create-panel admin-register-panel';panel.append(el('h3','Register a user'));const form=el('form');const field=(label,type,name)=>{const wrap=el('label',label),input=el('input');input.name=name;input.type=type;input.required=true;wrap.append(input);form.append(wrap);return input;};const username=field('Username','text','username');username.pattern='[A-Za-z0-9_]{3,32}';username.maxLength=32;const email=field('Email address · use no_reply if unavailable','text','email');email.maxLength=254;const rankSet=el('fieldset');rankSet.append(el('legend','Website ranks'));for(const rank of data.ranks){const label=el('label'),box=el('input');box.type='checkbox';box.name='rank';box.value=rank.key;box.checked=rank.key==='user';label.append(box,document.createTextNode(rank.label));rankSet.append(label);}form.append(rankSet);const ageWrap=el('label','Declared age group'),age=el('select');age.name='ageBand';age.required=true;for(const[value,label]of [['','Choose the age group declared by the user'],['15plus','15 or older'],['under15','Under 15']]){const option=el('option',label);option.value=value;age.append(option);}ageWrap.append(age);form.append(ageWrap);form.append(el('p','The user must change the temporary password, verify their own email and personally accept the terms at first sign-in.'));const submit=el('button','Create account');submit.type='submit';const status=el('p');status.setAttribute('role','status');const output=el('textarea');output.readOnly=true;output.rows=8;output.hidden=true;output.setAttribute('aria-label','New account credentials');const copy=el('button','Copy account details'),download=el('button','Download text file');copy.type=download.type='button';copy.hidden=download.hidden=true;copy.onclick=async()=>{await navigator.clipboard.writeText(output.value);status.textContent='Account details copied.';};download.onclick=()=>{const url=URL.createObjectURL(new Blob([output.value],{type:'text/plain;charset=utf-8'}));const link=el('a');link.href=url;link.download='DuneRealms-'+username.value.trim()+'.txt';document.body.append(link);link.click();link.remove();setTimeout(()=>URL.revokeObjectURL(url),1000);};form.append(submit);panel.append(form,status,output,copy,download);const heading=root.querySelector(':scope>h2');if(heading)heading.after(tab,panel);else root.prepend(tab,panel);tab.onclick=()=>{panel.hidden=!panel.hidden;tab.setAttribute('aria-expanded',String(!panel.hidden));};form.onsubmit=async event=>{event.preventDefault();submit.disabled=true;status.textContent='Creating account…';try{const r=await fetch('/api/admin/register-user',{method:'POST',headers:{'Content-Type':'application/json'},cache:'no-store',body:JSON.stringify({username:username.value,email:email.value.trim(),ageBand:age.value,ranks:[...rankSet.querySelectorAll('input:checked')].map(i=>i.value)})});const result=await r.json();if(!r.ok)throw Error(result.message);output.value=result.credentials;output.hidden=copy.hidden=download.hidden=false;form.hidden=true;if(typeof result.username==='string')username.value=result.username;try{download.onclick();status.textContent='Account created. Login file download started. Keep these credentials; they will not be shown again.';}catch{status.textContent='Account created. Use Download text file or Copy account details to save the credentials.';}output.focus();}catch(e){status.textContent=e.message;submit.disabled=false;}};} +async function mount(){const root=host();if(!root||document.getElementById('admin-registration-tab')||root.dataset.registrationMount)return;root.dataset.registrationMount='loading';const session=await fetch('/api/auth/session',{cache:'no-store'}).then(r=>r.json()).catch(()=>null);if(!session?.user?.ranks?.some(r=>['owners','official_account','web_net_admin','network_admin'].includes(r)))return;const response=await fetch('/api/admin/register-user',{cache:'no-store'});if(!response.ok)return;const data=await response.json();const tab=el('button','Register a user');tab.id='admin-registration-tab';tab.type='button';tab.setAttribute('aria-expanded','false');const panel=el('section');panel.hidden=true;panel.className='rank-create-panel admin-register-panel';panel.append(el('h3','Register a user'));const form=el('form');const field=(label,type,name)=>{const wrap=el('label',label),input=el('input');input.name=name;input.type=type;input.required=true;wrap.append(input);form.append(wrap);return input;};const username=field('Username','text','username');username.pattern='[A-Za-z0-9_]{3,32}';username.maxLength=32;const email=field('Email address · use no_reply if unavailable','text','email');email.maxLength=254;const rankSet=el('fieldset');rankSet.append(el('legend','Website ranks'));for(const rank of data.ranks){const label=el('label'),box=el('input');box.type='checkbox';box.name='rank';box.value=rank.key;box.checked=rank.key==='user';label.append(box,document.createTextNode(rank.label));rankSet.append(label);}form.append(rankSet);const ageWrap=el('label','Declared age group'),age=el('select');age.name='ageBand';age.setAttribute('aria-label','Declared age group');age.required=true;for(const[value,label]of [['','Choose the age group declared by the user'],['15plus','15 or older'],['under15','Under 15']]){const option=el('option',label);option.value=value;age.append(option);}ageWrap.append(age);form.append(ageWrap);form.append(el('p','The user must change the temporary password, verify their own email and personally accept the terms at first sign-in.'));const submit=el('button','Create account');submit.type='submit';const status=el('p');status.setAttribute('role','status');const output=el('textarea');output.readOnly=true;output.rows=8;output.hidden=true;output.setAttribute('aria-label','New account credentials');const copy=el('button','Copy account details'),download=el('button','Download text file');copy.type=download.type='button';copy.hidden=download.hidden=true;copy.onclick=async()=>{await navigator.clipboard.writeText(output.value);status.textContent='Account details copied.';};download.onclick=()=>{const url=URL.createObjectURL(new Blob([output.value],{type:'text/plain;charset=utf-8'}));const link=el('a');link.href=url;link.download='DuneRealms-'+username.value.trim()+'.txt';document.body.append(link);link.click();link.remove();setTimeout(()=>URL.revokeObjectURL(url),1000);};form.append(submit);panel.append(form,status,output,copy,download);const heading=root.querySelector(':scope>h2');if(heading)heading.after(tab,panel);else root.prepend(tab,panel);tab.onclick=()=>{panel.hidden=!panel.hidden;tab.setAttribute('aria-expanded',String(!panel.hidden));};form.onsubmit=async event=>{event.preventDefault();submit.disabled=true;status.textContent='Creating account…';try{const r=await fetch('/api/admin/register-user',{method:'POST',headers:{'Content-Type':'application/json'},cache:'no-store',body:JSON.stringify({username:username.value,email:email.value.trim(),ageBand:age.value,ranks:[...rankSet.querySelectorAll('input:checked')].map(i=>i.value)})});const result=await r.json();if(!r.ok)throw Error(result.message);output.value=result.credentials;output.hidden=copy.hidden=download.hidden=false;form.hidden=true;if(typeof result.username==='string')username.value=result.username;try{download.onclick();status.textContent='Account created. Login file download started. Keep these credentials; they will not be shown again.';}catch{status.textContent='Account created. Use Download text file or Copy account details to save the credentials.';}output.focus();}catch(e){status.textContent=e.message;submit.disabled=false;}};} window.addEventListener('dune:session',()=>void mount());void mount(); const readyObserver=new MutationObserver(()=>{if(host()){readyObserver.disconnect();void mount();}});if(!host())readyObserver.observe(document.body,{childList:true,subtree:true}); From f3a1a12b7b3c3ba04cdb72b1aeb7e87134812b6e Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:56:50 +0100 Subject: [PATCH 3/4] Match account instructions to the no-reply verification override --- website/control-panel/public/admin-registration.mjs | 2 +- website/node/admin-registration.mjs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/website/control-panel/public/admin-registration.mjs b/website/control-panel/public/admin-registration.mjs index 4a5961e9..85544189 100644 --- a/website/control-panel/public/admin-registration.mjs +++ b/website/control-panel/public/admin-registration.mjs @@ -1,6 +1,6 @@ const host=()=>document.getElementById('user-management'); const el=(tag,text)=>{const n=document.createElement(tag);if(text)n.textContent=text;return n;}; -async function mount(){const root=host();if(!root||document.getElementById('admin-registration-tab')||root.dataset.registrationMount)return;root.dataset.registrationMount='loading';const session=await fetch('/api/auth/session',{cache:'no-store'}).then(r=>r.json()).catch(()=>null);if(!session?.user?.ranks?.some(r=>['owners','official_account','web_net_admin','network_admin'].includes(r)))return;const response=await fetch('/api/admin/register-user',{cache:'no-store'});if(!response.ok)return;const data=await response.json();const tab=el('button','Register a user');tab.id='admin-registration-tab';tab.type='button';tab.setAttribute('aria-expanded','false');const panel=el('section');panel.hidden=true;panel.className='rank-create-panel admin-register-panel';panel.append(el('h3','Register a user'));const form=el('form');const field=(label,type,name)=>{const wrap=el('label',label),input=el('input');input.name=name;input.type=type;input.required=true;wrap.append(input);form.append(wrap);return input;};const username=field('Username','text','username');username.pattern='[A-Za-z0-9_]{3,32}';username.maxLength=32;const email=field('Email address · use no_reply if unavailable','text','email');email.maxLength=254;const rankSet=el('fieldset');rankSet.append(el('legend','Website ranks'));for(const rank of data.ranks){const label=el('label'),box=el('input');box.type='checkbox';box.name='rank';box.value=rank.key;box.checked=rank.key==='user';label.append(box,document.createTextNode(rank.label));rankSet.append(label);}form.append(rankSet);const ageWrap=el('label','Declared age group'),age=el('select');age.name='ageBand';age.setAttribute('aria-label','Declared age group');age.required=true;for(const[value,label]of [['','Choose the age group declared by the user'],['15plus','15 or older'],['under15','Under 15']]){const option=el('option',label);option.value=value;age.append(option);}ageWrap.append(age);form.append(ageWrap);form.append(el('p','The user must change the temporary password, verify their own email and personally accept the terms at first sign-in.'));const submit=el('button','Create account');submit.type='submit';const status=el('p');status.setAttribute('role','status');const output=el('textarea');output.readOnly=true;output.rows=8;output.hidden=true;output.setAttribute('aria-label','New account credentials');const copy=el('button','Copy account details'),download=el('button','Download text file');copy.type=download.type='button';copy.hidden=download.hidden=true;copy.onclick=async()=>{await navigator.clipboard.writeText(output.value);status.textContent='Account details copied.';};download.onclick=()=>{const url=URL.createObjectURL(new Blob([output.value],{type:'text/plain;charset=utf-8'}));const link=el('a');link.href=url;link.download='DuneRealms-'+username.value.trim()+'.txt';document.body.append(link);link.click();link.remove();setTimeout(()=>URL.revokeObjectURL(url),1000);};form.append(submit);panel.append(form,status,output,copy,download);const heading=root.querySelector(':scope>h2');if(heading)heading.after(tab,panel);else root.prepend(tab,panel);tab.onclick=()=>{panel.hidden=!panel.hidden;tab.setAttribute('aria-expanded',String(!panel.hidden));};form.onsubmit=async event=>{event.preventDefault();submit.disabled=true;status.textContent='Creating account…';try{const r=await fetch('/api/admin/register-user',{method:'POST',headers:{'Content-Type':'application/json'},cache:'no-store',body:JSON.stringify({username:username.value,email:email.value.trim(),ageBand:age.value,ranks:[...rankSet.querySelectorAll('input:checked')].map(i=>i.value)})});const result=await r.json();if(!r.ok)throw Error(result.message);output.value=result.credentials;output.hidden=copy.hidden=download.hidden=false;form.hidden=true;if(typeof result.username==='string')username.value=result.username;try{download.onclick();status.textContent='Account created. Login file download started. Keep these credentials; they will not be shown again.';}catch{status.textContent='Account created. Use Download text file or Copy account details to save the credentials.';}output.focus();}catch(e){status.textContent=e.message;submit.disabled=false;}};} +async function mount(){const root=host();if(!root||document.getElementById('admin-registration-tab')||root.dataset.registrationMount)return;root.dataset.registrationMount='loading';const session=await fetch('/api/auth/session',{cache:'no-store'}).then(r=>r.json()).catch(()=>null);if(!session?.user?.ranks?.some(r=>['owners','official_account','web_net_admin','network_admin'].includes(r)))return;const response=await fetch('/api/admin/register-user',{cache:'no-store'});if(!response.ok)return;const data=await response.json();const tab=el('button','Register a user');tab.id='admin-registration-tab';tab.type='button';tab.setAttribute('aria-expanded','false');const panel=el('section');panel.hidden=true;panel.className='rank-create-panel admin-register-panel';panel.append(el('h3','Register a user'));const form=el('form');const field=(label,type,name)=>{const wrap=el('label',label),input=el('input');input.name=name;input.type=type;input.required=true;wrap.append(input);form.append(wrap);return input;};const username=field('Username','text','username');username.pattern='[A-Za-z0-9_]{3,32}';username.maxLength=32;const email=field('Email address · use no_reply if unavailable','text','email');email.maxLength=254;const rankSet=el('fieldset');rankSet.append(el('legend','Website ranks'));for(const rank of data.ranks){const label=el('label'),box=el('input');box.type='checkbox';box.name='rank';box.value=rank.key;box.checked=rank.key==='user';label.append(box,document.createTextNode(rank.label));rankSet.append(label);}form.append(rankSet);const ageWrap=el('label','Declared age group'),age=el('select');age.name='ageBand';age.setAttribute('aria-label','Declared age group');age.required=true;for(const[value,label]of [['','Choose the age group declared by the user'],['15plus','15 or older'],['under15','Under 15']]){const option=el('option',label);option.value=value;age.append(option);}ageWrap.append(age);form.append(ageWrap);form.append(el('p','The user must change the temporary password and accept the terms at first sign-in. Email verification is skipped when you enter no_reply.'));const submit=el('button','Create account');submit.type='submit';const status=el('p');status.setAttribute('role','status');const output=el('textarea');output.readOnly=true;output.rows=8;output.hidden=true;output.setAttribute('aria-label','New account credentials');const copy=el('button','Copy account details'),download=el('button','Download text file');copy.type=download.type='button';copy.hidden=download.hidden=true;copy.onclick=async()=>{await navigator.clipboard.writeText(output.value);status.textContent='Account details copied.';};download.onclick=()=>{const url=URL.createObjectURL(new Blob([output.value],{type:'text/plain;charset=utf-8'}));const link=el('a');link.href=url;link.download='DuneRealms-'+username.value.trim()+'.txt';document.body.append(link);link.click();link.remove();setTimeout(()=>URL.revokeObjectURL(url),1000);};form.append(submit);panel.append(form,status,output,copy,download);const heading=root.querySelector(':scope>h2');if(heading)heading.after(tab,panel);else root.prepend(tab,panel);tab.onclick=()=>{panel.hidden=!panel.hidden;tab.setAttribute('aria-expanded',String(!panel.hidden));};form.onsubmit=async event=>{event.preventDefault();submit.disabled=true;status.textContent='Creating account…';try{const r=await fetch('/api/admin/register-user',{method:'POST',headers:{'Content-Type':'application/json'},cache:'no-store',body:JSON.stringify({username:username.value,email:email.value.trim(),ageBand:age.value,ranks:[...rankSet.querySelectorAll('input:checked')].map(i=>i.value)})});const result=await r.json();if(!r.ok)throw Error(result.message);output.value=result.credentials;output.hidden=copy.hidden=download.hidden=false;form.hidden=true;if(typeof result.username==='string')username.value=result.username;try{download.onclick();status.textContent='Account created. Login file download started. Keep these credentials; they will not be shown again.';}catch{status.textContent='Account created. Use Download text file or Copy account details to save the credentials.';}output.focus();}catch(e){status.textContent=e.message;submit.disabled=false;}};} window.addEventListener('dune:session',()=>void mount());void mount(); const readyObserver=new MutationObserver(()=>{if(host()){readyObserver.disconnect();void mount();}});if(!host())readyObserver.observe(document.body,{childList:true,subtree:true}); diff --git a/website/node/admin-registration.mjs b/website/node/admin-registration.mjs index e63c0171..e7bfd5d5 100644 --- a/website/node/admin-registration.mjs +++ b/website/node/admin-registration.mjs @@ -31,5 +31,5 @@ export function createAdminRegistration(db,origin){return async request=>{ const ranks=[...new Set(b.ranks)];for(const k of ranks){const r=await rankFor(db,k);if(r.kind!=='access'||r.level<=0||['memorial','crysknife'].includes(k))return reply({message:'Invalid rank.'},400);} const id=randomUUID(),password=randomBytes(24).toString('base64url'),salt=randomBytes(16).toString('hex'),hash=(await scrypt(password,salt,64)).toString('hex'),now=Date.now(); try{await db.batch([{async run(c){const q=async(sql,v=[])=>(await c.execute(sql,v))[0];const a=await q('SELECT role FROM site_accounts WHERE id=? FOR UPDATE',[actor.id]);const extra=await q('SELECT rank_key FROM cp_account_ranks WHERE user_id=? FOR SHARE',[actor.id]);if(![a[0]?.role,...extra.map(r=>r.rank_key)].some(isOwnerRank))throw Error('permission-changed');await q('INSERT INTO site_accounts(id,username,display_name,password_salt,password_hash,role,created_at) VALUES(?,?,?,?,?,?,?)',[id,username,username,salt,hash,ranks[0],now]);for(const k of ranks.slice(1))await q('INSERT INTO cp_account_ranks(user_id,rank_key) VALUES(?,?)',[id,k]);await q('INSERT INTO player_profiles(user_id,display_name,minecraft_name,discord_name,created_at,updated_at) VALUES(?,?,?,?,?,?)',[id,username,'','',now,now]);await q('INSERT INTO site_age_declarations(user_id,age_band,declared_at) VALUES(?,?,?)',[id,b.ageBand,now]);await q('INSERT INTO site_contact_emails(user_id,address,version) VALUES(?,?,0)',[id,email]);await q('INSERT INTO site_first_login(user_id,created_at) VALUES(?,?)',[id,now]);await ensurePersonnelNumber({query:q,first:async(sql,args)=>(await q(sql,args))[0]||null},id,{actorId:actor.id,now});await q('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),actor.id,'admin-register',JSON.stringify({username,ranks,firstLoginRequired:true}),now]);return{meta:{changes:1}};}}]);}catch(e){if(e.code==='ER_DUP_ENTRY'||String(e.message).includes('UNIQUE constraint'))return reply({message:'Username unavailable.'},409);if(e.message==='permission-changed')return reply({message:'Your account authority changed.'},403);throw e;} - return reply({username,credentials:'DuneRealms account: '+username+'\nWebsite: https://cp.dunerealms.com/\nPassword: '+password+'\n\nAt your first sign-in, change your password and verify your own email address:\nhttps://cp.dunerealms.com/#security\n',firstLoginRequired:true},201); + return reply({username,credentials:'DuneRealms account: '+username+'\nWebsite: https://cp.dunerealms.com/\nPassword: '+password+'\n\nAt your first sign-in, change your password'+(email==='no_reply@dunerealms.com'?'':' and verify your own email address')+', then accept the terms:\nhttps://cp.dunerealms.com/#security\n',firstLoginRequired:true},201); };} From 18c66fbfccad672fdf99b8d060ddb03354a394d8 Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:58:36 +0100 Subject: [PATCH 4/4] Describe only pending onboarding steps in access responses --- website/node/first-login.mjs | 2 +- website/tests/first-login-override.test.mjs | 11 +++++++++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/website/node/first-login.mjs b/website/node/first-login.mjs index e0f98b5a..919d409a 100644 --- a/website/node/first-login.mjs +++ b/website/node/first-login.mjs @@ -12,7 +12,7 @@ export async function firstLoginState(db,user){ export async function firstLoginGate(request,db){ const path=new URL(request.url).pathname;if(!path.startsWith('/api/')&&!path.startsWith('/sso/')&&!path.startsWith('/git/'))return null; if(['/api/auth/login','/api/auth/logout','/api/auth/session','/api/auth/password','/api/auth/terms','/api/account/email'].includes(path))return null; - const state=await firstLoginState(db,await identity(request,db));return state?Response.json({message:'Complete your first sign-in: change your password and verify your own email address.',firstLogin:state,securityUrl:'https://cp.dunerealms.com/#security'},{status:428,headers:{'Cache-Control':'no-store'}}):null; + const state=await firstLoginState(db,await identity(request,db));return state?Response.json({message:'Complete your first sign-in: '+[state.passwordRequired?'change your password':null,state.emailRequired?'verify your email address':null,state.termsRequired?'accept the terms':null].filter(Boolean).join(', ')+'.',firstLogin:state,securityUrl:'https://cp.dunerealms.com/#security'},{status:428,headers:{'Cache-Control':'no-store'}}):null; } export async function initializeFirstLogin(db){await db.prepare(FIRST_LOGIN_SCHEMA).run();await db.prepare('CREATE TABLE IF NOT EXISTS site_terms_acceptances(user_id CHAR(36) NOT NULL,version VARCHAR(64) NOT NULL,accepted_at BIGINT NOT NULL,PRIMARY KEY(user_id,version))').run();} diff --git a/website/tests/first-login-override.test.mjs b/website/tests/first-login-override.test.mjs index 3888a109..99e1f54c 100644 --- a/website/tests/first-login-override.test.mjs +++ b/website/tests/first-login-override.test.mjs @@ -1,6 +1,6 @@ -import test from 'node:test';import assert from 'node:assert/strict'; +import test from 'node:test';import assert from 'node:assert/strict';import {createHash} from 'node:crypto'; import {LocalD1} from './d1-adapter.mjs'; -import {firstLoginState,initializeFirstLogin,TERMS_VERSION} from '../node/first-login.mjs'; +import {firstLoginState,firstLoginGate,initializeFirstLogin,TERMS_VERSION} from '../node/first-login.mjs'; test('no_reply explicitly waives email onboarding without claiming verified email or waiving password and terms',async()=>{ const db=new LocalD1('CREATE TABLE site_contact_emails(user_id TEXT,address TEXT,verified_at INTEGER)'); try{await initializeFirstLogin(db);db.sqlite.prepare('INSERT INTO site_first_login VALUES(?,?,?)').run('user',0,Date.now());db.sqlite.prepare('INSERT INTO site_contact_emails VALUES(?,?,NULL)').run('user','no_reply@dunerealms.com'); @@ -13,3 +13,10 @@ test('no_reply explicitly waives email onboarding without claiming verified emai db.sqlite.prepare('UPDATE site_contact_emails SET verified_at=?').run(Date.now());assert.equal(await firstLoginState(db,{id:'user'}),null); }finally{db.close();} }); +test('the live gate describes only unfinished steps and opens normal APIs after no-reply onboarding',async()=>{ + const db=new LocalD1('CREATE TABLE site_accounts(id TEXT,username TEXT,display_name TEXT,role TEXT);CREATE TABLE site_sessions(token_hash TEXT,user_id TEXT,expires_at INTEGER);CREATE TABLE site_contact_emails(user_id TEXT,address TEXT,verified_at INTEGER)'); + try{await initializeFirstLogin(db);const token='x'.repeat(43);db.sqlite.prepare('INSERT INTO site_accounts VALUES(?,?,?,?)').run('user','test_citizen','Test Citizen','user');db.sqlite.prepare('INSERT INTO site_sessions VALUES(?,?,?)').run(createHash('sha256').update(token).digest('hex'),'user',Date.now()+60000);db.sqlite.prepare('INSERT INTO site_contact_emails VALUES(?,?,NULL)').run('user','no_reply@dunerealms.com');db.sqlite.prepare('INSERT INTO site_first_login VALUES(?,?,?)').run('user',1,Date.now()); + const request=new Request('https://cp.dunerealms.com/api/game',{headers:{cookie:'__Host-dune_session='+token}}),pending=await firstLoginGate(request,db);assert.equal(pending.status,428);const body=await pending.json();assert.equal(body.message,'Complete your first sign-in: accept the terms.');assert.deepEqual(body.firstLogin,{passwordRequired:false,emailRequired:false,termsRequired:true}); + db.sqlite.prepare('INSERT INTO site_terms_acceptances VALUES(?,?,?)').run('user',TERMS_VERSION,Date.now());assert.equal(await firstLoginGate(request,db),null); + }finally{db.close();} +});