From 607b240aa3ede1387dd327ef75d5ee2148059f25 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E9=98=BF=E7=99=BD=E5=8F=94?=
<11794527+absfan@user.noreply.gitee.com>
Date: Sat, 17 Oct 2026 18:57:43 +0800
Subject: [PATCH] fix(bpm): persist encrypted sessions without file renames
---
src/bpm-session-manager.cjs | 14 ++++++++++---
src/bpm-vault.cjs | 22 +++++++++++++------
tests/bpm-account.test.cjs | 6 +++---
tests/bpm-session.test.cjs | 15 +++++++++++++
tests/bpm-vault.test.cjs | 42 +++++++++++++++++++++++++++++--------
5 files changed, 78 insertions(+), 21 deletions(-)
diff --git a/src/bpm-session-manager.cjs b/src/bpm-session-manager.cjs
index 38acce2..51d4b6f 100644
--- a/src/bpm-session-manager.cjs
+++ b/src/bpm-session-manager.cjs
@@ -264,11 +264,16 @@ class BpmSessionManager {
};
lease.network.on('Page.frameRequestedNavigation',started);
lease.network.on('Page.frameStartedLoading',started);
- lease.network.on('Page.frameStoppedLoading',event=>{
+ const finished=event=>{
if (event.frameId!==lease.mainFrameId) return;
lease.finishNavigation?.(); lease.pendingNavigation=null; lease.finishNavigation=null;
- });
+ };
+ lease.network.on('Page.frameStoppedLoading',finished);
+ // Portal images/widgets can stall after its document is ready. Login
+ // verification needs the committed document, not every subresource.
+ lease.network.on('Page.lifecycleEvent',event=>{if(event.name==='DOMContentLoaded')finished(event);});
await lease.network.send('Page.enable');
+ await lease.network.send('Page.setLifecycleEventsEnabled',{enabled:true});
lease.network.on('Fetch.requestPaused', async event => {
try {
if (this.allowed(event.request.url)) await lease.network.send('Fetch.continueRequest',{requestId:event.requestId});
@@ -327,8 +332,11 @@ class BpmSessionManager {
});
}
async defaultProbe(page) {
+ // A visible company SSO form is an explicit login state. The authenticated
+ // portal renders its user menu asynchronously after DOMContentLoaded.
+ if(new URL(page.url()).origin==='https://sso.skyworthdigital.com' && await page.locator('#kc-form-login').isVisible().catch(()=>false))return {ok:false};
const marker=page.locator('a.yz-btn-signinuser .x-btn-inner').first();
- await marker.waitFor({state:'visible',timeout:4000}).catch(()=>{});
+ await marker.waitFor({state:'visible',timeout:15000}).catch(()=>{});
if (!await marker.isVisible().catch(()=>false)) return {ok:false};
const identity=(await marker.innerText()).trim();
return {ok:!!identity && !/^(登录|请登录|未登录|sign\s*in|login)$/i.test(identity),identity};
diff --git a/src/bpm-vault.cjs b/src/bpm-vault.cjs
index 027fa3e..f9ce331 100644
--- a/src/bpm-vault.cjs
+++ b/src/bpm-vault.cjs
@@ -62,7 +62,8 @@ class BpmVault {
if(this.db)return this.db;
const db=new DatabaseSync(path.join(this.stateDir,'accounts.sqlite'));
try{db.exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA secure_delete=ON;
- CREATE TABLE IF NOT EXISTS accounts(connection_id TEXT PRIMARY KEY,username_key TEXT NOT NULL UNIQUE,payload BLOB NOT NULL);`);this.db=db;return db;}
+ CREATE TABLE IF NOT EXISTS accounts(connection_id TEXT PRIMARY KEY,username_key TEXT NOT NULL UNIQUE,payload BLOB NOT NULL);
+ CREATE TABLE IF NOT EXISTS sessions(connection_id TEXT PRIMARY KEY,payload BLOB NOT NULL);`);this.db=db;return db;}
catch{db.close();throw fail();}
}
accountKey(username) {
@@ -103,21 +104,30 @@ class BpmVault {
const filename = this.filename(id);
try {
if(id.startsWith('account:')){const row=this.accounts().prepare('SELECT payload FROM accounts WHERE connection_id=?').get(id.slice(8));if(row)return this.decode(id,row.payload);}
+ else{const row=this.accounts().prepare('SELECT payload FROM sessions WHERE connection_id=?').get(id);if(row)return this.decode(id,row.payload);}
const state=this.decode(id,await fsp.readFile(filename));
if(id.startsWith('account:')){this.putAccount(id,state);await fsp.rm(filename,{force:true});}
+ else{
+ // Commit legacy ciphertext before removing its file. An existing database
+ // session is authoritative if another process completed migration first.
+ this.accounts().prepare('INSERT OR IGNORE INTO sessions(connection_id,payload) VALUES(?,?)').run(id,this.encode(id,state));
+ const saved=this.decode(id,this.accounts().prepare('SELECT payload FROM sessions WHERE connection_id=?').get(id).payload);
+ await fsp.rm(filename,{force:true});return saved;
+ }
return state;
} catch (error) { if (error.code === 'ENOENT') return null;if(error.code==='BPM_ACCOUNT_DUPLICATE')throw error;throw fail(); }
}
async write(id, state) {
- const filename = this.filename(id), temp = filename + '.' + crypto.randomUUID() + '.tmp';
+ const filename = this.filename(id);
if(id.startsWith('account:')){this.putAccount(id,state);await fsp.rm(filename,{force:true}).catch(()=>{});return;}
try {
- await fsp.writeFile(temp, this.encode(id,state), { flag: 'wx', mode: 0o600 });
- await fsp.rename(temp, filename);
+ // Some Windows state directories reject even same-directory renames with
+ // EXDEV. SQLite publishes the encrypted payload in one atomic transaction.
+ this.accounts().prepare('INSERT INTO sessions(connection_id,payload) VALUES(?,?) ON CONFLICT(connection_id) DO UPDATE SET payload=excluded.payload').run(id,this.encode(id,state));
+ await fsp.rm(filename,{force:true}).catch(()=>{});
} catch { throw fail(); }
- finally { await fsp.rm(temp, { force: true }).catch(() => {}); }
}
- async remove(id) { try { await fsp.rm(this.filename(id), { force: true });if(id.startsWith('account:'))this.accounts().prepare('DELETE FROM accounts WHERE connection_id=?').run(id.slice(8)); } catch { throw fail(); } }
+ async remove(id) { try { await fsp.rm(this.filename(id), { force: true });if(id.startsWith('account:'))this.accounts().prepare('DELETE FROM accounts WHERE connection_id=?').run(id.slice(8));else this.accounts().prepare('DELETE FROM sessions WHERE connection_id=?').run(id); } catch { throw fail(); } }
destroy() { this.db?.close();this.db=null;this.key?.fill(0);this.key=null; }
}
module.exports = { BpmVault };
diff --git a/tests/bpm-account.test.cjs b/tests/bpm-account.test.cjs
index c2a3894..a1f2d36 100644
--- a/tests/bpm-account.test.cjs
+++ b/tests/bpm-account.test.cjs
@@ -48,7 +48,7 @@ test('account saves encrypted credentials without browser, returns safe metadata
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')){
+ 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);
}
@@ -177,7 +177,7 @@ test('new portal authentication is sufficient for connected checks and cookie re
});
test('network uncertainty preserves the prior good encrypted snapshot without another login attempt',async t=>{
const {manager,submissions,setVerificationMode}=await automaticFixture(t);await manager.saveAccount(connection,principal,credentials);await manager.ensure(connection,principal);
- const filename=manager.vault().filename(connection.id),lastGood=await fs.readFile(filename);
+ const payload=()=>Buffer.from(manager.vault().accounts().prepare('SELECT payload FROM sessions WHERE connection_id=?').get(connection.id).payload),lastGood=payload();
setVerificationMode('network');const checked=await manager.ensure(connection,principal);assert.equal(checked.status,'error');assert.equal(checked.checks.portal.ok,false);
- assert.deepEqual(await fs.readFile(filename),lastGood);assert.equal(submissions(),1);
+ assert.deepEqual(payload(),lastGood);assert.equal(submissions(),1);
});
diff --git a/tests/bpm-session.test.cjs b/tests/bpm-session.test.cjs
index 478aa95..49b2fcd 100644
--- a/tests/bpm-session.test.cjs
+++ b/tests/bpm-session.test.cjs
@@ -159,3 +159,18 @@ test('immediate save after remote login Enter waits for pending login navigation
await manager.input('a',principal,{type:'key',key:'Enter'});
assert.equal((await manager.save(connection,principal)).status,'connected');
});
+
+test('login verification waits for the document but does not wait for a stalled portal image',async t=>{
+ const {manager,origin}=await fixture(t);await manager.open(connection,principal);const lease=manager.sessions.get('a');
+ let release;const pending=new Promise(resolve=>{release=resolve;});
+ await lease.page.route(origin+'/pending-image',async route=>{await pending;await route.fulfill({status:204}).catch(()=>{});});
+ await lease.page.route(origin+'/main',route=>route.fulfill({contentType:'text/html',body:'Fixture User
'}));
+ try{await lease.page.goto(origin+'/main',{waitUntil:'domcontentloaded'});assert.equal((await manager.save(connection,principal)).status,'connected');}
+ finally{release();}
+});
+
+test('portal identity rendered after four seconds is recognized as logged in',async t=>{
+ const {manager}=await fixture(t);await manager.open(connection,principal);const page=manager.sessions.get('a').page;
+ await page.setContent('Loading');
+ assert.deepEqual(await manager.defaultProbe(page),{ok:true,identity:'Fixture User'});
+});
diff --git a/tests/bpm-vault.test.cjs b/tests/bpm-vault.test.cjs
index 2757e0d..1084de1 100644
--- a/tests/bpm-vault.test.cjs
+++ b/tests/bpm-vault.test.cjs
@@ -4,6 +4,19 @@ const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
+test('session updates remain atomic when the state directory rejects file renames',async t=>{
+ const {BpmVault}=require('../src/bpm-vault.cjs');
+ const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-session-rename-'));
+ const vault=new BpmVault({stateDir:dir});
+ t.after(async()=>{vault.destroy();await fs.rm(dir,{recursive:true,force:true});});
+ t.mock.method(fs,'rename',async()=>{throw Object.assign(new Error('cross device rename'),{code:'EXDEV'});});
+ await vault.write('session',{storageState:{cookies:[]},sessionStorage:{test:{value:'private-session-state'}}});
+ await vault.write('session',{storageState:{cookies:[]},sessionStorage:{test:{value:'updated-session-state'}}});
+ vault.destroy();const restarted=new BpmVault({stateDir:dir});
+ try{assert.equal((await restarted.read('session')).sessionStorage.test.value,'updated-session-state');}finally{restarted.destroy();}
+ for(const filename of await fs.readdir(dir)){const bytes=await fs.readFile(path.join(dir,filename));assert.equal(bytes.includes(Buffer.from('updated-session-state')),false);assert.equal(filename.endsWith('.tmp'),false);}
+});
+
test('managed accounts use an encrypted SQLite registry with uniqueness across connections and restarts',async t=>{
const {BpmVault}=require('../src/bpm-vault.cjs');
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-accounts-db-'));
@@ -52,18 +65,17 @@ test('legacy encrypted account files migrate atomically and conflicting legacy f
test('vault encrypts state, survives restart, rejects corruption and keeps connection isolation', async t => {
const { BpmVault } = require('../src/bpm-vault.cjs');
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'bpm-vault-'));
- t.after(() => fs.rm(dir, { recursive: true, force: true }));
const vault = new BpmVault({ stateDir: dir });
+ t.after(async()=>{vault.destroy();await fs.rm(dir,{recursive:true,force:true});});
const state = { cookies: [{ name: 'session', value: 'private-cookie-value' }], sessionStorage: { 'https://bpm.example': { account: 'secret-user' } } };
await vault.write('connection-a', state);
- assert.deepEqual(await new BpmVault({ stateDir: dir }).read('connection-a'), state);
+ const restored=new BpmVault({stateDir:dir});try{assert.deepEqual(await restored.read('connection-a'),state);}finally{restored.destroy();}
assert.equal(await vault.read('connection-b'), null);
- const filename = (await fs.readdir(dir)).find(file => file.endsWith('.enc'));
- const encrypted = await fs.readFile(path.join(dir, filename));
+ const encrypted=Buffer.from(vault.accounts().prepare('SELECT payload FROM sessions WHERE connection_id=?').get('connection-a').payload);
assert.equal(encrypted.includes(Buffer.from('private-cookie-value')), false);
assert.equal(encrypted.includes(Buffer.from('secret-user')), false);
encrypted[encrypted.length - 1] ^= 1;
- await fs.writeFile(path.join(dir, filename), encrypted);
+ vault.accounts().prepare('UPDATE sessions SET payload=? WHERE connection_id=?').run(encrypted,'connection-a');
await assert.rejects(vault.read('connection-a'), error => error.status === 503 && !error.message.includes('private-cookie'));
await vault.remove('connection-a');
assert.equal(await vault.read('connection-a'), null);
@@ -72,13 +84,25 @@ test('vault encrypts state, survives restart, rejects corruption and keeps conne
test('vault binds ciphertext to connection identity and never leaves plaintext temporary files', async t => {
const { BpmVault } = require('../src/bpm-vault.cjs');
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'bpm-vault-'));
- t.after(() => fs.rm(dir, { recursive: true, force: true }));
const vault = new BpmVault({ stateDir: dir });
+ t.after(async()=>{vault.destroy();await fs.rm(dir,{recursive:true,force:true});});
await vault.write('a', { secret: 'alpha' });
await vault.write('b', { secret: 'bravo' });
- const crypto = require('node:crypto');
- const filename = id => path.join(dir, crypto.createHash('sha256').update(id).digest('hex') + '.enc');
- await fs.copyFile(filename('a'), filename('b'));
+ const encrypted=vault.accounts().prepare('SELECT payload FROM sessions WHERE connection_id=?').get('a').payload;
+ vault.accounts().prepare('UPDATE sessions SET payload=? WHERE connection_id=?').run(encrypted,'b');
await assert.rejects(vault.read('b'), error => error.status === 503);
assert.equal((await fs.readdir(dir)).some(file => file.endsWith('.tmp')), false);
});
+
+test('legacy session ciphertext migrates, database state wins, and removal cannot restore a stale file',async t=>{
+ const {BpmVault}=require('../src/bpm-vault.cjs'),dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-legacy-session-')),vault=new BpmVault({stateDir:dir});
+ t.after(async()=>{vault.destroy();await fs.rm(dir,{recursive:true,force:true});});
+ const old={storageState:{cookies:[]},sessionStorage:{portal:{token:'legacy-private-token'}}};
+ await fs.writeFile(vault.filename('legacy'),vault.encode('legacy',old));
+ assert.deepEqual(await vault.read('legacy'),old);await assert.rejects(fs.stat(vault.filename('legacy')),e=>e.code==='ENOENT');
+ const restarted=new BpmVault({stateDir:dir});try{assert.deepEqual(await restarted.read('legacy'),old);}finally{restarted.destroy();}
+ const current={storageState:{cookies:[]},sessionStorage:{portal:{token:'current-private-token'}}};await vault.write('legacy',current);
+ await fs.writeFile(vault.filename('legacy'),vault.encode('legacy',old));assert.deepEqual(await vault.read('legacy'),current);
+ await vault.remove('legacy');assert.equal(await vault.read('legacy'),null);await assert.rejects(fs.stat(vault.filename('legacy')),e=>e.code==='ENOENT');
+ await fs.writeFile(vault.filename('broken'),Buffer.from('corrupted legacy ciphertext'));await assert.rejects(vault.read('broken'),e=>e.status===503);assert.equal(vault.accounts().prepare('SELECT count(*) AS n FROM sessions WHERE connection_id=?').get('broken').n,0);assert.equal((await fs.stat(vault.filename('broken'))).isFile(),true);
+});