Add account password changes and administrator resets
This commit is contained in:
1 parent
23e28a7dcb
commit
060b36682d
14 files changed
+263
-26
No files matched your search
@@ -0,0 +1,83 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
|
||||
const {Store}=require('../../src/modules/dashboard/store.cjs'),{createDashboard}=require('../../src/app/dashboard.cjs');
|
||||
const {SessionStore}=require('../../src/modules/dashboard/sessions.cjs');
|
||||
const OLD='Test-password-123',NEW='Changed-password-456';
|
||||
async function fixture(t,options={}){
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'account-password-')),store=new Store(dir);const admin=store.bootstrap('admin',OLD);
|
||||
const viewer=store.addUser({username:'viewer',password:OLD,role:'viewer'},'admin'),operator=store.addUser({username:'operator',password:OLD,role:'operator'},'admin');
|
||||
let server,base;async function start(){server=createDashboard({store,outputDir:dir,...options});await new Promise(r=>server.listen(0,'127.0.0.1',r));base='http://127.0.0.1:'+server.address().port;}
|
||||
async function stop(){server.closeAllConnections();await new Promise(r=>server.close(r));}await start();t.after(async()=>{await stop();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
const call=(route,body,cookie,origin)=>fetch(base+route,{method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{Origin:origin||base,'Content-Type':'application/json'}),...(cookie?{Cookie:cookie}:{})},body:body===undefined?undefined:JSON.stringify(body)});
|
||||
const login=async(username='admin',password=OLD)=>{const r=await call('/api/login',{username,password});assert.equal(r.status,200);return r.headers.get('set-cookie').split(';')[0];};
|
||||
return {dir,store,admin,viewer,operator,call,login,restart:async()=>{await stop();await start();}};
|
||||
}
|
||||
const input=(currentPassword=OLD,newPassword=NEW)=>({currentPassword,newPassword,confirmPassword:newPassword});
|
||||
test('every role can change own password; all old sessions expire and new credentials persist after restart',async t=>{
|
||||
const f=await fixture(t);for(const username of ['admin','viewer','operator']){
|
||||
const first=await f.login(username),second=await f.login(username);const result=await f.call('/api/account/password',input(),first);assert.equal(result.status,200);assert.equal((await result.json()).requiresLogin,true);assert.equal(result.headers.get('set-cookie'),null);
|
||||
assert.equal((await f.call('/api/me',undefined,first)).status,401);assert.equal((await f.call('/api/me',undefined,second)).status,401);assert.equal((await f.call('/api/login',{username,password:OLD})).status,401);
|
||||
assert.ok(new Store(f.dir).authenticate(username,NEW));await f.restart();assert.equal((await f.call('/api/me',undefined,second)).status,401);assert.equal((await f.call('/api/me',undefined,await f.login(username,NEW))).status,200);
|
||||
}
|
||||
const serialized=JSON.stringify(f.store.audit());assert.match(serialized,/修改密码/);assert.equal(serialized.includes(NEW),false);assert.equal(serialized.includes(OLD),false);
|
||||
assert.equal(fs.readFileSync(path.join(f.dir,'state.sqlite')).includes(Buffer.from(NEW)),false);
|
||||
});
|
||||
test('invalid password edits, wrong current password, and cross-origin requests preserve existing credentials and sessions',async t=>{
|
||||
const f=await fixture(t),cookie=await f.login();const original=JSON.stringify(f.store.data);
|
||||
const invalid=[input('incorrect'),input(OLD,'short'),input(OLD,'x'.repeat(129)),input(OLD,OLD),{...input(),confirmPassword:'Mismatch-password-123'},{...input(),userId:f.viewer.id}];
|
||||
for(const body of invalid)assert.equal((await f.call('/api/account/password',body,cookie)).status,400);
|
||||
assert.equal((await f.call('/api/account/password',input(),cookie,'https://evil.test')).status,403);assert.equal((await f.call('/api/account/password',input())).status,401);
|
||||
assert.equal(JSON.stringify(f.store.data),original);assert.equal((await f.call('/api/me',undefined,cookie)).status,200);
|
||||
});
|
||||
test('admin reset requires admin current password, revokes target sessions, preserves other accounts, and rejects self reset',async t=>{
|
||||
const f=await fixture(t),admin=await f.login(),target=await f.login('viewer');const route='/api/users/'+f.viewer.id+'/password';
|
||||
assert.equal((await f.call(route,input(),target)).status,403);assert.equal((await f.call(route,input('incorrect'),admin)).status,400);
|
||||
assert.equal((await f.call('/api/users/'+f.admin.id+'/password',input(),admin)).status,400);assert.equal((await f.call('/api/users/missing/password',input(),admin)).status,404);
|
||||
const r=await f.call(route,input(),admin);assert.equal(r.status,200);assert.equal((await r.json()).requiresLogin,false);
|
||||
assert.equal((await f.call('/api/me',undefined,target)).status,401);assert.equal((await f.call('/api/me',undefined,admin)).status,200);assert.ok(f.store.authenticate('viewer',NEW));assert.ok(f.store.authenticate('admin',OLD));
|
||||
assert.match(JSON.stringify(f.store.audit()),/重置密码/);
|
||||
});
|
||||
test('incorrect current passwords are rate limited without invalidating a valid session',async t=>{
|
||||
const f=await fixture(t),cookie=await f.login();for(let i=0;i<10;i++)assert.equal((await f.call('/api/account/password',input('incorrect'),cookie)).status,400);
|
||||
assert.equal((await f.call('/api/account/password',input(),cookie)).status,429);assert.equal((await f.call('/api/me',undefined,cookie)).status,200);
|
||||
});
|
||||
test('password version rejects old sessions even if eager session cleanup fails',async t=>{
|
||||
const f=await fixture(t),cookie=await f.login();const original=SessionStore.prototype.revokeUser;SessionStore.prototype.revokeUser=()=>{throw Error('injected cleanup failure');};
|
||||
try{assert.equal((await f.call('/api/account/password',input(),cookie)).status,200);}finally{SessionStore.prototype.revokeUser=original;}
|
||||
assert.equal((await f.call('/api/me',undefined,cookie)).status,401);await f.restart();assert.equal((await f.call('/api/me',undefined,cookie)).status,401);await f.login('admin',NEW);
|
||||
});
|
||||
|
||||
test('password change closes only the target account BPM login windows',async t=>{
|
||||
const crypto=require('node:crypto'),{BpmSessionManager}=require('../../src/modules/bpm/session-manager.cjs');
|
||||
const f=await fixture(t),first=await f.login('viewer'),second=await f.login('viewer'),admin=await f.login();
|
||||
const cookies=[first,second,admin],manager={revokedSessionHashes:new Set(),sessions:new Map(cookies.map((cookie,i)=>[String(i),{id:String(i),sessionId:cookie.split('=')[1]}])),run:async(id,work)=>work(),async closeLease(id){this.sessions.delete(id);}};
|
||||
const hashes=new SessionStore(f.dir);const targetHashes=hashes.userSessionHashes(f.viewer.id);hashes.close();
|
||||
assert.equal(targetHashes.length,2);await BpmSessionManager.prototype.releaseSessionHashes.call(manager,targetHashes);assert.deepEqual([...manager.sessions.keys()],['2']);
|
||||
assert.equal(targetHashes.includes(crypto.createHash('sha256').update(admin.split('=')[1]).digest('hex')),false);
|
||||
});
|
||||
test('existing database sessions survive schema migration until their account password changes',async t=>{
|
||||
const {DatabaseSync}=require('node:sqlite'),crypto=require('node:crypto');
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'account-legacy-session-')),store=new Store(dir),user=store.bootstrap('admin',OLD),token=crypto.randomBytes(32).toString('hex');
|
||||
const db=new DatabaseSync(path.join(dir,'auth.sqlite'));db.exec('CREATE TABLE sessions(hash TEXT PRIMARY KEY,userId TEXT NOT NULL,expires INTEGER NOT NULL,renewedAt INTEGER NOT NULL)');db.prepare('INSERT INTO sessions VALUES(?,?,?,?)').run(crypto.createHash('sha256').update(token).digest('hex'),user.id,Date.now()+86400000,Date.now());db.close();
|
||||
const server=createDashboard({store,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(async()=>{server.closeAllConnections();await new Promise(r=>server.close(r));fs.rmSync(dir,{recursive:true,force:true});});
|
||||
const base='http://127.0.0.1:'+server.address().port,cookie='order_session='+token;
|
||||
assert.equal((await fetch(base+'/api/me',{headers:{Cookie:cookie}})).status,200);
|
||||
const updated=await fetch(base+'/api/account/password',{method:'POST',headers:{Origin:base,'Content-Type':'application/json',Cookie:cookie},body:JSON.stringify(input())});assert.equal(updated.status,200);assert.equal((await fetch(base+'/api/me',{headers:{Cookie:cookie}})).status,401);
|
||||
});
|
||||
|
||||
test('a delayed password response never clears or renews over a later login cookie',async t=>{
|
||||
let arrived,release;const entered=new Promise(r=>arrived=r),gate=new Promise(r=>release=r);
|
||||
const f=await fixture(t,{bpmSessions:{async releaseSessionHashes(){arrived();await gate;}}}),cookie=await f.login();
|
||||
const {DatabaseSync}=require('node:sqlite');const db=new DatabaseSync(path.join(f.dir,'auth.sqlite'));db.prepare('UPDATE sessions SET renewedAt=?').run(Date.now()-2*86400000);db.close();
|
||||
const pending=f.call('/api/account/password',input(),cookie);await entered;
|
||||
try{const fresh=await f.login('viewer');release();const result=await pending;assert.equal(result.status,200);assert.equal(result.headers.get('set-cookie'),null,'late credential response must not overwrite a newer browser login');assert.equal((await f.call('/api/me',undefined,fresh)).status,200);}finally{release();}
|
||||
});
|
||||
test('revoked BPM principals queued before lease creation cannot open a new login window',async()=>{
|
||||
const crypto=require('node:crypto'),{BpmSessionManager}=require('../../src/modules/bpm/session-manager.cjs');
|
||||
const manager=new BpmSessionManager({stateDir:os.tmpdir()}),principal={sessionId:'revoked-token',user:{id:'a',username:'admin',role:'admin'}},connection={id:'queued',status:'disconnected'};
|
||||
let release;const gate=new Promise(r=>release=r);const blocker=manager.run(connection.id,()=>gate);
|
||||
manager.create=async(connection,principal)=>{manager.authorize(connection,principal);const lease={id:connection.id,sessionId:principal.sessionId,expiresAt:Date.now()+10000,page:{url:()=> 'https://bpmn.skyworthdigital.com/'}};manager.sessions.set(connection.id,lease);return lease;};
|
||||
const opening=assert.rejects(manager.open(connection,principal),e=>e.status===401);
|
||||
try{await manager.releaseSessionHashes([crypto.createHash('sha256').update(principal.sessionId).digest('hex')]);}finally{release();}
|
||||
await blocker;await opening;assert.equal(manager.sessions.size,0);assert.throws(()=>manager.authorize(connection,principal),e=>e.status===401);
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
|
||||
const {Store}=require('../../src/modules/dashboard/store.cjs'),{createDashboard}=require('../../src/app/dashboard.cjs'),{loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
|
||||
const OLD='Test-password-123',NEW='Changed-password-456';
|
||||
test('account UI lets every role change passwords, validates confirmation, and gives admins a member reset form',{timeout:90000},async t=>{
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'account-ui-')),store=new Store(dir);const admin=store.bootstrap('admin',OLD),viewer=store.addUser({username:'viewer',password:OLD,role:'viewer'},'admin');store.addUser({username:'operator',password:OLD,role:'operator'},'admin');
|
||||
const server=createDashboard({store,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));const base='http://127.0.0.1:'+server.address().port;let browser;
|
||||
t.after(async()=>{await browser?.close();server.closeAllConnections();await new Promise(r=>server.close(r));fs.rmSync(dir,{recursive:true,force:true});});browser=await loadPlaywright().chromium.launch(browserOptions());const errors=[];
|
||||
const login=async(page,username,password=OLD)=>{await page.getByLabel('账号',{exact:true}).fill(username);await page.getByLabel('密码',{exact:true}).fill(password);await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('link',{name:'修改密码',exact:true}).waitFor({timeout:5000});};
|
||||
const page=await browser.newPage({viewport:{width:1440,height:1000}});page.on('pageerror',e=>errors.push(e.message));await page.goto(base+'/#users');await login(page,'admin');
|
||||
assert.equal(await page.locator('[data-reset-user="'+admin.id+'"]').count(),0);await page.locator('[data-reset-user="'+viewer.id+'"]').click();
|
||||
await page.getByLabel('管理员当前密码',{exact:true}).fill(OLD);await page.getByLabel('成员新密码',{exact:true}).fill(NEW);await page.getByLabel('确认成员新密码',{exact:true}).fill(NEW);await page.getByRole('button',{name:'确认重置密码',exact:true}).click();await page.getByText('成员密码已重置,该账号需要重新登录。',{exact:true}).waitFor();assert.ok(store.authenticate('viewer',NEW));assert.equal(await page.locator('#password-reset-form').count(),0);
|
||||
// The separate create-user flow remains usable after introducing reset controls.
|
||||
await page.getByLabel('登录账号',{exact:true}).fill('new-member');await page.getByLabel('初始密码',{exact:true}).fill(OLD);await page.getByRole('button',{name:'创建账号',exact:true}).click();await page.getByText('new-member',{exact:true}).waitFor();
|
||||
for(const [username,password]of [['admin',OLD],['operator',OLD],['viewer',NEW]]){
|
||||
const account=username==='admin'?page:await browser.newPage();if(account!==page){account.on('pageerror',e=>errors.push(e.message));await account.goto(base+'/#account');await login(account,username,password);}
|
||||
await account.getByRole('link',{name:'修改密码',exact:true}).click();await account.getByLabel('当前密码',{exact:true}).fill('incorrect');await account.getByLabel('新密码',{exact:true}).fill('Final-password-789');await account.getByLabel('确认新密码',{exact:true}).fill('different-password-789');await account.getByRole('button',{name:'保存新密码',exact:true}).click();await account.getByText('两次输入的新密码不一致。',{exact:true}).waitFor();
|
||||
await account.getByLabel('确认新密码',{exact:true}).fill('Final-password-789');await account.getByRole('button',{name:'保存新密码',exact:true}).click();await account.getByText('当前密码不正确。',{exact:true}).waitFor();assert.equal(await account.getByLabel('新密码',{exact:true}).inputValue(),'Final-password-789');
|
||||
await account.getByLabel('当前密码',{exact:true}).fill(password);
|
||||
if(username==='admin'){await account.setViewportSize({width:390,height:844});assert.equal(await account.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await fs.promises.mkdir(path.resolve('output/verification'),{recursive:true});await account.screenshot({path:path.resolve('output/verification/account-password-mobile.png'),fullPage:true});await account.setViewportSize({width:1440,height:1000});}
|
||||
let release,arrived;const pending=new Promise(r=>arrived=r);
|
||||
if(username==='operator')await account.route('**/api/account/password',async route=>{arrived();await new Promise(r=>release=r);await route.continue();},{times:1});
|
||||
await account.getByRole('button',{name:'保存新密码',exact:true}).click();
|
||||
if(username==='operator'){await pending;await account.getByRole('link',{name:'操作记录',exact:true}).click();release();}
|
||||
await account.getByRole('heading',{name:'登录工作台',exact:true}).waitFor({timeout:5000});await account.getByText('密码已修改,请使用新密码重新登录。',{exact:true}).waitFor();await login(account,username,'Final-password-789');assert.ok(store.authenticate(username,'Final-password-789'));
|
||||
}
|
||||
assert.deepEqual(errors,[]);
|
||||
});
|
||||
Reference in new issue
Block a user