fix: recover BPM browsers and harden redaction and Windows supervision
This commit is contained in:
1 parent
acba28c879
commit
db98d78f6b
14 files changed
+223
-59
No files matched your search
@@ -1,6 +1,6 @@
|
||||
'use strict';
|
||||
const crypto=require('node:crypto'),{fail}=require('./store.cjs');
|
||||
function redact(value,maxLength=2000){return String(value??'').replace(/\b(?:Bearer\s+)[^\s,;]+/gi,'Bearer [已隐藏]').replace(/((?:password|passwd|api[_-]?key|token|cookie|authorization|密码)\s*[=::]\s*)([^\s,;]+)/gi,'$1[已隐藏]').replace(/\b[A-Za-z]:[\\/][^\r\n"'<>]*/g,'[本机路径已隐藏]').replace(/\\\\[^\r\n"'<>]*/g,'[共享路径已隐藏]').slice(0,maxLength);}
|
||||
const {redact}=require('../../shared/redact.cjs');
|
||||
const cleanMessage=(value,key)=>String(value??'').split(key||'\u0000').join('[已隐藏]');
|
||||
function snapshot({workspace,scanner,storage,dashboard},user){
|
||||
const w=workspace?.snapshot()||{connections:[],exceptions:[]},authorized=c=>user.role==='admin'||c.owner===user.username;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
'use strict';
|
||||
const {fail}=require('./store.cjs'),{redact,cleanMessage,snapshot,checkAction,parseResponse}=require('./policy.cjs');
|
||||
const {fail}=require('./store.cjs'),{cleanMessage,snapshot,checkAction,parseResponse}=require('./policy.cjs'),{redact}=require('../../shared/redact.cjs');
|
||||
class AssistantService{
|
||||
constructor({store,runtime,...deps}){this.store=store;this.runtime=runtime;this.deps=deps;this.running=new Map();this.actions=new Set();this.stopped=false;}
|
||||
context(user){return snapshot(this.deps,user);}
|
||||
@@ -17,7 +17,7 @@ class AssistantService{
|
||||
const task=Promise.resolve().then(async()=>{
|
||||
try{if(controller.signal.aborted)throw controller.signal.reason;
|
||||
const raw=await this.runtime.chat({config,text:cleanMessage(redact(text,4000),config.apiKey),context,history,signal:controller.signal});if(controller.signal.aborted)throw controller.signal.reason;
|
||||
const response=parseResponse(raw,this.deps,principal.user);response.reply=cleanMessage(response.reply,config.apiKey);if(!config.allowActions)response.actions=[];
|
||||
const response=parseResponse(raw,this.deps,principal.user);response.reply=cleanMessage(redact(response.reply,20000),config.apiKey);if(!config.allowActions)response.actions=[];
|
||||
this.store.updateTurn(turn.id,'success',{...response,evidence:[{label:'诊断快照时间',value:context.at},{label:'范围',value:`${context.connections.length} 个授权 BPM 连接,${context.servers.length} 个存储配置,${context.jobs.length} 条导出记录`}],finishedAt:new Date().toISOString()});
|
||||
}catch(e){const cancelled=e.status===499&&!e.stopUnconfirmed&&controller.signal.aborted&&controller.signal.reason?.status===499;this.store.updateTurn(turn.id,cancelled?'cancelled':'error',{error:cleanMessage(redact(e.status?e.message:'ZCode 调用未完成,请检查运行包和模型配置。'),config.apiKey),finishedAt:new Date().toISOString()});}
|
||||
finally{clearTimeout(timer);this.running.delete(turn.id);}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
'use strict';
|
||||
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' }
|
||||
};
|
||||
async function fillSavedForm(lease,stored,loginForms) {
|
||||
const origin=new URL(lease.page.url()).origin, form=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 function automaticSubmitForm(lease,stored,submit,loginForms) {
|
||||
const origin=new URL(lease.page.url()).origin, form=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);
|
||||
}
|
||||
module.exports={LOGIN_FORMS,fillSavedForm,automaticSubmitForm};
|
||||
@@ -5,9 +5,7 @@ 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 { LOGIN_FORMS, fillSavedForm, automaticSubmitForm } = require('./login-form.cjs');
|
||||
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 });
|
||||
@@ -75,53 +73,16 @@ class BpmSessionManager {
|
||||
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:'请等待登录表单显示后重试。'}; }
|
||||
return fillSavedForm(lease,stored,this.loginForms);
|
||||
}
|
||||
|
||||
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);
|
||||
return automaticSubmitForm(lease,stored,submit,this.loginForms);
|
||||
}
|
||||
|
||||
async persistLease(lease) {
|
||||
await this.captureSessions(lease);
|
||||
const storageState=await lease.context.storageState({indexedDB:true});
|
||||
@@ -205,8 +166,24 @@ class BpmSessionManager {
|
||||
}
|
||||
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;
|
||||
const cached=this.browserPromise;
|
||||
if (cached) {
|
||||
const browser=await cached;
|
||||
if (browser.isConnected?.()!==false) return browser;
|
||||
this.invalidateBrowser(browser,cached);
|
||||
return this.browser();
|
||||
}
|
||||
const pending=Promise.resolve().then(()=>this.browserFactory()).then(browser=>{
|
||||
browser.on?.('disconnected',()=>this.invalidateBrowser(browser,pending));
|
||||
if (browser.isConnected?.()===false) { this.invalidateBrowser(browser,pending);throw error('BPM 浏览器暂不可用,请重试。',503); }
|
||||
return browser;
|
||||
}).catch(cause=>{if(this.browserPromise===pending)this.browserPromise=null;throw cause;});
|
||||
this.browserPromise=pending;
|
||||
return pending;
|
||||
}
|
||||
invalidateBrowser(browser,pending) {
|
||||
if(this.browserPromise===pending)this.browserPromise=null;
|
||||
for(const [id,lease] of this.sessions)if(lease.browser===browser){clearTimeout(lease.timer);this.sessions.delete(id);lease.context?.close().catch(()=>{});}
|
||||
}
|
||||
async create(connection, principal) {
|
||||
this.authorize(connection,principal);
|
||||
@@ -217,6 +194,7 @@ class BpmSessionManager {
|
||||
const stored = await this.vault().read(connection.id);
|
||||
lease.sessionStorage = stored?.sessionStorage || {};
|
||||
const browser = await this.browser();
|
||||
lease.browser=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 => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs'),path=require('node:path'),{DatabaseSync}=require('node:sqlite'),{readSupervisor}=require('../../platform/service/control.cjs'),{redact}=require('../assistant/policy.cjs');
|
||||
const fs=require('node:fs'),path=require('node:path'),{DatabaseSync}=require('node:sqlite'),{readSupervisor}=require('../../platform/service/control.cjs'),{redact}=require('../../shared/redact.cjs');
|
||||
function timestamp(value){if(typeof value!=='string')return null;const normalized=/^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d$/.test(value)?value.replace(' ','T')+'Z':value;const n=Date.parse(normalized);return Number.isFinite(n)?new Date(n).toISOString():null;}
|
||||
const latest=(...values)=>values.map(timestamp).filter(Boolean).sort().at(-1)||null;
|
||||
const groupStatus=items=>!items.length?'unconfigured':['error','unknown','running','pending','healthy','paused','disabled'].find(s=>items.some(i=>i.status===s))||'pending';
|
||||
|
||||
Reference in new issue
Block a user