Files
order-notification-automation/tests/app/account-password.test.cjs
T

84 lines
10 KiB
JavaScript

'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);
});