fix: reconcile BPM sources and retain safe storage diagnostics
This commit is contained in:
1 parent
7e42a6dcc6
commit
33e9e9c108
9 files changed
+179
-40
No files matched your search
@@ -5,9 +5,11 @@ const path = require('node:path');
|
||||
const crypto = require('node:crypto');
|
||||
const { execFileSync } = require('node:child_process');
|
||||
const { DatabaseSync } = require('node:sqlite');
|
||||
const fail = () => Object.assign(new Error('BPM 会话存储不可用,请重新登录或联系管理员。'), { status: 503 });
|
||||
const fail = (cause,stage) => cause?.code==='STORAGE_UNAVAILABLE'&&!stage?cause:Object.assign(new Error('加密存储暂时不可用,请查看系统诊断。',cause?{cause}:undefined), { status: 503,code:'STORAGE_UNAVAILABLE',stage:stage||'db_read' });
|
||||
const duplicate = () => Object.assign(new Error('该 BPM 账号已开启自动续登,请使用已有连接或先解除原账号托管。'), { status: 409, code: 'BPM_ACCOUNT_DUPLICATE' });
|
||||
const digest = value => crypto.createHash('sha256').update(value).digest('hex');
|
||||
const securedDirectories=new Map();
|
||||
function directoryIdentity(dir){const info=fs.lstatSync(dir,{bigint:true});if(!info.isDirectory()||info.isSymbolicLink())throw Object.assign(Error('Storage directory must be a real directory'),{code:'ESTORAGEPATH'});return [info.dev,info.ino,info.birthtimeNs].join(':');}
|
||||
|
||||
function powershell(script, input) {
|
||||
const utf8='[Console]::InputEncoding=New-Object System.Text.UTF8Encoding; [Console]::OutputEncoding=New-Object System.Text.UTF8Encoding; ';
|
||||
@@ -18,7 +20,11 @@ function powershell(script, input) {
|
||||
function secureDirectory(dir) {
|
||||
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
if (process.platform === 'win32') {
|
||||
const key=path.resolve(dir).toLowerCase(),identity=directoryIdentity(dir);
|
||||
if(securedDirectories.get(key)===identity)return;
|
||||
powershell('$ErrorActionPreference="Stop"; $p=[Console]::In.ReadToEnd(); $s=[System.Security.Principal.WindowsIdentity]::GetCurrent().User; $a=New-Object System.Security.AccessControl.DirectorySecurity; $a.SetAccessRuleProtection($true,$false); $a.SetOwner($s); $r=New-Object System.Security.AccessControl.FileSystemAccessRule($s,"FullControl","ContainerInherit,ObjectInherit","None","Allow"); $a.AddAccessRule($r); [System.IO.Directory]::SetAccessControl($p,$a)', dir);
|
||||
if(directoryIdentity(dir)!==identity)throw Object.assign(Error('Storage directory changed during protection'),{code:'ESTORAGECHANGED'});
|
||||
securedDirectories.set(key,identity);if(securedDirectories.size>512)securedDirectories.delete(securedDirectories.keys().next().value);
|
||||
} else fs.chmodSync(dir, 0o700);
|
||||
}
|
||||
function dpapi(value, decrypt = false) {
|
||||
@@ -31,10 +37,11 @@ class BpmVault {
|
||||
try {
|
||||
this.stateDir = path.resolve(stateDir);
|
||||
secureDirectory(this.stateDir);
|
||||
} catch { throw fail(); }
|
||||
} catch(cause) { throw fail(cause,'directory_permissions'); }
|
||||
}
|
||||
ensureKey() {
|
||||
if (this.key) return this.key;
|
||||
let stage='key_directory';
|
||||
try {
|
||||
// The key always stays on the service user's local disk, even when project code is on a shared drive.
|
||||
const keyDir = process.platform === 'win32'
|
||||
@@ -43,17 +50,17 @@ class BpmVault {
|
||||
secureDirectory(keyDir);
|
||||
const keyFile = path.join(keyDir, digest(this.stateDir.toLowerCase()) + '.key');
|
||||
if (!fs.existsSync(keyFile)) {
|
||||
stage='key_create';
|
||||
const raw = crypto.randomBytes(32);
|
||||
const protectedKey = process.platform === 'win32' ? dpapi(raw) : raw;
|
||||
try { fs.writeFileSync(keyFile, protectedKey, { flag: 'wx', mode: 0o600 }); }
|
||||
catch (error) { if (error.code !== 'EEXIST') throw error; }
|
||||
try {stage='key_protect';const protectedKey = process.platform === 'win32' ? dpapi(raw) : raw;stage='key_write';try{fs.writeFileSync(keyFile, protectedKey, { flag: 'wx', mode: 0o600 });}catch(error){if(error.code!=='EEXIST')throw error;}}
|
||||
finally { raw.fill(0); }
|
||||
}
|
||||
const protectedKey = fs.readFileSync(keyFile);
|
||||
stage='key_read';const protectedKey = fs.readFileSync(keyFile);
|
||||
stage='key_unprotect';
|
||||
this.key = process.platform === 'win32' ? dpapi(protectedKey, true) : protectedKey;
|
||||
if (this.key.length !== 32) throw fail();
|
||||
stage='key_length';if (this.key.length !== 32) throw Object.assign(Error('Invalid key length'),{code:'ESTORAGEKEY'});
|
||||
return this.key;
|
||||
} catch { throw fail(); }
|
||||
} catch(cause) { this.key?.fill(0);this.key=null;throw fail(cause,stage); }
|
||||
}
|
||||
filename(id) {
|
||||
if (typeof id !== 'string' || !id || id.length > 200) throw Object.assign(new Error('连接标识无效。'), { status: 400 });
|
||||
@@ -65,7 +72,7 @@ class BpmVault {
|
||||
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);
|
||||
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();}
|
||||
catch(cause){db.close();throw fail(cause,'db_open');}
|
||||
}
|
||||
accountKey(username) {
|
||||
if(typeof username!=='string'||!username.trim()||username.length>150)throw Object.assign(new Error('请输入有效的 BPM 账号。'),{status:400});
|
||||
@@ -85,11 +92,11 @@ class BpmVault {
|
||||
}
|
||||
putAccount(id,state) {
|
||||
try{this.accounts().prepare('INSERT INTO accounts(connection_id,username_key,payload) VALUES(?,?,?) ON CONFLICT(connection_id) DO UPDATE SET username_key=excluded.username_key,payload=excluded.payload').run(id.slice(8),this.accountKey(state.username),this.encode(id,state));}
|
||||
catch(cause){if(cause.errcode===2067)throw duplicate();if(cause.status)throw cause;throw fail();}
|
||||
catch(cause){if(cause.errcode===2067)throw duplicate();if(cause.status)throw cause;throw fail(cause,'account_write');}
|
||||
}
|
||||
async accountAvailability(connectionId,username) {
|
||||
try{const row=this.accounts().prepare('SELECT connection_id FROM accounts WHERE username_key=?').get(this.accountKey(username));return {available:!row||row.connection_id===connectionId};}
|
||||
catch(cause){if(cause.status)throw cause;throw fail();}
|
||||
catch(cause){if(cause.status)throw cause;throw fail(cause,'account_read');}
|
||||
}
|
||||
async migrateAccounts(connectionIds) {
|
||||
const db=this.accounts(),legacy=[];
|
||||
@@ -99,7 +106,7 @@ class BpmVault {
|
||||
try{for(const item of legacy)this.putAccount(item.id,item.state);db.exec('COMMIT');}catch(cause){db.exec('ROLLBACK');throw cause;}
|
||||
// Committed database rows become authoritative before legacy ciphertext is removed.
|
||||
for(const item of legacy)await fsp.rm(this.filename(item.id),{force:true});
|
||||
}catch(cause){if(cause.status)throw cause;throw fail();}
|
||||
}catch(cause){if(cause.status)throw cause;throw fail(cause,'account_migrate');}
|
||||
}
|
||||
async read(id) {
|
||||
const filename = this.filename(id);
|
||||
@@ -116,7 +123,7 @@ class BpmVault {
|
||||
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(); }
|
||||
} catch (error) { if (error.code === 'ENOENT') return null;if(error.code==='BPM_ACCOUNT_DUPLICATE')throw error;throw fail(error); }
|
||||
}
|
||||
async write(id, state) {
|
||||
const filename = this.filename(id);
|
||||
@@ -126,9 +133,9 @@ class BpmVault {
|
||||
// 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(); }
|
||||
} catch(cause) { throw fail(cause); }
|
||||
}
|
||||
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(); } }
|
||||
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(cause) { throw fail(cause,'session_remove'); } }
|
||||
destroy() { this.db?.close();this.db=null;this.key?.fill(0);this.key=null; }
|
||||
}
|
||||
module.exports = { BpmVault };
|
||||
Reference in new issue
Block a user