refactor: organize source web and tests by business module
This commit is contained in:
1 parent
9854d2d5c2
commit
2aed328774
113 files changed
+189
-183
No files matched your search
@@ -0,0 +1,73 @@
|
||||
const fail=(status,message)=>{throw Object.assign(new Error(message),{status});};
|
||||
const isLoopback=address=>['127.0.0.1','::1','::ffff:127.0.0.1'].includes(address);
|
||||
function secureBpmTransport(request,trustedProxy=false){
|
||||
if(request.socket.encrypted)return true;
|
||||
if(!isLoopback(request.socket.remoteAddress))return false;
|
||||
if(trustedProxy && request.headers['x-forwarded-proto']==='https')return true;
|
||||
try{const host=new URL('http://'+request.headers.host);return ['localhost','127.0.0.1','[::1]'].includes(host.hostname) && !host.username && !host.password && host.pathname==='/' && !host.search && !host.hash;}catch{return false;}
|
||||
}
|
||||
function authorizeConnection(connection,user){
|
||||
if(user?.role!=='admin' && !(user?.role==='operator' && connection.owner===user.username))fail(403,'仅连接负责人或管理员可以操作此连接。');
|
||||
}
|
||||
function emptyBody(body){if(!body || Object.keys(body).length)fail(400,'此操作不接受额外数据。');}
|
||||
async function managerCall(work){
|
||||
try{return await work();}catch(error){
|
||||
if(error?.status===409&&error.code==='BPM_ACCOUNT_DUPLICATE')fail(409,'该 BPM 账号已开启自动续登,请使用已有连接或先解除原账号托管。');
|
||||
const messages={400:'登录操作数据不正确。',403:'没有操作此登录会话的权限。',404:'登录会话不存在,请重新打开。',409:'登录会话正被使用或不可操作,请刷新后重试。',410:'登录会话已过期,请重新打开。',429:'登录窗口已达到上限,请稍后重试。',503:'BPM 登录服务暂不可用,请稍后重试。'};
|
||||
const status=messages[error?.status]?error.status:502;fail(status,messages[status] || 'BPM 暂时无法连接,请稍后重试。');
|
||||
}
|
||||
}
|
||||
async function bpmApi({workspace,bpmSessions,user,sessionId,route,method,body,request,response,reply,trustedProxy=false}){
|
||||
const match=/^\/api\/connections\/([\w-]+)\/(?:login\/(open|frame|input|navigate|save|close|fill-account)|(check|disable|delete)|(account)(\/(?:clear|check))?)$/.exec(route);
|
||||
if(!match || !workspace)return false;
|
||||
const [,id,login,other,account,suffix]=match;const action=login || other || (suffix==='/clear'?'clear-account':suffix==='/check'?'check-account':account);
|
||||
if(action==='account'?!['GET','POST'].includes(method):method!==(action==='frame'?'GET':'POST'))fail(405,'此操作不支持当前请求方式。');
|
||||
const connection=workspace.getConnection(id);authorizeConnection(connection,user);
|
||||
if(action==='delete'){
|
||||
if(user.role!=='admin')fail(403,'仅管理员可以删除连接。');emptyBody(body);
|
||||
if(connection.status!=='disabled')fail(409,'请先停用连接再删除。');
|
||||
if(!bpmSessions)fail(503,'BPM 登录服务暂不可用,请稍后重试。');
|
||||
await managerCall(()=>bpmSessions.disable(id));reply(200,workspace.deleteConnection(id,user));return true;
|
||||
}
|
||||
if(action==='disable'){
|
||||
if(user.role!=='admin')fail(403,'仅管理员可以停用连接。');emptyBody(body);
|
||||
if(bpmSessions)await managerCall(()=>bpmSessions.disable(id));reply(200,workspace.disableConnection(id,user));return true;
|
||||
}
|
||||
if(connection.status==='disabled')fail(409,'此连接已停用。');
|
||||
if(!secureBpmTransport(request,trustedProxy))fail(403,'请在部署机本地或 HTTPS 页面中登录 BPM。');
|
||||
if(!bpmSessions)fail(503,'BPM 登录服务暂不可用。');
|
||||
const principal={user,sessionId};
|
||||
if(action==='check-account'){
|
||||
const value=await managerCall(()=>bpmSessions.checkAccount(connection,principal,body));reply(200,{available:value.available===true});return true;
|
||||
}
|
||||
if(!['frame','input','navigate','account'].includes(action))emptyBody(body);
|
||||
if(action==='account' || action==='clear-account'){
|
||||
const saving=action==='account' && method==='POST';
|
||||
const previous=saving?await managerCall(()=>bpmSessions.account(connection,principal)):null;
|
||||
const value=await managerCall(()=>bpmSessions[action==='clear-account'?'clearAccount':saving?'saveAccount':'account'](connection,principal,body));
|
||||
let checked;
|
||||
if(saving && previous.configured && previous.username!==value.username)workspace.resetConnectionSession(id,user);
|
||||
if(saving || action==='clear-account')workspace.record(user,saving?'bpm.account.save':'bpm.account.clear',connection.name);
|
||||
if(saving){
|
||||
try{const result=await managerCall(()=>bpmSessions.ensure(workspace.getConnection(id),principal));checked=workspace.updateConnectionSession(id,result,user);}
|
||||
catch(error){if(error.status!==409)throw error;checked=workspace.getConnection(id);}
|
||||
}
|
||||
reply(200,{configured:value.configured===true,username:typeof value.username==='string'?value.username:'',updatedAt:typeof value.updatedAt==='string'?value.updatedAt:null,...(saving?{connection:checked}:{})});return true;
|
||||
}
|
||||
if(action==='fill-account'){
|
||||
const value=await managerCall(()=>bpmSessions.fillAccount(connection,principal));reply(200,{filled:value.filled===true,message:typeof value.message==='string'?value.message:''});return true;
|
||||
}
|
||||
if(action==='frame'){
|
||||
const bytes=await managerCall(()=>bpmSessions.frame(id,principal));
|
||||
if(!Buffer.isBuffer(bytes))fail(502,'登录画面暂不可用。');
|
||||
response.writeHead(200,{'Content-Type':'image/jpeg'});response.end(bytes);return true;
|
||||
}
|
||||
if(action==='save' || action==='check'){
|
||||
const result=await managerCall(()=>bpmSessions[action](connection,principal));reply(200,workspace.updateConnectionSession(id,result,user));return true;
|
||||
}
|
||||
const value=await managerCall(()=>bpmSessions[action](action==='open'?connection:id,principal,body));
|
||||
if(action==='open')reply(200,{active:value.active===true,viewport:{width:value.viewport?.width,height:value.viewport?.height},expiresAt:value.expiresAt,host:value.host});
|
||||
else reply(200,{ok:true});
|
||||
return true;
|
||||
}
|
||||
module.exports={bpmApi,secureBpmTransport};
|
||||
@@ -0,0 +1,34 @@
|
||||
const crypto=require('node:crypto');
|
||||
class BpmCustodian {
|
||||
constructor({workspace,manager,intervalMs=5*60*1000}){
|
||||
this.workspace=workspace;this.manager=manager;this.intervalMs=intervalMs;this.stopped=false;this.running=null;
|
||||
this.principal={user:{id:'bpm-custodian',username:'系统托管',role:'admin'},sessionId:'custodian:'+crypto.randomBytes(24).toString('hex')};
|
||||
}
|
||||
start(){if(this.timer || this.stopped)return;this.timer=setInterval(()=>{this.tick().catch(()=>{});},this.intervalMs);this.timer.unref?.();this.tick().catch(()=>{});}
|
||||
tick(){
|
||||
if(this.stopped || this.running)return Promise.resolve();
|
||||
this.running=this.checkAll().finally(()=>{this.running=null;});return this.running;
|
||||
}
|
||||
async checkAll(){
|
||||
const connections=this.workspace.snapshot().connections;
|
||||
for(const candidate of connections){
|
||||
if(this.stopped)break;
|
||||
if(candidate.status==='disabled')continue;
|
||||
try{
|
||||
const connection=this.workspace.getConnection(candidate.id);
|
||||
if(connection.status==='disabled')continue;
|
||||
const account=await this.manager.account(connection,this.principal);
|
||||
if(!account.configured && !connection.lastConnectedAt && !['connected','unchecked','login_required'].includes(connection.status))continue;
|
||||
const result=await this.manager.ensure(connection,this.principal);
|
||||
// The connection can be disabled while its remote check is in flight.
|
||||
if(this.workspace.getConnection(connection.id).status!=='disabled')this.workspace.updateConnectionSession(connection.id,result,this.principal.user);
|
||||
}catch(cause){
|
||||
// Interactive leases and transient browser failures are retried on the next cycle.
|
||||
// The manager returns checked upstream failures as structured results.
|
||||
if(![403,404,409,429].includes(cause.status))this.lastErrorAt=new Date().toISOString();
|
||||
}
|
||||
}
|
||||
}
|
||||
async stop(){this.stopped=true;clearInterval(this.timer);this.timer=null;await this.running;}
|
||||
}
|
||||
module.exports={BpmCustodian};
|
||||
@@ -0,0 +1,57 @@
|
||||
'use strict';
|
||||
const sanitize=require('sanitize-html');
|
||||
const {loadPlaywright}=require('../../platform/browser.cjs');
|
||||
const fail=(message,status=502)=>Object.assign(new Error(message),{status});
|
||||
const SOURCES=[['portal-v8','bpm/worklist/informlist'],['portal-v4','skyworth/todo/v2/workflow/get_process_of_inform_v4']];
|
||||
function plain(value,max=8000){
|
||||
const text=sanitize(String(value??''),{allowedTags:[],allowedAttributes:{}}).replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi,(m,key)=>{
|
||||
if(key[0]==='#'){const n=key[1].toLowerCase()==='x'?parseInt(key.slice(2),16):+key.slice(1);return n>0&&n<=0x10ffff?String.fromCodePoint(n):'';}
|
||||
return {amp:'&',lt:'<',gt:'>',quot:'"',apos:"'",nbsp:' '}[key.toLowerCase()];
|
||||
});return text.replace(/\s+/g,' ').trim().slice(0,max);
|
||||
}
|
||||
function normalizeArrival(row,source){
|
||||
if(!row||typeof row!=='object'||!['string','number'].includes(typeof row.taskId)||!String(row.taskId)||String(row.taskId).length>200)throw fail('BPM 列表缺少有效的任务标识。');
|
||||
const raw=row.startTime;
|
||||
if(typeof raw!=='string'||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})?$/.test(raw))throw fail('BPM 列表缺少有效的流程到达时间。');
|
||||
const day=raw.slice(0,10),valid=new Date(day+'T00:00:00Z');
|
||||
if(Number.isNaN(+valid)||valid.toISOString().slice(0,10)!==day)throw fail('BPM 流程到达日期无效。');
|
||||
const date=new Date(/(?:Z|[+-]\d{2}:\d{2})$/.test(raw)?raw:raw+'+08:00');
|
||||
if(Number.isNaN(+date))throw fail('BPM 流程到达时间无效。');
|
||||
const arrivedAt=date.toISOString(),arrivalDay=new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(date);
|
||||
return {source,taskId:String(row.taskId),serialNum:plain(row.serialNum,250),processName:plain(row.processName,250),activityName:plain(row.activityName,250),subject:plain(row.processInstanceSubject),initiator:plain(row.processInstanceInitiatorShortName||row.processInstanceInitiator,250),arrivedAt,arrivalDay};
|
||||
}
|
||||
class BpmListClient{
|
||||
constructor({baseURL='https://bpmn.skyworthdigital.com/',pageSize=100,allowLocal=false}={}){
|
||||
const u=new URL(baseURL);if(u.href!=='https://bpmn.skyworthdigital.com/'&&!(allowLocal&&['127.0.0.1','localhost','[::1]'].includes(u.hostname)&&['http:','https:'].includes(u.protocol)&&u.pathname==='/'&&!u.username&&!u.password&&!u.search&&!u.hash))throw fail('BPM 地址不受支持。',400);
|
||||
this.baseURL=u.href;this.pageSize=pageSize;
|
||||
}
|
||||
async scan(storageState){
|
||||
if(!storageState)throw fail('BPM 会话需要续登。',401);
|
||||
const request=await loadPlaywright().request.newContext({baseURL:this.baseURL,storageState,timeout:20000});
|
||||
const get=async(route,options={})=>{
|
||||
let response;try{response=await request.get(route,{...options,maxRedirects:0});}catch{throw fail('BPM 查询连接失败,请稍后重试。');}
|
||||
const status=response.status();if(status>=300&&status<400)throw fail('BPM 查询发生登录跳转,需要续登。',401);
|
||||
if([401,403].includes(status))throw fail('BPM 会话需要续登。',401);
|
||||
if(status!==200)throw fail('BPM 查询失败,请稍后重试。');
|
||||
const body=await response.body();if(body.length>10*1024*1024)throw fail('BPM 查询响应过大。');return body.toString('utf8');
|
||||
};
|
||||
try{
|
||||
const html=await get('/'),token=/Yiez\.clientId\s*=\s*['"]([^'"\s<>]{1,16000})['"]/.exec(html)?.[1];
|
||||
if(!token)throw fail('BPM 会话需要续登。',401);
|
||||
const rows=[];
|
||||
for(const [source,route]of SOURCES){
|
||||
let total=null;const seen=new Set();
|
||||
for(let page=1;page<=100;page++){
|
||||
let data;try{data=JSON.parse(await get(route,{params:{page,start:(page-1)*this.pageSize,limit:this.pageSize},headers:{Authorization:'Bearer '+token}}));}catch(cause){if(cause.status)throw cause;throw fail('BPM 列表数据格式不正确。');}
|
||||
if(!Array.isArray(data.children)||!Number.isSafeInteger(data.total)||data.total<0||data.total>10000||data.success===false)throw fail('BPM 列表分页数据不完整。');
|
||||
if(total!==null&&total!==data.total)throw fail('BPM 列表正在变化,请重新扫描。');total=data.total;
|
||||
for(const raw of data.children){const row=normalizeArrival(raw,source);if(seen.has(row.taskId))throw fail('BPM 列表分页重复,请重新扫描。');seen.add(row.taskId);rows.push(row);}
|
||||
if(seen.size===total)break;
|
||||
if(!data.children.length||data.children.length>this.pageSize||seen.size>total||page===100)throw fail('BPM 列表分页不完整,请重新扫描。');
|
||||
}
|
||||
}
|
||||
return rows;
|
||||
}finally{await request.dispose();}
|
||||
}
|
||||
}
|
||||
module.exports={BpmListClient,normalizeArrival};
|
||||
@@ -0,0 +1,23 @@
|
||||
'use strict';
|
||||
async function bpmScanApi({scanner,workspace,user,sessionId,url,route,method,body,reply}){
|
||||
if(!route.startsWith('/api/bpm-scan')&&route!=='/api/arrivals')return false;
|
||||
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
|
||||
if(!scanner)fail('BPM 扫描暂不可用。',503);
|
||||
if(route==='/api/arrivals'&&method==='GET'){
|
||||
const filters={connectionId:url.searchParams.get('connectionId')||'',q:url.searchParams.get('q')||'',before:url.searchParams.get('before')||'',days:Number(url.searchParams.get('days')||7)};
|
||||
reply(200,scanner.store.list(filters));return true;
|
||||
}
|
||||
if(route==='/api/bpm-scan'&&method==='GET'){reply(200,{...scanner.store.status(),connections:workspace.snapshot().connections.map(({id,name,status,owner})=>({id,name,status,owner}))});return true;}
|
||||
if(route==='/api/bpm-scan/config'&&method==='POST'){
|
||||
if(user.role!=='admin')fail('仅管理员可以配置自动扫描。',403);
|
||||
const config=scanner.store.saveConfig(body);workspace.record(user,'保存自动扫描',`${config.enabled?'开启':'暂停'},间隔 ${config.intervalMinutes} 分钟`);reply(200,config);return true;
|
||||
}
|
||||
if(route==='/api/bpm-scan/run'&&method==='POST'){
|
||||
if(!body||Object.keys(body).some(k=>k!=='connectionId')||typeof body.connectionId!=='string')fail('请选择 BPM 连接。');
|
||||
// A scan may span many pages. The UI polls the durable run instead of holding a request open.
|
||||
const {promise,runId}=scanner.startScan(body.connectionId,{user,sessionId});
|
||||
promise.catch(()=>{});reply(202,{runId});return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
module.exports={bpmScanApi};
|
||||
@@ -0,0 +1,36 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs');const path=require('node:path');const crypto=require('node:crypto');const {DatabaseSync}=require('node:sqlite');
|
||||
const invalid=message=>Object.assign(new Error(message),{status:400});
|
||||
class BpmScanStore{
|
||||
constructor(dir){fs.mkdirSync(dir,{recursive:true});this.db=new DatabaseSync(path.join(dir,'scan.sqlite'));this.db.exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL;
|
||||
CREATE TABLE IF NOT EXISTS config(id INTEGER PRIMARY KEY CHECK(id=1),value TEXT NOT NULL);
|
||||
INSERT OR IGNORE INTO config VALUES(1,'{"enabled":true,"intervalMinutes":5}');
|
||||
CREATE TABLE IF NOT EXISTS arrivals(connection_id TEXT NOT NULL,source TEXT NOT NULL,task_id TEXT NOT NULL,day TEXT NOT NULL,value TEXT NOT NULL,first_seen TEXT NOT NULL,last_seen TEXT NOT NULL,PRIMARY KEY(connection_id,source,task_id));
|
||||
CREATE INDEX IF NOT EXISTS arrivals_day ON arrivals(day DESC);
|
||||
CREATE TABLE IF NOT EXISTS runs(id TEXT PRIMARY KEY,connection_id TEXT NOT NULL,actor TEXT NOT NULL,started_at TEXT NOT NULL,finished_at TEXT,status TEXT NOT NULL,seen INTEGER,added INTEGER,message TEXT);
|
||||
UPDATE runs SET status='error',message='服务重启,扫描未完成。',finished_at=CURRENT_TIMESTAMP WHERE status='running';`);}
|
||||
transaction(fn){this.db.exec('BEGIN IMMEDIATE');try{const r=fn();this.db.exec('COMMIT');return r;}catch(e){this.db.exec('ROLLBACK');throw e;}}
|
||||
config(){return JSON.parse(this.db.prepare('SELECT value FROM config WHERE id=1').get().value);}
|
||||
saveConfig(input){if(!input||Object.keys(input).some(k=>!['enabled','intervalMinutes'].includes(k))||typeof input.enabled!=='boolean'||!Number.isInteger(input.intervalMinutes)||input.intervalMinutes<1||input.intervalMinutes>1440)throw invalid('扫描间隔需为 1–1440 分钟。');this.db.prepare('UPDATE config SET value=? WHERE id=1').run(JSON.stringify(input));return this.config();}
|
||||
begin(connectionId,actor){const id=crypto.randomUUID();this.db.prepare('INSERT INTO runs(id,connection_id,actor,started_at,status) VALUES(?,?,?,?,?)').run(id,connectionId,actor,new Date().toISOString(),'running');return id;}
|
||||
complete(id,connectionId,rows){return this.transaction(()=>{
|
||||
let added=0;const now=new Date().toISOString();
|
||||
const insert=this.db.prepare('INSERT OR IGNORE INTO arrivals VALUES(?,?,?,?,?,?,?)');const update=this.db.prepare('UPDATE arrivals SET day=?,value=?,last_seen=? WHERE connection_id=? AND source=? AND task_id=?');
|
||||
for(const row of rows){if(!row.arrivalDay||!row.taskId||!row.source)throw invalid('流程记录无效。');const value=JSON.stringify(row);added+=Number(insert.run(connectionId,row.source,row.taskId,row.arrivalDay,value,now,now).changes);update.run(row.arrivalDay,value,now,connectionId,row.source,row.taskId);}
|
||||
this.db.prepare('UPDATE runs SET status=?,finished_at=?,seen=?,added=?,message=? WHERE id=? AND status=?').run('success',now,rows.length,added,'',id,'running');this.prune();return {seen:rows.length,added};
|
||||
});}
|
||||
fail(id,message){this.db.prepare('UPDATE runs SET status=?,finished_at=?,message=? WHERE id=?').run('error',new Date().toISOString(),message,id);this.prune();}
|
||||
prune(){this.db.exec("DELETE FROM runs WHERE status!='running' AND id NOT IN(SELECT id FROM runs ORDER BY started_at DESC,rowid DESC LIMIT 200)");}
|
||||
status(){return {config:this.config(),total:this.db.prepare('SELECT COUNT(*) n FROM arrivals').get().n,runs:this.db.prepare('SELECT id,connection_id AS connectionId,actor,started_at AS startedAt,finished_at AS finishedAt,status,seen,added,message FROM runs ORDER BY started_at DESC,rowid DESC LIMIT 30').all()};}
|
||||
list({connectionId='',q='',before='',days=7}={}){
|
||||
if(typeof q!=='string'||q.length>200||typeof connectionId!=='string'||connectionId.length>200||typeof before!=='string'||(before&&!/^\d{4}-\d{2}-\d{2}$/.test(before))||!Number.isInteger(days)||days<1||days>31)throw invalid('查询条件无效。');
|
||||
const conditions=[],args=[];if(connectionId){conditions.push('connection_id=?');args.push(connectionId);}if(q){conditions.push("value LIKE ? ESCAPE '\\'");args.push('%'+q.replace(/[\\%_]/g,'\\$&')+'%');}
|
||||
const where=conditions.length?' WHERE '+conditions.join(' AND '):'';const total=this.db.prepare('SELECT COUNT(*) n FROM arrivals'+where).get(...args).n;
|
||||
if(before){conditions.push('day<?');args.push(before);}const filtered=conditions.length?' WHERE '+conditions.join(' AND '):'';
|
||||
const dates=this.db.prepare('SELECT DISTINCT day FROM arrivals'+filtered+' ORDER BY day DESC LIMIT ?').all(...args,days+1).map(r=>r.day);const shown=dates.slice(0,days);
|
||||
const groups=shown.map(day=>({day,items:this.db.prepare('SELECT connection_id AS connectionId,value,first_seen AS firstSeenAt,last_seen AS lastSeenAt FROM arrivals'+(filtered?filtered+' AND ':' WHERE ')+'day=? ORDER BY json_extract(value,\'$.arrivedAt\') DESC,task_id').all(...args,day).map(({value,...rest})=>({...JSON.parse(value),...rest}))}));
|
||||
return {total,groups,nextBefore:dates.length>days?shown.at(-1):null};
|
||||
}
|
||||
close(){this.db.close();}
|
||||
}
|
||||
module.exports={BpmScanStore};
|
||||
@@ -0,0 +1,28 @@
|
||||
'use strict';
|
||||
const crypto=require('node:crypto');const {dayPolicy}=require('../../shared/schedule.cjs');
|
||||
const fail=(message,status)=>Object.assign(new Error(message),{status});
|
||||
class BpmScanner{
|
||||
constructor({store,workspace,manager,settings,clock=()=>new Date()}){Object.assign(this,{store,workspace,manager,settings,clock});this.pending=new Map();this.stopped=false;this.lastTick=0;this.principal={user:{username:'系统扫描',role:'admin'},sessionId:'scan:'+crypto.randomUUID()};}
|
||||
start(){if(this.timer||this.stopped)return;this.timer=setInterval(()=>this.tick().catch(()=>{}),15000);this.timer.unref?.();this.tick().catch(()=>{});}
|
||||
async scan(id,principal){return this.startScan(id,principal).promise;}
|
||||
startScan(id,principal){
|
||||
if(this.stopped)throw fail('扫描服务正在关闭。',503);const connection=this.workspace.getConnection(id);
|
||||
if(!principal?.sessionId||!['admin','operator'].includes(principal.user?.role)||(principal.user.role!=='admin'&&connection.owner!==principal.user.username))throw fail('只有连接负责人或管理员可以扫描。',403);
|
||||
if(connection.status==='disabled')throw fail('此 BPM 连接已停用。',409);
|
||||
if(this.pending.has(id))throw fail('此连接正在扫描,请稍后查看结果。',409);
|
||||
const runId=this.store.begin(id,principal.user.username);
|
||||
const operation=Promise.resolve().then(async()=>{
|
||||
try{const rows=await this.manager.scanArrivals(connection,principal);if(this.workspace.getConnection(id).status==='disabled')throw fail('此 BPM 连接已停用。',409);return {...this.store.complete(runId,id,rows),runId};}
|
||||
catch(cause){this.store.fail(runId,cause.status?cause.message:'BPM 扫描失败,请稍后重试。');throw cause;}
|
||||
}).finally(()=>this.pending.delete(id));this.pending.set(id,operation);return {promise:operation,runId};
|
||||
}
|
||||
tick(){if(this.stopped||this.ticking)return Promise.resolve();this.ticking=this.checkAll().finally(()=>{this.ticking=null;});return this.ticking;}
|
||||
async checkAll(){
|
||||
const config=this.store.config(),now=this.clock();if(!config.enabled||+now-this.lastTick<config.intervalMinutes*60000)return;
|
||||
const snapshot=this.workspace.snapshot();if(!dayPolicy(now,this.settings().schedule,snapshot.calendar.overrides).scan)return;
|
||||
this.lastTick=+now;
|
||||
for(const connection of snapshot.connections){if(this.stopped)break;if(connection.status==='disabled'||(!connection.lastConnectedAt&&connection.status!=='connected')||this.pending.has(connection.id))continue;try{await this.scan(connection.id,this.principal);}catch{}}
|
||||
}
|
||||
async stop(){this.stopped=true;clearInterval(this.timer);await this.ticking;await Promise.allSettled([...this.pending.values()]);}
|
||||
}
|
||||
module.exports={BpmScanner};
|
||||
@@ -0,0 +1,427 @@
|
||||
'use strict';
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { BpmVault } = require('../../platform/security/vault.cjs');
|
||||
const { loadPlaywright, browserOptions } = require('../../platform/browser.cjs');
|
||||
const { BpmListClient } = require('./list-client.cjs');
|
||||
const DEFAULT_URLS = { main: 'https://bpmn.skyworthdigital.com/' };
|
||||
const LOGIN_FORMS = {
|
||||
'https://sso.skyworthdigital.com': { username:'#username', password:'#password', submit:'#kc-form-login button[type="submit"]', form:'#kc-form-login', actionPath:'/realms/skyworthdigital/login-actions/authenticate' }
|
||||
};
|
||||
const TTL = 10 * 60 * 1000;
|
||||
const KEYS = new Set(['Tab','Enter','Backspace','Delete','ArrowUp','ArrowDown','ArrowLeft','ArrowRight','Home','End','Escape','Control+A']);
|
||||
const error = (message, status = 400) => Object.assign(new Error(message), { status });
|
||||
const safe = cause => cause?.status ? cause : error('BPM 浏览器暂不可用,请重试。', 503);
|
||||
const object = (value, fields) => value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).every(key => fields.includes(key));
|
||||
|
||||
class BpmSessionManager {
|
||||
constructor({ stateDir, browserFactory, urls, allowedOrigins, probe, loginForms } = {}) {
|
||||
this.stateDir = path.resolve(stateDir); fs.mkdirSync(this.stateDir, { recursive: true });
|
||||
if (urls!==undefined && !object(urls,['main'])) throw error('BPM 地址配置无效。');
|
||||
this.urls = { ...DEFAULT_URLS, ...urls };
|
||||
this.allowedOrigins = new Set(Object.values(DEFAULT_URLS).map(url => new URL(url).origin));
|
||||
this.allowedOrigins.add('https://sso.skyworthdigital.com');
|
||||
if (allowedOrigins) {
|
||||
// Injection exists only for local integration fixtures; it cannot widen production's external allowlist.
|
||||
for (const origin of allowedOrigins) {
|
||||
const parsed = new URL(origin);
|
||||
if (!['localhost','127.0.0.1','[::1]'].includes(parsed.hostname) || !['http:','https:'].includes(parsed.protocol) || parsed.origin !== origin) throw error('测试域名必须为本机地址。');
|
||||
this.allowedOrigins.add(origin);
|
||||
}
|
||||
}
|
||||
for (const target of Object.values(this.urls)) if (!this.allowed(target)) throw error('BPM 地址不在允许范围内。',403);
|
||||
this.loginForms = { ...LOGIN_FORMS };
|
||||
// Only local fixtures may register additional forms; callers cannot replace company forms.
|
||||
for (const [origin,form] of Object.entries(loginForms || {})) {
|
||||
const parsed = new URL(origin);
|
||||
if (!['localhost','127.0.0.1','[::1]'].includes(parsed.hostname) || !this.allowedOrigins.has(origin) || parsed.origin!==origin || !object(form,['username','password','submit']) || !['username','password'].every(key=>typeof form[key]==='string' && /^#[a-zA-Z_][\w-]*$/.test(form[key])) || (form.submit!==undefined && !/^#[a-zA-Z_][\w-]*$/.test(form.submit))) throw error('测试登录表单无效。');
|
||||
this.loginForms[origin] = { ...form };
|
||||
}
|
||||
this.browserFactory = browserFactory || (() => loadPlaywright().chromium.launch(browserOptions()));
|
||||
this.probe = probe || this.defaultProbe.bind(this);
|
||||
this.sessions = new Map(); this.operations = new Map(); this.disabled = new Set(); this.stopped = false;
|
||||
}
|
||||
allowed(url) { try { const parsed = new URL(url); return !parsed.username && !parsed.password && this.allowedOrigins.has(parsed.origin); } catch { return false; } }
|
||||
vault() { return this._vault ||= new BpmVault({ stateDir: this.stateDir }); }
|
||||
accountMetadata(stored) { return stored ? {configured:true,username:stored.username,updatedAt:stored.updatedAt} : {configured:false,username:'',updatedAt:null}; }
|
||||
async migrateAccounts(connections) { await this.vault().migrateAccounts(connections.map(connection=>connection.id)); }
|
||||
async checkAccount(connection,principal,input) {
|
||||
return this.run(connection?.id,async()=>{this.authorize(connection,principal);if(!object(input,['username'])||typeof input.username!=='string'||!input.username.trim()||input.username.length>150)throw error('请输入有效的 BPM 账号。');return this.vault().accountAvailability(connection.id,input.username);});
|
||||
}
|
||||
async account(connection,principal) {
|
||||
return this.run(connection?.id,async()=>{ this.authorize(connection,principal); return this.accountMetadata(await this.vault().read('account:'+connection.id)); });
|
||||
}
|
||||
async saveAccount(connection,principal,credentials) {
|
||||
return this.run(connection?.id,async()=>{
|
||||
this.authorize(connection,principal);
|
||||
if (!object(credentials,['username','password']) || typeof credentials.username!=='string' || !credentials.username.trim() || credentials.username.length>150 || typeof credentials.password!=='string' || !credentials.password || credentials.password.length>256) throw error('请输入有效的 BPM 账号和密码。');
|
||||
const lease=this.sessions.get(connection.id);
|
||||
if (lease && lease.sessionId!==principal.sessionId) throw error('此连接正在另一登录窗口中使用。',409);
|
||||
const stored={username:credentials.username.trim(),password:credentials.password,updatedAt:new Date().toISOString()};
|
||||
const previous=await this.vault().read('account:'+connection.id);
|
||||
// A password rotation retains valid cookies. Only an actual account change revokes
|
||||
// authentication; first custody can reuse a user's already saved manual login.
|
||||
await this.vault().write('account:'+connection.id,stored);
|
||||
if (previous && previous.username.trim().toLowerCase()!==stored.username.toLowerCase()) {
|
||||
try{await this.vault().remove(connection.id);await this.closeLease(connection.id);}
|
||||
catch(cause){await this.vault().write('account:'+connection.id,previous);throw cause;}
|
||||
}
|
||||
return this.accountMetadata(stored);
|
||||
});
|
||||
}
|
||||
async clearAccount(connection,principal) {
|
||||
return this.run(connection?.id,async()=>{ this.authorize(connection,principal); await this.vault().remove('account:'+connection.id); return this.accountMetadata(null); });
|
||||
}
|
||||
async fillSavedAccount(lease) {
|
||||
const stored=await this.vault().read('account:'+lease.id);
|
||||
if (!stored) return {filled:false,message:'请先保存托管账号。'};
|
||||
const origin=new URL(lease.page.url()).origin, form=this.loginForms[origin];
|
||||
if (!form || lease.blocked) return {filled:false,message:'请打开支持的 BPM 登录页面。'};
|
||||
try {
|
||||
await Promise.all([lease.page.locator(form.username).waitFor({state:'visible',timeout:1500}),lease.page.locator(form.password).waitFor({state:'visible',timeout:1500})]);
|
||||
// Validate and set both values in one browser task: a navigation or DOM replacement
|
||||
// between separate locator.fill calls must never redirect a secret to another field.
|
||||
const filled=await lease.page.evaluate(({origin,form,username,password})=>{
|
||||
if (location.origin!==origin || window!==window.top) return false;
|
||||
const user=document.querySelector(form.username), secret=document.querySelector(form.password);
|
||||
const usable=(node,type)=>node instanceof HTMLInputElement && node.type===type && !node.disabled && !node.readOnly && node.getClientRects().length>0 && getComputedStyle(node).visibility==='visible' && getComputedStyle(node).display!=='none';
|
||||
if (!usable(user,'text') || !usable(secret,'password') || user===secret) return false;
|
||||
const set=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set;
|
||||
set.call(user,username);set.call(secret,password);
|
||||
for (const node of [user,secret]) { node.dispatchEvent(new Event('input',{bubbles:true})); node.dispatchEvent(new Event('change',{bubbles:true})); }
|
||||
return true;
|
||||
},{origin,form,username:stored.username,password:stored.password});
|
||||
return {filled,message:filled?'已填入托管账号,请完成登录。':'请打开支持的 BPM 登录表单。'};
|
||||
} catch { return {filled:false,message:'请等待登录表单显示后重试。'}; }
|
||||
}
|
||||
async fillAccount(connection,principal) {
|
||||
return this.run(connection?.id,async()=>{ this.authorize(connection,principal); const lease=await this.getLease(connection.id,principal,true); await this.settleNavigation(lease); return this.fillSavedAccount(lease); });
|
||||
}
|
||||
async automaticSubmit(lease,stored,submit=false) {
|
||||
const origin=new URL(lease.page.url()).origin, form=this.loginForms[origin];
|
||||
if (!form?.submit || lease.blocked) return false;
|
||||
return lease.page.evaluate(({origin,form,stored,submit})=>{
|
||||
if (location.origin!==origin || window!==window.top) return false;
|
||||
const visible=node=>!!node && node.getClientRects().length>0 && getComputedStyle(node).visibility==='visible' && getComputedStyle(node).display!=='none';
|
||||
const user=document.querySelector(form.username),secret=document.querySelector(form.password),button=document.querySelector(form.submit);
|
||||
if (!(user instanceof HTMLInputElement) || user.type!=='text' || !visible(user) || user.disabled || user.readOnly || !(secret instanceof HTMLInputElement) || secret.type!=='password' || !visible(secret) || secret.disabled || secret.readOnly || !visible(button) || button.disabled || button.type!=='submit') return false;
|
||||
const login=user.form;
|
||||
if (!login || secret.form!==login || button.form!==login || login.method.toLowerCase()!=='post' || (form.form && !login.matches(form.form))) return false;
|
||||
if ((button.getAttribute('formmethod') || login.method).toLowerCase()!=='post' || !['','_self'].includes(button.getAttribute('formtarget') || login.target)) return false;
|
||||
const action=new URL(button.getAttribute('formaction') || login.action,location.href);
|
||||
if (action.origin!==origin || (form.actionPath && action.pathname!==form.actionPath)) return false;
|
||||
// Any additional visible field or challenge requires the user's intervention.
|
||||
const challenge=/captcha|recaptcha|hcaptcha|turnstile|otp|one.?time|totp|verification|verify.?code/i;
|
||||
if (Array.from(document.querySelectorAll('input,iframe,img,[id],[class]')).some(node=>visible(node) && challenge.test([node.id,node.className,node.getAttribute('name'),node.getAttribute('autocomplete'),node.getAttribute('src'),node.getAttribute('title')].join(' ')))) return false;
|
||||
if (Array.from(login.elements).some(node=>visible(node) && node!==user && node!==secret && !['submit','button','hidden','reset'].includes(node.type))) return false;
|
||||
if (submit) {
|
||||
const set=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set;
|
||||
set.call(user,stored.username);set.call(secret,stored.password);
|
||||
button.click();
|
||||
}
|
||||
return true;
|
||||
},{origin,form,stored:{username:stored.username,password:stored.password},submit}).catch(()=>false);
|
||||
}
|
||||
async persistLease(lease) {
|
||||
await this.captureSessions(lease);
|
||||
const storageState=await lease.context.storageState({indexedDB:true});
|
||||
await this.vault().write(lease.id,{storageState,sessionStorage:lease.sessionStorage});
|
||||
}
|
||||
canPersistVerified(result) {
|
||||
return result.status==='connected' && result.checks.portal.ok;
|
||||
}
|
||||
async ensure(connection,principal) {
|
||||
return this.run(connection?.id,async()=>{
|
||||
this.authorize(connection,principal);
|
||||
if (this.sessions.has(connection.id)) throw error('此连接正在登录窗口中使用。',409);
|
||||
const lease=await this.create(connection,principal);
|
||||
try {
|
||||
let result=await this.verify(lease);
|
||||
this.authorize(connection,principal);
|
||||
if (this.canPersistVerified(result)) await this.persistLease(lease);
|
||||
if (result.status==='connected') return result;
|
||||
// Network failures and a healthy portal never justify submitting credentials again.
|
||||
if (result.status!=='login_required' || result.checks.portal.message!=='请在此入口完成登录。' || lease.blocked) return result;
|
||||
const stored=await this.vault().read('account:'+connection.id);
|
||||
if (!stored) return result;
|
||||
const manual=message=>{ if (!result.checks.portal.ok) result.checks.portal.message=message; return result; };
|
||||
if (Date.parse(stored.nextAttemptAt)>Date.now()) return manual('自动登录暂缓,请稍后重试或更新托管账号。');
|
||||
await this.readOnlyGoto(lease,this.urls.main);
|
||||
if (lease.blocked || !this.allowed(lease.page.url())) return manual('请人工检查 BPM 登录页面。');
|
||||
if (!await this.automaticSubmit(lease,stored)) return manual('需要人工完成验证码或登录验证。');
|
||||
// Persist before a request to avoid repeated retries after a crash or failed password.
|
||||
await this.vault().write('account:'+connection.id,{...stored,nextAttemptAt:new Date(Date.now()+15*60*1000).toISOString()});
|
||||
if (!await this.automaticSubmit(lease,stored,true)) return manual('需要人工完成登录验证。');
|
||||
await this.settleNavigation(lease);
|
||||
result=await this.verify(lease);this.authorize(connection,principal);
|
||||
if (this.canPersistVerified(result)) {
|
||||
await this.persistLease(lease);delete stored.nextAttemptAt;await this.vault().write('account:'+connection.id,stored);
|
||||
} else if (!result.checks.portal.ok) result.checks.portal.message='自动登录未完成,请检查托管账号或人工完成验证;稍后重试。';
|
||||
return result;
|
||||
} finally { await this.closeLease(connection.id); }
|
||||
});
|
||||
}
|
||||
async scanArrivals(connection,principal) {
|
||||
const query=()=>this.run(connection?.id,async()=>{
|
||||
this.authorize(connection,principal);
|
||||
if(this.sessions.has(connection.id))throw error('此连接正在登录窗口中使用,请关闭后扫描。',409);
|
||||
const saved=await this.vault().read(connection.id);
|
||||
const rows=await (this.listClient ||= new BpmListClient()).scan(saved?.storageState);
|
||||
this.authorize(connection,principal);return rows;
|
||||
});
|
||||
try{return await query();}catch(cause){if(cause.status!==401)throw cause;}
|
||||
// Renewal takes the same per-connection lock, so it must run after query releases it.
|
||||
const renewed=await this.ensure(connection,principal);
|
||||
if(renewed.status!=='connected')throw error(renewed.checks?.portal?.message||'请在 BPM 连接中完成登录。',401);
|
||||
return query();
|
||||
}
|
||||
authorize(connection, principal) {
|
||||
if (!connection || typeof connection.id !== 'string' || !connection.id || connection.id.length > 200) throw error('连接标识无效。');
|
||||
if (!principal?.sessionId || !principal.user || !['admin','operator'].includes(principal.user.role) || (principal.user.role !== 'admin' && connection.owner !== principal.user.username)) throw error('只有连接负责人或管理员可以操作。',403);
|
||||
if (this.stopped) throw error('BPM 服务正在关闭。',503);
|
||||
if (connection.status === 'disabled' || this.disabled.has(connection.id)) throw error('此 BPM 连接已停用。',409);
|
||||
}
|
||||
run(id, work) {
|
||||
const before = this.operations.get(id) || Promise.resolve();
|
||||
const operation = before.catch(()=>{}).then(work).catch(cause=>{ throw safe(cause); });
|
||||
this.operations.set(id, operation);
|
||||
operation.finally(()=>{ if (this.operations.get(id) === operation) this.operations.delete(id); }).catch(()=>{});
|
||||
return operation;
|
||||
}
|
||||
touch(lease) {
|
||||
lease.expiresAt = Date.now() + TTL; clearTimeout(lease.timer);
|
||||
lease.timer = setTimeout(()=>this.run(lease.id, async()=>{ if (lease.expiresAt <= Date.now()) await this.closeLease(lease.id); }).catch(()=>{}), TTL + 10);
|
||||
lease.timer.unref?.();
|
||||
}
|
||||
async getLease(id, principal, touch = false, closing = false) {
|
||||
const lease = this.sessions.get(id);
|
||||
if (!lease) throw error('登录窗口已关闭,请重新打开。',410);
|
||||
this.authorize(lease.connection,principal);
|
||||
if (lease.sessionId !== principal.sessionId) throw error('此连接正在另一登录窗口中使用。',409);
|
||||
if (lease.expiresAt <= Date.now()) { await this.closeLease(id); throw error('登录窗口已过期,请重新打开。',410); }
|
||||
if (!closing && (lease.blocked || !this.allowed(lease.page.url()))) throw error('已阻止离开允许的 BPM 域名,请重新打开登录窗口。',403);
|
||||
if (touch) this.touch(lease);
|
||||
return lease;
|
||||
}
|
||||
async browser() {
|
||||
if (this.stopped) throw error('BPM 服务正在关闭。',503);
|
||||
if (!this.browserPromise) this.browserPromise = Promise.resolve().then(()=>this.browserFactory()).catch(cause=>{ this.browserPromise=null; throw cause; });
|
||||
return this.browserPromise;
|
||||
}
|
||||
async create(connection, principal) {
|
||||
this.authorize(connection,principal);
|
||||
if (this.sessions.size >= 3) throw error('同时登录窗口已达上限,请先关闭其他窗口。',429);
|
||||
const lease = { id:connection.id, connection:{...connection}, sessionId:principal.sessionId, context:null, page:null, blocked:false, sessionStorage:{} };
|
||||
this.sessions.set(connection.id,lease); this.touch(lease);
|
||||
try {
|
||||
const stored = await this.vault().read(connection.id);
|
||||
lease.sessionStorage = stored?.sessionStorage || {};
|
||||
const browser = await this.browser();
|
||||
this.authorize(connection,principal);
|
||||
lease.context = await browser.newContext({ viewport:{width:1280,height:800}, acceptDownloads:false, serviceWorkers:'block', permissions:[], storageState:stored?.storageState });
|
||||
await lease.context.route('**/*', async route => {
|
||||
try {
|
||||
// A popup is never a remote-control surface. Block its first navigation,
|
||||
// before even an allowed host can redirect it elsewhere.
|
||||
if (route.request().isNavigationRequest() && route.request().frame().page()!==lease.page) return await route.abort('blockedbyclient');
|
||||
if (this.allowed(route.request().url())) {
|
||||
// route.continue follows redirects without re-entering the route handler.
|
||||
// Inspect each redirect before Chromium receives it, including resource redirects.
|
||||
const response=await route.fetch({maxRedirects:0,timeout:25000});
|
||||
const location=response.headers().location;
|
||||
if (location && response.status()>=300 && response.status()<400 && !this.allowed(new URL(location,route.request().url()).href)) {
|
||||
if (route.request().isNavigationRequest() && !route.request().frame().parentFrame()) lease.blocked=true;
|
||||
return await route.abort('blockedbyclient');
|
||||
}
|
||||
if (/attachment/i.test(response.headers()['content-disposition']||'')) return await route.abort('blockedbyclient');
|
||||
// Await inside this try: closing a context can dispose the fetched response
|
||||
// before fulfill finishes. Returning its promise bypasses this catch.
|
||||
return await route.fulfill({response});
|
||||
}
|
||||
if (route.request().isNavigationRequest() && !route.request().frame().parentFrame()) lease.blocked = true;
|
||||
await route.abort('blockedbyclient');
|
||||
} catch { await route.abort('failed').catch(()=>{}); }
|
||||
});
|
||||
if (lease.context.routeWebSocket) await lease.context.routeWebSocket(/.*/, socket => {
|
||||
const url=socket.url().replace(/^ws:/,'http:').replace(/^wss:/,'https:');
|
||||
if (this.allowed(url)) socket.connectToServer(); else socket.close();
|
||||
});
|
||||
await lease.context.addInitScript(({ sessions }) => {
|
||||
try { if (sessionStorage.length===0) for (const [key,value] of Object.entries(sessions[location.origin] || {})) sessionStorage.setItem(key,value); } catch {}
|
||||
// Native file pickers are not part of remote login and must never reach the service desktop.
|
||||
const disable = () => document.querySelectorAll('input[type=file]').forEach(input=>{ input.disabled=true; });
|
||||
new MutationObserver(disable).observe(document,{childList:true,subtree:true});
|
||||
document.addEventListener('click', event => { if (event.target.closest?.('input[type=file],a[download]')) { event.preventDefault(); event.stopImmediatePropagation(); } },true);
|
||||
}, { sessions:lease.sessionStorage });
|
||||
lease.page = await lease.context.newPage();
|
||||
// Playwright routes omit redirected requests. A private Chromium request-stage
|
||||
// guard sees every hop before any network access, including redirect chains.
|
||||
lease.network = await lease.context.newCDPSession(lease.page);
|
||||
lease.mainFrameId=(await lease.network.send('Page.getFrameTree')).frameTree.frame.id;
|
||||
// Raw mouse/keyboard input returns before a form-triggered navigation commits.
|
||||
// Track main-frame navigation independently so verification never races it.
|
||||
const started=event=>{
|
||||
if (event.frameId!==lease.mainFrameId || lease.pendingNavigation) return;
|
||||
lease.pendingNavigation=new Promise(resolve=>{lease.finishNavigation=resolve;});
|
||||
};
|
||||
lease.network.on('Page.frameRequestedNavigation',started);
|
||||
lease.network.on('Page.frameStartedLoading',started);
|
||||
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});
|
||||
else {
|
||||
if (event.resourceType==='Document' && event.frameId===lease.mainFrameId) lease.blocked=true;
|
||||
await lease.network.send('Fetch.failRequest',{requestId:event.requestId,errorReason:'BlockedByClient'});
|
||||
}
|
||||
} catch {}
|
||||
});
|
||||
await lease.network.send('Fetch.enable',{patterns:[{urlPattern:'*',requestStage:'Request'}]});
|
||||
lease.context.on('page', page=>{ if (page !== lease.page) page.close().catch(()=>{}); });
|
||||
lease.page.on('download', download=>download.cancel().catch(()=>{}));
|
||||
lease.page.on('dialog', dialog=>dialog.dismiss().catch(()=>{}));
|
||||
await lease.page.goto(this.urls.main,{waitUntil:'domcontentloaded',timeout:30000});
|
||||
this.authorize(connection,principal);
|
||||
if (lease.blocked || !this.allowed(lease.page.url())) throw error('已阻止离开允许的 BPM 域名。',403);
|
||||
await this.fillSavedAccount(lease);
|
||||
return lease;
|
||||
} catch (cause) { await this.closeLease(connection.id); throw safe(cause); }
|
||||
}
|
||||
async open(connection, principal) {
|
||||
return this.run(connection?.id,async()=>{
|
||||
this.authorize(connection,principal);
|
||||
const lease=this.sessions.has(connection.id) ? await this.getLease(connection.id,principal,true) : await this.create(connection,principal);
|
||||
return { active:true,viewport:{width:1280,height:800},expiresAt:new Date(lease.expiresAt).toISOString(),host:new URL(lease.page.url()).host };
|
||||
});
|
||||
}
|
||||
async frame(id,principal) { return this.run(id,async()=>{ const lease=await this.getLease(id,principal); return lease.page.screenshot({type:'jpeg',quality:75,caret:'initial',timeout:10000}); }); }
|
||||
async input(id,principal,action) {
|
||||
return this.run(id,async()=>{
|
||||
if (!object(action,['type','x','y','text','key','deltaX','deltaY'])) throw error('输入操作无效。');
|
||||
const type=action.type;
|
||||
if (type==='click') { if (!Number.isFinite(action.x)||!Number.isFinite(action.y)||action.x<0||action.x>=1280||action.y<0||action.y>=800) throw error('点击位置无效。'); }
|
||||
else if (type==='text') { if (typeof action.text!=='string'||action.text.length>2000) throw error('输入文字过长或无效。'); }
|
||||
else if (type==='key') { if (!KEYS.has(action.key)) throw error('不支持此按键。'); }
|
||||
else if (type==='scroll') { if (![action.deltaX,action.deltaY].every(value=>Number.isFinite(value)&&Math.abs(value)<=10000)) throw error('滚动距离无效。'); }
|
||||
else throw error('输入操作无效。');
|
||||
const lease=await this.getLease(id,principal,true);
|
||||
if (type==='click') await lease.page.mouse.click(action.x,action.y);
|
||||
if (type==='text') await lease.page.keyboard.insertText(action.text);
|
||||
if (type==='key') await lease.page.keyboard.press(action.key);
|
||||
if (type==='scroll') await lease.page.mouse.wheel(action.deltaX,action.deltaY);
|
||||
return {ok:true};
|
||||
});
|
||||
}
|
||||
async navigate(id,principal,action) {
|
||||
return this.run(id,async()=>{
|
||||
if (!object(action,['target']) || !['main','reload','back'].includes(action.target)) throw error('导航目标无效。');
|
||||
const lease=await this.getLease(id,principal,true), options={waitUntil:'domcontentloaded',timeout:30000};
|
||||
if (action.target==='reload') await lease.page.reload(options);
|
||||
else if (action.target==='back') await lease.page.goBack(options);
|
||||
else await lease.page.goto(this.urls[action.target],options);
|
||||
if (lease.blocked || !this.allowed(lease.page.url())) throw error('已阻止离开允许的 BPM 域名。',403);
|
||||
await this.fillSavedAccount(lease);
|
||||
return {ok:true,host:new URL(lease.page.url()).host};
|
||||
});
|
||||
}
|
||||
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: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};
|
||||
}
|
||||
async captureSessions(lease) {
|
||||
for (const frame of lease.page.frames()) {
|
||||
if (!this.allowed(frame.url())) continue;
|
||||
const item=await frame.evaluate(()=>({origin:location.origin,values:Object.fromEntries(Object.entries(sessionStorage))})).catch(()=>null);
|
||||
if (item) lease.sessionStorage[item.origin]=item.values;
|
||||
}
|
||||
}
|
||||
async settleNavigation(lease) {
|
||||
// A protocol round trip lets an input-triggered navigation notification arrive;
|
||||
// the wait itself follows lifecycle events, with a deadline rather than a sleep.
|
||||
await lease.network.send('Page.getFrameTree');
|
||||
const pending=lease.pendingNavigation;
|
||||
if (pending) {
|
||||
let timeout;
|
||||
try { await Promise.race([pending,new Promise((_,reject)=>{timeout=setTimeout(()=>reject(error('BPM 页面仍在加载,请稍后重试。',503)),15000);})]); }
|
||||
finally { clearTimeout(timeout); }
|
||||
}
|
||||
await lease.page.waitForLoadState('domcontentloaded',{timeout:15000});
|
||||
}
|
||||
async readOnlyGoto(lease,url) {
|
||||
await this.settleNavigation(lease);
|
||||
for (let attempt=0;attempt<2;attempt++) {
|
||||
try { return await lease.page.goto(url,{waitUntil:'domcontentloaded',timeout:25000}); }
|
||||
catch (cause) {
|
||||
// Retry only our read-only verification GET, never the user's login action.
|
||||
if (attempt || lease.blocked || !/interrupted by another navigation|ERR_ABORTED/i.test(cause.message||'')) throw cause;
|
||||
await this.settleNavigation(lease);
|
||||
}
|
||||
}
|
||||
}
|
||||
async verify(lease) {
|
||||
const checkedAt=new Date().toISOString();
|
||||
try {
|
||||
await this.settleNavigation(lease);await this.captureSessions(lease);
|
||||
lease.blocked=false;
|
||||
const response=await this.readOnlyGoto(lease,this.urls.main);
|
||||
if (lease.blocked || !this.allowed(lease.page.url())) throw error('域名被阻止。',403);
|
||||
if (response && response.status()>=400) throw error('BPM 暂时无法连接。',503);
|
||||
const result=await this.probe(lease.page,'portal');
|
||||
const ok=result?.ok===true && typeof result.identity==='string' && !!result.identity.trim();
|
||||
await this.captureSessions(lease);
|
||||
return {status:ok?'connected':'login_required',identity:ok?result.identity.trim().slice(0,150):'',checkedAt,checks:{portal:{ok,message:ok?'已验证登录账号。':'请在此入口完成登录。'}}};
|
||||
} catch {
|
||||
return {status:'error',identity:'',checkedAt,checks:{portal:{ok:false,message:lease.blocked?'已阻止离开允许的 BPM 域名。':'暂时无法验证此入口。'}}};
|
||||
}
|
||||
}
|
||||
async save(connection,principal) {
|
||||
return this.run(connection?.id,async()=>{
|
||||
this.authorize(connection,principal); const lease=await this.getLease(connection.id,principal,true);
|
||||
const result=await this.verify(lease);
|
||||
this.authorize(connection,principal);
|
||||
// Failed verification never replaces a previously working credential snapshot.
|
||||
if (this.canPersistVerified(result)) await this.persistLease(lease);
|
||||
return result;
|
||||
});
|
||||
}
|
||||
async check(connection,principal) {
|
||||
return this.run(connection?.id,async()=>{
|
||||
this.authorize(connection,principal);
|
||||
const transient=!this.sessions.has(connection.id);
|
||||
const lease=transient ? await this.create(connection,principal) : await this.getLease(connection.id,principal,true);
|
||||
try { const result=await this.verify(lease); this.authorize(connection,principal); if(this.canPersistVerified(result))await this.persistLease(lease); return result; }
|
||||
finally { if (transient) await this.closeLease(connection.id); }
|
||||
});
|
||||
}
|
||||
async closeLease(id) {
|
||||
const lease=this.sessions.get(id); if (!lease) return;
|
||||
clearTimeout(lease.timer); this.sessions.delete(id);
|
||||
await lease.context?.close().catch(()=>{});
|
||||
}
|
||||
async close(id,principal) { return this.run(id,async()=>{ if (!this.sessions.has(id)) return {active:false}; await this.getLease(id,principal,false,true); await this.closeLease(id); return {active:false}; }); }
|
||||
async releaseSession(sessionId) { await Promise.all([...this.sessions.values()].filter(lease=>lease.sessionId===sessionId).map(lease=>this.run(lease.id,()=>this.closeLease(lease.id)))); }
|
||||
async disable(id) { this.disabled.add(id); await this.run(id,async()=>{ await this.closeLease(id); await this.vault().remove(id); await this.vault().remove('account:'+id); }); }
|
||||
async shutdown() {
|
||||
this.stopped=true;
|
||||
await Promise.allSettled([...this.operations.values()]);
|
||||
await Promise.all([...this.sessions.keys()].map(id=>this.closeLease(id)));
|
||||
if (this.browserPromise) await (await this.browserPromise.catch(()=>null))?.close().catch(()=>{});
|
||||
this._vault?.destroy();
|
||||
}
|
||||
}
|
||||
module.exports={BpmSessionManager};
|
||||
Reference in new issue
Block a user