Allow existing shorter passwords at sign-in while retaining new-password policy

This commit is contained in:
unimatrixgit 2026-11-29 07:25:08 +01:00
commit 73f3464e45
7 changed files with 97 additions and 5 deletions

View file

@ -18,12 +18,12 @@ export async function startCPAuthentication(onReady,{fetcher=fetch,locationTarge
function showSignIn(){
host.replaceChildren();const art=el('img');art.src='https://www.dunerealms.com/assets/nav-account-v2.webp';art.alt='';art.width=art.height=96;host.append(art,el('p','YOUR PLACE IN THE IMPERIAL LEDGER','cp-v2-auth-eyebrow'),el('h1','Citizen Passport'),el('p','Sign in to your DuneRealms account.'));
const tabs=el('div',undefined,'cp-v2-company-actions'),login=el('button','Sign in'),register=el('button','Create account');login.type=register.type='button';tabs.append(login,register);
const form=el('form'),name=el('input'),password=el('input');name.name='username';name.autocomplete='username';name.required=true;name.minLength=3;name.maxLength=32;name.pattern='[A-Za-z0-9_]{3,32}';password.name='password';password.type='password';password.autocomplete='current-password';password.required=true;password.minLength=12;password.maxLength=256;
const form=el('form'),name=el('input'),password=el('input');name.name='username';name.autocomplete='username';name.required=true;name.minLength=3;name.maxLength=32;name.pattern='[A-Za-z0-9_]{3,32}';password.name='password';password.type='password';password.autocomplete='current-password';password.required=true;password.minLength=1;password.maxLength=256;
const field=(label,input)=>{const node=el('label',label);node.append(input);return node;};form.append(field('DuneRealms name',name),field('Password',password));
const age=el('select');age.name='ageBand';for(const [value,label]of [['','Choose your age category'],['under15','Under 15'],['15to17','15–17'],['18plus','18 or older']]){const option=el('option',label);option.value=value;age.append(option);}const ageField=field('Age category',age);ageField.hidden=true;age.disabled=true;
const bio=el('textarea');bio.name='bio';bio.minLength=10;bio.maxLength=1000;bio.rows=4;const bioField=field('Biography · required · 10–1,000 characters',bio);
const send=el('button','Sign in');send.type='submit';const feedback=el('p');feedback.setAttribute('role','status');form.append(ageField,bioField,send,feedback);host.append(tabs,form);let mode='login';
const select=value=>{mode=value;ageField.hidden=age.disabled=bioField.hidden=bio.disabled=value!=='register';age.required=bio.required=value==='register';password.autocomplete=value==='register'?'new-password':'current-password';send.textContent=value==='register'?'Create account':'Sign in';login.setAttribute('aria-pressed',String(value==='login'));register.setAttribute('aria-pressed',String(value==='register'));feedback.textContent='';};login.onclick=()=>select('login');register.onclick=()=>select('register');select('login');
const select=value=>{mode=value;ageField.hidden=age.disabled=bioField.hidden=bio.disabled=value!=='register';age.required=bio.required=value==='register';password.autocomplete=value==='register'?'new-password':'current-password';password.minLength=value==='register'?12:1;send.textContent=value==='register'?'Create account':'Sign in';login.setAttribute('aria-pressed',String(value==='login'));register.setAttribute('aria-pressed',String(value==='register'));feedback.textContent='';};login.onclick=()=>select('login');register.onclick=()=>select('register');select('login');
form.onsubmit=async event=>{event.preventDefault();if(send.disabled)return;if(mode==='register'&&bio.value.trim().length<10){feedback.textContent='Write a biography of at least 10 characters.';bio.focus();return;}send.disabled=true;feedback.textContent='Opening your passport…';try{await request('auth/'+mode,{username:name.value.trim(),password:password.value,...(mode==='register'?{ageBand:age.value,bio:bio.value.trim()}:{})});password.value='';locationTarget.reload();}catch(error){password.value='';feedback.textContent=error.message;send.disabled=false;password.focus();}};
}
function showOnboarding(){

View file

@ -0,0 +1,20 @@
# Existing-password sign-in correction
The owner reported being unable to sign in. The Citizen Passport screenshot
showed native browser validation requiring twelve characters for an existing
nine-character password. Both browser forms and the shared authentication API
incorrectly applied the new-password minimum to existing-password login.
Sign-in now accepts a nonempty existing password up to the existing 256-character
limit and verifies its unchanged stored hash. Registration and password changes
still require twelve characters. No password, account, role or session records
were reset or edited to make the correction.
Regression checks authenticate a seeded nine-character existing password through
both host origins, reject an incorrect password, preserve the stored hash/salt
and role, reject empty/oversized login input, and continue rejecting short new
passwords. Both actual form scripts are exercised across login/register mode
switches, including the Citizen Passport submission path. Ten targeted checks
passed locally. Publication must use the normal reviewed commit and canonical
CI; verify the live form constraints and serving revision afterward. No real
user credential was requested or used in testing.

View file

@ -38,7 +38,8 @@ export function createAuth(db,origin,{trackFirstLogin=false,onAccountReady=async
let data;try{data=await request.json();}catch{return json({message:'Send valid JSON.'},400);}
const username=typeof data?.username==='string'?data.username.trim().toLowerCase():'';
const password=data?.password;
if(!/^[a-z0-9_]{3,32}$/.test(username)||typeof password!=='string'||password.length<12||password.length>256)return json({message:'Use a username of 3–32 letters, numbers or underscores and a password of 12–256 characters.'},400);
const minimumPasswordLength=path==='/api/auth/register'?12:1;
if(!/^[a-z0-9_]{3,32}$/.test(username)||typeof password!=='string'||password.length<minimumPasswordLength||password.length>256)return json({message:path==='/api/auth/register'?'Use a username of 3–32 letters, numbers or underscores and a password of 12–256 characters.':'Enter your existing password and a username of 3–32 letters, numbers or underscores.'},400);
if(!allowed(username)||!allowed('global',120,60000))return json({message:'Too many attempts. Please try again later.'},429);
if(path==='/api/auth/register'){
if(!['under15','15to17','18plus'].includes(data?.ageBand))

File diff suppressed because one or more lines are too long

View file

@ -5,7 +5,7 @@ ageField.textContent='Age category';age.name='ageBand';for(const [value,label]of
form.insertBefore(ageField,document.querySelector('#account-note'));form.insertBefore(bioField,document.querySelector('#account-note'));
function registrationFields(){const registering=mode==='register';bioField.hidden=ageField.hidden=bio.disabled=age.disabled=!registering;bio.required=age.required=registering;bio.setCustomValidity('');}
bio.addEventListener('input',()=>bio.setCustomValidity(mode==='register'&&bio.value.trim().length<10?'Write a biography of at least 10 characters.':''));registrationFields();
function change(next){mode=next;for(const type of ['login','register'])document.querySelector('#'+type+'-tab').setAttribute('aria-pressed',String(next===type));form.elements.password.autocomplete=mode==='register'?'new-password':'current-password';submit.textContent=mode==='register'?'Create account →':'Sign in →';document.querySelector('#account-note').textContent=mode==='register'?'Choose 3–32 letters, numbers or underscores, and a password of at least 12 characters.':'Use your DuneRealms website account.';status.textContent='';}
function change(next){mode=next;for(const type of ['login','register'])document.querySelector('#'+type+'-tab').setAttribute('aria-pressed',String(next===type));form.elements.password.autocomplete=mode==='register'?'new-password':'current-password';form.elements.password.minLength=mode==='register'?12:1;form.elements.password.placeholder=mode==='register'?'At least 12 characters':'Your existing password';submit.textContent=mode==='register'?'Create account →':'Sign in →';document.querySelector('#account-note').textContent=mode==='register'?'Choose 3–32 letters, numbers or underscores, and a password of at least 12 characters.':'Use your DuneRealms website account.';status.textContent='';}
for(const type of ['login','register'])document.querySelector('#'+type+'-tab').addEventListener('click',()=>{change(type);registrationFields();});
function destination(){const value=new URLSearchParams(location.search).get('return_to');return value&&value.startsWith('/')&&!value.startsWith('//')&&!/[\\\r\n]/.test(value)?value:'/portal.html';}
form.addEventListener('submit',async event=>{event.preventDefault();submit.disabled=true;status.textContent='Please wait…';try{const response=await fetch('/api/auth/'+mode,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(Object.fromEntries(new FormData(form)))});const result=await response.json();if(!response.ok)throw Error(result.message||'Sign-in failed.');location.assign(destination());}catch(error){status.textContent=error.message;}finally{submit.disabled=false;}});

View file

@ -0,0 +1,44 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import vm from 'node:vm';
function node(tag='div',text=''){
return {tag,textContent:text||'',children:[],events:{},value:'',hidden:false,disabled:false,
append(...children){this.children.push(...children);},prepend(...children){this.children.unshift(...children);},
replaceChildren(...children){this.children=children;},insertBefore(child){this.children.push(child);},
setAttribute(name,value){this[name]=value;},addEventListener(name,fn){this.events[name]=fn;},
setCustomValidity(){},focus(){}};
}
test('Citizen Passport switches the password constraint by mode and submits an existing nine-character password',async()=>{
const nodes=[],surfaces=new Map(),writes=[];let reloads=0;
const el=(tag,text)=>{const n=node(tag,text);nodes.push(n);return n;};
const document={body:node(),querySelector(selector){if(selector==='.command-banner')return null;if(!surfaces.has(selector))surfaces.set(selector,node());return surfaces.get(selector);}};
const source=readFileSync(new URL('../control-panel/public/cp-v2/cp-v2-auth.mjs',import.meta.url),'utf8').replace(/^import .*;\r?\n/gm,'').replaceAll('export ','');
const context=vm.createContext({el,document,URL,AbortSignal,mountSecurity(){},location:{href:'https://cp.dunerealms.com/'}});
vm.runInContext(source,context);
await context.startCPAuthentication(()=>assert.fail('No authenticated session yet'),{locationTarget:{reload(){reloads++;}},fetcher:async(path,init)=>{
if(path==='/api/auth/session')return Response.json({authenticated:false});
writes.push({path,data:JSON.parse(init.body)});return Response.json({ok:true});
}});
const password=nodes.find(n=>n.name==='password'),name=nodes.find(n=>n.name==='username'),form=nodes.find(n=>n.tag==='form');
const login=nodes.find(n=>n.tag==='button'&&n.textContent==='Sign in'),register=nodes.find(n=>n.tag==='button'&&n.textContent==='Create account');
assert.equal(password.minLength,1);assert.equal(password.maxLength,256);assert.equal(password.autocomplete,'current-password');
register.onclick();assert.equal(password.minLength,12);assert.equal(password.autocomplete,'new-password');
login.onclick();assert.equal(password.minLength,1);assert.equal(password.autocomplete,'current-password');
name.value='legacy_test';password.value='oldpass12';await form.onsubmit({preventDefault(){}});
assert.deepEqual(writes,[{path:'/api/auth/login',data:{username:'legacy_test',password:'oldpass12'}}]);assert.equal(reloads,1);
});
test('public sign-in starts with an existing-password constraint and retains the registration minimum',async()=>{
const html=readFileSync(new URL('../node/public/login.html',import.meta.url),'utf8');
assert.match(html,/autocomplete="current-password" required minlength="1" maxlength="256"/);
const form=node('form');form.elements={password:{minLength:1,maxLength:256}};
const nodes=new Map([['#account-form',form]]);
const document={createElement:tag=>node(tag),querySelector(selector){if(!nodes.has(selector))nodes.set(selector,node());return nodes.get(selector);}};
const source=readFileSync(new URL('../node/public/login.js',import.meta.url),'utf8');
vm.runInNewContext(source,{document,URLSearchParams,location:{search:''},fetch:async()=>({json:async()=>({authenticated:false})})});
nodes.get('#register-tab').events.click();assert.equal(form.elements.password.minLength,12);assert.equal(form.elements.password.autocomplete,'new-password');
nodes.get('#login-tab').events.click();assert.equal(form.elements.password.minLength,1);assert.equal(form.elements.password.autocomplete,'current-password');
});

View file

@ -5,6 +5,8 @@ import {readFileSync} from 'node:fs';
import {LocalD1} from './d1-adapter.mjs';
import {createApplication} from '../node/server.mjs';
import {mysqlSql} from '../node/mysql.mjs';
import {scryptSync} from 'node:crypto';
import {createAuth} from '../node/auth.mjs';
const schema=REGISTRATION_PROFILE_SCHEMA+['0000_forums','0001_profiles_tickets'].map(n=>readFileSync(new URL('../drizzle/'+n+'.sql',import.meta.url),'utf8')).join('\n')+`
CREATE TABLE IF NOT EXISTS site_age_declarations(user_id TEXT PRIMARY KEY,age_band TEXT,declared_at INTEGER);CREATE TABLE site_accounts(id TEXT PRIMARY KEY,username TEXT UNIQUE,display_name TEXT,password_salt TEXT,password_hash TEXT,role TEXT,created_at INTEGER);
CREATE TABLE site_sessions(token_hash TEXT PRIMARY KEY,user_id TEXT,expires_at INTEGER);`;
@ -35,3 +37,28 @@ test('External hosting rejects forged identity, protects sessions and keeps priv
test('MySQL profile upserts retain bound values',()=>{
assert.equal(mysqlSql('INSERT INTO player_profiles(user_id) VALUES(?) ON CONFLICT(user_id) DO UPDATE SET display_name=excluded.display_name'),'INSERT INTO player_profiles(user_id) VALUES(?) ON DUPLICATE KEY UPDATE display_name=VALUES(display_name)');
});
test('existing nine-character passwords authenticate on both hosts without weakening new-password rules',async()=>{
const db=new LocalD1(schema+`CREATE TABLE cp_ranks(rank_key TEXT PRIMARY KEY,label TEXT,rank_level INTEGER,kind TEXT,permissions_json TEXT,version INTEGER);`);
try{
const app=createApplication(db),account={username:'legacy_test',password:'A long registration password',ageBand:'18plus',bio:'An existing traveller of the desert.'};
assert.equal((await app(request('/api/auth/register','POST',account))).status,200);
const row=await db.prepare('SELECT * FROM site_accounts WHERE username=?').bind(account.username).first();
const existing='oldpass12';assert.equal(existing.length,9);
const hash=scryptSync(existing,row.password_salt,64).toString('hex');
await db.prepare('UPDATE site_accounts SET password_hash=? WHERE id=?').bind(hash,row.id).run();
for(const host of ['https://www.dunerealms.com','https://cp.dunerealms.com']){
const auth=createAuth(db,host),post=(path,data,cookie)=>auth(new Request(host+path,{method:'POST',headers:{Origin:host,'Content-Type':'application/json',...(cookie?{Cookie:cookie}:{})},body:JSON.stringify(data)}));
const signedIn=await post('/api/auth/login',{username:account.username,password:existing});assert.equal(signedIn.status,200);
const cookie=signedIn.headers.get('set-cookie').split(';')[0];assert.match(cookie,/^__Host-dune_session=/);
const session=await auth(new Request(host+'/api/auth/session',{headers:{Cookie:cookie}}));assert.equal((await session.json()).authenticated,true);
assert.equal((await post('/api/auth/login',{username:account.username,password:'wrongpass'})).status,401);
for(const password of ['', 'x'.repeat(257)])assert.equal((await post('/api/auth/login',{username:account.username,password})).status,400);
assert.equal((await post('/api/auth/register',{...account,username:'new_citizen',password:existing})).status,400);
assert.equal((await post('/api/auth/password',{currentPassword:existing,newPassword:'shortpass'},cookie)).status,400);
}
const unchanged=await db.prepare('SELECT * FROM site_accounts WHERE id=?').bind(row.id).first();
assert.equal(unchanged.password_hash,hash);assert.equal(unchanged.password_salt,row.password_salt);assert.equal(unchanged.role,row.role);
assert.equal((await db.prepare('SELECT COUNT(*) AS n FROM site_accounts').first()).n,1);
}finally{db.close();}
});