135 lines
8.8 KiB
JavaScript
135 lines
8.8 KiB
JavaScript
'use strict';
|
|
const fs = require('node:fs');
|
|
const fsp = require('node:fs/promises');
|
|
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 duplicate = () => Object.assign(new Error('该 BPM 账号已开启自动续登,请使用已有连接或先解除原账号托管。'), { status: 409, code: 'BPM_ACCOUNT_DUPLICATE' });
|
|
const digest = value => crypto.createHash('sha256').update(value).digest('hex');
|
|
|
|
function powershell(script, input) {
|
|
const utf8='[Console]::InputEncoding=New-Object System.Text.UTF8Encoding; [Console]::OutputEncoding=New-Object System.Text.UTF8Encoding; ';
|
|
return execFileSync('powershell.exe', ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', utf8+script], {
|
|
input, encoding: 'utf8', windowsHide: true, timeout: 15000, stdio: ['pipe', 'pipe', 'pipe']
|
|
}).trim();
|
|
}
|
|
function secureDirectory(dir) {
|
|
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
if (process.platform === 'win32') {
|
|
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);
|
|
} else fs.chmodSync(dir, 0o700);
|
|
}
|
|
function dpapi(value, decrypt = false) {
|
|
const operation = decrypt ? 'Unprotect' : 'Protect';
|
|
return Buffer.from(powershell(`$ErrorActionPreference="Stop"; Add-Type -AssemblyName System.Security; $b=[Convert]::FromBase64String([Console]::In.ReadToEnd()); $r=[System.Security.Cryptography.ProtectedData]::${operation}($b,$null,[System.Security.Cryptography.DataProtectionScope]::CurrentUser); [Console]::Out.Write([Convert]::ToBase64String($r))`, value.toString('base64')), 'base64');
|
|
}
|
|
|
|
class BpmVault {
|
|
constructor({ stateDir }) {
|
|
try {
|
|
this.stateDir = path.resolve(stateDir);
|
|
secureDirectory(this.stateDir);
|
|
} catch { throw fail(); }
|
|
}
|
|
ensureKey() {
|
|
if (this.key) return this.key;
|
|
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'
|
|
? path.join(process.env.LOCALAPPDATA, 'OrderNotificationAutomation', 'bpm-keys')
|
|
: path.join(this.stateDir, '.keys');
|
|
secureDirectory(keyDir);
|
|
const keyFile = path.join(keyDir, digest(this.stateDir.toLowerCase()) + '.key');
|
|
if (!fs.existsSync(keyFile)) {
|
|
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; }
|
|
finally { raw.fill(0); }
|
|
}
|
|
const protectedKey = fs.readFileSync(keyFile);
|
|
this.key = process.platform === 'win32' ? dpapi(protectedKey, true) : protectedKey;
|
|
if (this.key.length !== 32) throw fail();
|
|
return this.key;
|
|
} catch { throw fail(); }
|
|
}
|
|
filename(id) {
|
|
if (typeof id !== 'string' || !id || id.length > 200) throw Object.assign(new Error('连接标识无效。'), { status: 400 });
|
|
return path.join(this.stateDir, digest(id) + '.enc');
|
|
}
|
|
accounts() {
|
|
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);
|
|
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) {
|
|
if(typeof username!=='string'||!username.trim()||username.length>150)throw Object.assign(new Error('请输入有效的 BPM 账号。'),{status:400});
|
|
return crypto.createHmac('sha256',this.ensureKey()).update(username.trim().toLowerCase()).digest('hex');
|
|
}
|
|
encode(id,state) {
|
|
const iv=crypto.randomBytes(12),cipher=crypto.createCipheriv('aes-256-gcm',this.ensureKey(),iv);cipher.setAAD(Buffer.from(id));
|
|
const encrypted=Buffer.concat([cipher.update(JSON.stringify(state),'utf8'),cipher.final()]);
|
|
return Buffer.concat([Buffer.from('BPM1'),iv,cipher.getAuthTag(),encrypted]);
|
|
}
|
|
decode(id,bytes) {
|
|
const data=Buffer.from(bytes);
|
|
if(data.length<33||data.subarray(0,4).toString()!=='BPM1')throw fail();
|
|
const decipher=crypto.createDecipheriv('aes-256-gcm',this.ensureKey(),data.subarray(4,16));
|
|
decipher.setAAD(Buffer.from(id));decipher.setAuthTag(data.subarray(16,32));
|
|
return JSON.parse(Buffer.concat([decipher.update(data.subarray(32)),decipher.final()]).toString('utf8'));
|
|
}
|
|
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();}
|
|
}
|
|
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();}
|
|
}
|
|
async migrateAccounts(connectionIds) {
|
|
const db=this.accounts(),legacy=[];
|
|
try{
|
|
for(const connectionId of connectionIds){const id='account:'+connectionId;if(db.prepare('SELECT 1 FROM accounts WHERE connection_id=?').get(connectionId))continue;try{const payload=await fsp.readFile(this.filename(id));legacy.push({id,state:this.decode(id,payload)});}catch(cause){if(cause.code!=='ENOENT')throw cause;}}
|
|
db.exec('BEGIN IMMEDIATE');
|
|
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();}
|
|
}
|
|
async read(id) {
|
|
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);
|
|
if(id.startsWith('account:')){this.putAccount(id,state);await fsp.rm(filename,{force:true}).catch(()=>{});return;}
|
|
try {
|
|
// 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(); }
|
|
}
|
|
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 };
|