'use strict'; const {test}=require('node:test'); const assert=require('node:assert/strict'); const fs=require('node:fs/promises'); const os=require('node:os'); const path=require('node:path'); const http=require('node:http'); const {BpmSessionManager}=require('../../src/modules/bpm/session-manager.cjs'); const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'); const principal={user:{username:'owner',role:'operator'},sessionId:'session-one'}; const connection={id:'account-test',owner:'owner',status:'disconnected'}; const credentials={username:'Fixture User',password:' Fixture-password-123 '}; const empty={configured:false,username:'',updatedAt:null}; test('account availability enforces scope and duplicate saves preserve old credentials and cookies',async t=>{ const {manager}=await fixture(t);const other={...connection,id:'other'}; await manager.saveAccount(connection,principal,credentials); await manager.saveAccount(other,principal,{username:'different',password:'original-password'}); await manager.vault().write(other.id,{storageState:{cookies:[{name:'keep',value:'unchanged'}],origins:[]}}); assert.deepEqual(await manager.checkAccount(other,principal,{username:' fixture USER '}),{available:false}); await assert.rejects(manager.saveAccount(other,principal,{username:'fixture user',password:'replacement'}),e=>e.status===409&&e.code==='BPM_ACCOUNT_DUPLICATE'); assert.equal((await manager.account(other,principal)).username,'different');assert.ok(await manager.vault().read(other.id)); for(const user of [{username:'unrelated',role:'operator'},{username:'owner',role:'viewer'}])await assert.rejects(manager.checkAccount(other,{...principal,user},{username:'anything'}),e=>e.status===403); for(const body of [null,{},[],{username:' '},{username:'x',password:'secret'}])await assert.rejects(manager.checkAccount(other,principal,body),e=>e.status===400); }); async function fixture(t,{browser=false,known=true}={}){ const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-account-')); const server=http.createServer((req,res)=>{ const type=req.url==='/malicious'?'text':'password'; const hidden=req.url==='/hidden'?'style="display:none"':''; res.setHeader('content-type','text/html'); res.end(`
`); }); await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve)); const origin='http://127.0.0.1:'+server.address().port; const options={stateDir:dir,urls:{main:origin+'/login'},allowedOrigins:[origin],...(known?{loginForms:{[origin]:{username:'#username',password:'#password'}}}:{})}; if(browser)options.browserFactory=async()=>loadPlaywright().chromium.launch(browserOptions()); else options.browserFactory=async()=>{throw new Error('browser must not launch for account CRUD');}; const manager=new BpmSessionManager(options); const managers=[manager],make=()=>{const next=new BpmSessionManager(options);managers.push(next);return next;}; t.after(async()=>{for(const item of managers)await item.shutdown();server.closeAllConnections();await new Promise(resolve=>server.close(resolve));await fs.rm(dir,{recursive:true,force:true});}); return {manager,dir,options,origin,make}; } test('account saves encrypted credentials without browser, returns safe metadata and survives restart',async t=>{ const {manager,dir,make}=await fixture(t); assert.deepEqual(await manager.account(connection,principal),empty); const saved=await manager.saveAccount(connection,principal,credentials); assert.equal(saved.configured,true);assert.equal(saved.username,'Fixture User');assert.ok(Date.parse(saved.updatedAt)); assert.deepEqual(Object.keys(saved).sort(),['configured','updatedAt','username']); assert.equal((await manager.vault().read('account:account-test')).password,credentials.password); assert.equal(await manager.vault().read(connection.id),null); for(const filename of await fs.readdir(dir))if(filename.endsWith('.enc')||filename.includes('.sqlite')){ const bytes=await fs.readFile(path.join(dir,filename)); assert.equal(bytes.includes(Buffer.from(credentials.username)),false);assert.equal(bytes.includes(Buffer.from(credentials.password)),false); } await manager.shutdown();const restarted=make(); assert.deepEqual(await restarted.account(connection,principal),saved); assert.deepEqual(await restarted.clearAccount(connection,principal),empty); assert.equal(await restarted.vault().read('account:account-test'),null); }); test('account enforces owner and admin, strict payload bounds and disabled deletion',async t=>{ const {manager}=await fixture(t); for(const user of [{username:'other',role:'operator'},{username:'owner',role:'viewer'}])for(const method of ['account','saveAccount','clearAccount','fillAccount'])await assert.rejects(manager[method](connection,{...principal,user},credentials),e=>e.status===403); for(const body of [null,[],{}, {...credentials,extra:true},{...credentials,username:' '},{...credentials,username:'x'.repeat(151)},{...credentials,password:''},{...credentials,password:'x'.repeat(257)}])await assert.rejects(manager.saveAccount(connection,principal,body),e=>e.status===400); const admin={...principal,user:{username:'admin',role:'admin'}}; await manager.saveAccount(connection,admin,credentials);assert.equal((await manager.account(connection,principal)).configured,true); await manager.vault().write(connection.id,{storageState:{cookies:[],origins:[]}}); await manager.disable(connection.id); assert.equal(await manager.vault().read(connection.id),null);assert.equal(await manager.vault().read('account:account-test'),null); await assert.rejects(manager.account(connection,principal),e=>e.status===409); }); test('saved account fills real known form on open and navigate without submission, captcha changes or field writeback',async t=>{ const {manager,make}=await fixture(t,{browser:true}); await manager.saveAccount(connection,principal,credentials);await manager.shutdown(); const restarted=make(); await restarted.open(connection,principal);const page=restarted.sessions.get(connection.id).page; assert.equal(await page.locator('#username').inputValue(),credentials.username);assert.equal(await page.locator('#password').inputValue(),credentials.password); assert.equal(await page.locator('#captcha').inputValue(),'');assert.equal(await page.evaluate(()=>window.submitted),0); await page.locator('#password').fill('Browser edit');assert.equal((await restarted.vault().read('account:account-test')).password,credentials.password); await restarted.navigate(connection.id,principal,{target:'main'});assert.equal(await page.locator('#password').inputValue(),credentials.password); assert.equal((await restarted.fillAccount(connection,principal)).filled,true); assert.equal(await page.evaluate(()=>window.submitted),0); await assert.rejects(restarted.fillAccount(connection,{...principal,sessionId:'second-session'}),e=>e.status===409); await restarted.clearAccount(connection,principal);const absent=await restarted.fillAccount(connection,principal);assert.equal(absent.filled,false);assert.match(absent.message,/托管|保存/); }); test('unknown origins and unsafe or hidden form fields never receive any saved credentials',async t=>{ const unknown=await fixture(t,{browser:true,known:false});await unknown.manager.saveAccount(connection,principal,credentials);await unknown.manager.open(connection,principal); const unknownPage=unknown.manager.sessions.get(connection.id).page;assert.equal(await unknownPage.locator('#username').inputValue(),'');assert.equal(await unknownPage.locator('#password').inputValue(),''); assert.equal((await unknown.manager.fillAccount(connection,principal)).filled,false);assert.equal(await unknownPage.evaluate(()=>window.submitted),0); const known=await fixture(t,{browser:true});await known.manager.saveAccount(connection,principal,credentials);await known.manager.open(connection,principal);const page=known.manager.sessions.get(connection.id).page; for(const target of ['/malicious','/hidden']){await page.goto(known.origin+target);assert.equal((await known.manager.fillAccount(connection,principal)).filled,false);assert.equal(await page.locator('#username').inputValue(),'');assert.equal(await page.locator('#password').inputValue(),'');assert.equal(await page.evaluate(()=>window.submitted),0);} await assert.rejects(known.manager.fillAccount({...connection,id:'unopened'},principal),e=>e.status===410); }); test('saving a managed account invalidates previous authentication and refuses another dashboard lease',async t=>{ const {manager}=await fixture(t,{browser:true}); await manager.saveAccount(connection,principal,credentials); await manager.vault().write(connection.id,{storageState:{cookies:[],origins:[]},sessionStorage:{old:'authentication'}}); await manager.open(connection,principal); await manager.saveAccount(connection,principal,{...credentials,password:'Updated password'}); assert.ok(await manager.vault().read(connection.id));assert.equal(manager.sessions.has(connection.id),true); await assert.rejects(manager.saveAccount(connection,{...principal,sessionId:'other-session'},{username:'New User',password:'New password'}),e=>e.status===409); assert.equal((await manager.account(connection,principal)).username,credentials.username); assert.ok(await manager.vault().read(connection.id)); await assert.rejects(manager.saveAccount(connection,principal,{username:'New User',password:''}),e=>e.status===400); assert.ok(await manager.vault().read(connection.id));assert.equal(manager.sessions.has(connection.id),true); await manager.saveAccount(connection,principal,{username:'New User',password:'New password'}); assert.equal(await manager.vault().read(connection.id),null);assert.equal(manager.sessions.has(connection.id),false); assert.equal((await manager.account(connection,principal)).username,'New User'); }); async function automaticFixture(t,{challenge=false,wrong=false,unknown=false,unsafe=false,portalFailure=false,getSubmit=false}={}){ const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-automatic-'));let submissions=0,verificationMode=''; const server=http.createServer((req,res)=>{ res.setHeader('content-type','text/html'); if(req.url.startsWith('/authenticate') && req.method!=='POST'){submissions++;res.end('Unsafe GET submission');return;} if(req.url==='/authenticate' && req.method==='POST'){ submissions++;let body='';req.on('data',chunk=>body+=chunk);req.on('end',()=>{ const params=new URLSearchParams(body);if(!wrong && params.get('username')===credentials.username && params.get('password')===credentials.password)res.setHeader('Set-Cookie','auth=valid; HttpOnly; Path=/'); res.writeHead(302,{Location:'/main'});res.end(); });return; } if((req.headers.cookie||'').includes('auth=valid'))res.end('