diff --git a/src/modules/bpm/order-form.cjs b/src/modules/bpm/order-form.cjs
new file mode 100644
index 0000000..97289aa
--- /dev/null
+++ b/src/modules/bpm/order-form.cjs
@@ -0,0 +1,44 @@
+'use strict';
+const fail=(message,status=409)=>Object.assign(new Error(message),{status});
+function processURL(value){
+ const u=new URL(value,'https://bpm.skyworthdigital.com');
+ if(u.origin!=='https://bpm.skyworthdigital.com'||u.pathname!=='/YZSoft/Forms/Process.aspx'||u.username||u.password||u.hash||[...u.searchParams.keys()].length!==2||!['tid','pid'].every(k=>/^\d+$/.test(u.searchParams.get(k)||'')))throw fail('待办流程目标地址未通过核验。',403);return u;
+}
+function safeEntry(value){
+ let u;try{u=new URL(value);}catch{throw fail('待办表单地址格式无效。',403);}if(u.origin==='https://bpm.skyworthdigital.com'&&u.pathname==='/sso/ssologin.aspx'){
+ if(u.username||u.password||u.hash||[...u.searchParams.keys()].length!==3||[...u.searchParams.keys()].some(k=>!['ReturnUrl','todo_token','todo_account'].includes(k))||!u.searchParams.get('todo_token')||!u.searchParams.get('todo_account'))throw fail('待办临时登录地址格式无效。',403);
+ return {entry:u,target:processURL(u.searchParams.get('ReturnUrl'))};
+ }
+ return null;
+}
+async function loadForm(request,entry,validateFinal){
+ const known=safeEntry(entry);let url=known?.entry||validateFinal(entry),target=known?.target;const visited=new Set();
+ for(let hop=0;hop<4;hop++){
+ if(visited.has(url.href))throw fail('表单跳转发生循环。');visited.add(url.href);
+ let response;try{response=await request.get(url.href,{maxRedirects:0,timeout:20000});}catch{throw fail('BPM 表单连接失败,请检查网络后重试。',502);}
+ const status=response.status();if(status>=300&&status<400){
+ const location=response.headers().location;if(!location)throw fail('表单跳转缺少目标。');const next=new URL(location,url);
+ if(target&&next.href===target.href){url=next;continue;}
+ // Only the observed SSO -> Process -> XForm chain is allowed; never login,
+ // Redirect.aspx, arbitrary domains, scripts or business mutation requests.
+ url=validateFinal(next.href);
+ if(target&&['tid','pid'].some(k=>url.searchParams.get(k)!==target.searchParams.get(k)))throw fail('表单跳转的实例或任务标识发生变化。',403);
+ continue;
+ }
+ if(status!==200)throw fail([401,403].includes(status)?'BPM 表单会话已失效,请重新核验连接。':'BPM 表单查询失败。',[401,403].includes(status)?401:502);
+ const final=validateFinal(url.href),bytes=await response.body();if(bytes.length>12000000)throw fail('表单响应超过采集上限。');
+ return {url:final,bytes};
+ }
+ throw fail('表单跳转次数超过上限。');
+}
+async function loadData(request,url){
+ const pid=url.searchParams.get('pid');if(!/^\d+$/.test(pid||''))throw fail('表单任务标识无效。');
+ let response;try{response=await request.post(new URL('/YZSoft/BPM/XMLService/DataProvider.ashx',url).href,{data:'GetFormProcessData'+pid+'',headers:{'Content-Type':'text/xml'},maxRedirects:0,timeout:20000});}catch{throw fail('表单数据读取超时或连接失败。',502);}
+ const status=response.status();if([301,302,303,307,308,401,403].includes(status))throw fail('表单数据会话失效,请重新核验 BPM 连接。',401);
+ if(status!==200)throw fail('表单数据读取失败。',502);
+ const bytes=await response.body();if(bytes.length>12000000)throw fail('表单数据超出采集上限。');
+ let data;try{data=JSON.parse(bytes.toString('utf8'));}catch{throw fail('表单数据格式无效。',502);}
+ if(data.success!==true||!Array.isArray(data.Tables)||data.Tables.length>200||data.Tables.some(t=>!t||typeof t.TableName!=='string'||!Array.isArray(t.Rows)||t.Rows.length>4000||t.Rows.some(r=>!r||Array.isArray(r)||typeof r!=='object')))throw fail('表单数据不完整或未通过权限检查。',502);
+ return data.Tables.filter(t=>t.FormTable===true);
+}
+module.exports={safeEntry,processURL,loadForm,loadData};
diff --git a/src/modules/bpm/order-provider.cjs b/src/modules/bpm/order-provider.cjs
index 3e3188f..2c9b4cc 100644
--- a/src/modules/bpm/order-provider.cjs
+++ b/src/modules/bpm/order-provider.cjs
@@ -1,15 +1,16 @@
'use strict';
const {BpmTodoClient}=require('./todo-client.cjs');
const {loadPlaywright,browserOptions}=require('../../platform/browser.cjs');
+const {safeEntry,loadForm,loadData}=require('./order-form.cjs');
const fail=(message,status=409)=>Object.assign(new Error(message),{status});
function detailURL(value,allowLocal=false){
let url;try{url=new URL(value);}catch{throw fail('待办没有可读取的表单地址;请核验对应门户表单接入。');}
const local=allowLocal&&['127.0.0.1','localhost','[::1]'].includes(url.hostname);
- if(url.username||url.password||url.hash||(!local&&(url.origin!=='https://bpm.skyworthdigital.com'||!url.pathname.startsWith('/YZSoft/Forms/XForm/')))||!/^\/[\s\S]+\.aspx$/i.test(url.pathname)||[...url.searchParams.keys()].some(k=>!['tid','pid'].includes(k))||!/^\d+$/.test(url.searchParams.get('tid')||'')||!/^\d+$/.test(url.searchParams.get('pid')||''))throw fail('表单地址不在已核验的只读范围内。',403);
+ if(url.username||url.password||url.hash||!['http:','https:'].includes(url.protocol)||(!local&&(url.origin!=='https://bpm.skyworthdigital.com'||!url.pathname.startsWith('/YZSoft/Forms/XForm/')))||!/^\/[\s\S]+\.aspx$/i.test(url.pathname)||[...url.searchParams.keys()].length!==2||[...url.searchParams.keys()].some(k=>!['tid','pid'].includes(k))||!/^\d+$/.test(url.searchParams.get('tid')||'')||!/^\d+$/.test(url.searchParams.get('pid')||''))throw fail('表单地址不在已核验的只读范围内。',403);
return url;
}
class BpmOrderProvider{
- constructor({manager,client=new BpmTodoClient(),browserFactory,allowLocal=false}={}){this.manager=manager;this.client=client;this.browserFactory=browserFactory||(()=>loadPlaywright().chromium.launch(browserOptions()));this.allowLocal=allowLocal;this.checks={liveTodo:false,pdfExport:false,message:'尚未完成真实待办与表单采集检查。'};}
+ constructor({manager,client=new BpmTodoClient(),browserFactory,allowLocal=false}={}){this.manager=manager;this.client=client;this.browserFactory=browserFactory||(()=>loadPlaywright().chromium.launch(browserOptions()));this.allowLocal=allowLocal;this.entries=new Map();this.checks={liveTodo:false,pdfExport:false,message:'尚未完成真实待办与表单采集检查。'};}
capabilities(){return {...this.checks};}
async saved(connection,principal,work){return this.manager.run(connection?.id,async()=>{
this.manager.authorize(connection,principal);if(this.manager.sessions.has(connection.id))throw fail('此连接正在登录窗口中使用。');
@@ -17,30 +18,65 @@ class BpmOrderProvider{
const result=await work(saved.storageState);this.manager.authorize(connection,principal);return result;
});}
async scan(connection,principal){
- try{const rows=await this.saved(connection,principal,state=>this.client.scan(state));this.checks={...this.checks,liveTodo:true,checkedAt:new Date().toISOString(),message:'真实待办接口已读取;各类别表单仍需字段与归档现场核验。'};return rows;}
+ try{const rows=await this.saved(connection,principal,state=>this.client.scan(state));
+ const safe=rows.map(row=>{const entry=row.detailUrl?safeEntry(row.detailUrl):null;return {...row,detailUrl:entry?entry.target.href:row.detailUrl?detailURL(row.detailUrl,this.allowLocal).href:undefined};});
+ this.entries.set(connection.id,new Map(rows.filter(r=>r.detailUrl).map(r=>[r.taskId,{url:r.detailUrl,row:r,at:Date.now()}])));
+ this.checks={...this.checks,liveTodo:true,checkedAt:new Date().toISOString(),message:'真实待办接口已读取;各类别表单仍需字段与归档现场核验。'};return safe;}
catch(error){this.checks={...this.checks,liveTodo:false,message:error.message};throw error;}
}
async capture(connection,principal,row){
- const url=detailURL(row.detailUrl,this.allowLocal);
return this.saved(connection,principal,async storageState=>{
+ let entry=this.entries.get(connection.id)?.get(row.taskId);
+ if((!entry||Date.now()-entry.at>5*60*1000)&&row.detailUrl?.includes('/YZSoft/Forms/Process.aspx')){
+ const rows=await this.client.scan(storageState),fresh=rows.find(r=>r.taskId===row.taskId&&r.instanceId===row.instanceId&&r.nodeName===row.nodeName&&r.processVersion===row.processVersion);
+ if(!fresh)throw fail('此任务已不在原节点或版本,请重新扫描核验。');entry={url:fresh.detailUrl,row:fresh,at:Date.now()};
+ }
+ const request=await loadPlaywright().request.newContext({storageState,timeout:20000});let loaded,tables;
+ try{loaded=await loadForm(request,entry?.url||row.detailUrl,value=>detailURL(value,this.allowLocal));tables=await loadData(request,loaded.url);}finally{await request.dispose();}
+ const url=loaded.url;
const browser=await this.browserFactory();try{
// Server-rendered V4 form only. No page scripts, approval requests or redirects.
const context=await browser.newContext({storageState,javaScriptEnabled:false,serviceWorkers:'block',acceptDownloads:false});
- await context.route('**/*',route=>route.request().method()==='GET'&&route.request().url()===url.href?route.continue():route.abort());
- const page=await context.newPage(),response=await page.goto(url.href,{waitUntil:'domcontentloaded',timeout:20000});
+ await context.route('**/*',async route=>{
+ if(route.request().method()!=='GET'||route.request().url()!==url.href)return route.abort();
+ return route.fulfill({status:200,contentType:'text/html; charset=utf-8',body:loaded.bytes});
+ });
+ const page=await context.newPage();let response;
+ try{response=await page.goto(url.href,{waitUntil:'domcontentloaded',timeout:20000});}catch{throw fail('BPM 只读表单解析失败。',502);}
if(!response||response.status()!==200||page.url()!==url.href)throw fail('BPM 表单读取失败或登录已失效,请续登后重试。',401);
- const snapshot=await page.evaluate(()=>{
+ const snapshot=await page.evaluate(tables=>{
const copy=document.documentElement.cloneNode(true),fields=[],seen=new Map();
+ const hydrated=new Map();
+ for(const table of tables){
+ const prefix=(table.DataSource?table.DataSource+':':'')+table.TableName;
+ for(const [index,row]of table.Rows.entries())for(const [column,value]of Object.entries(row)){
+ if(value!==null&&!['string','number','boolean'].includes(typeof value))continue;
+ const path=prefix+'.'+column,key=path.toLowerCase(),item={path:table.Rows.length===1?path:prefix+'['+index+'].'+column,value:value===null?'':String(value)};
+ const list=hydrated.get(key)||[];list.push(item);hydrated.set(key,list);
+ }
+ }
for(const el of document.querySelectorAll('[xdatabind]')){
const key=el.getAttribute('xdatabind');if(!key||key.length>250)continue;
+ const values=hydrated.get(key.toLowerCase()),label=el.getAttribute('aria-label')||el.closest('td')?.previousElementSibling?.textContent?.trim()||key;
+ if(values){for(const item of values){if(!seen.has(item.path)){seen.set(item.path,item.value);fields.push({...item,label:label.slice(0,200)});}}continue;}
if(['radio','checkbox'].includes(el.type)&&!el.checked)continue;
- const value='value'in el?el.value:el.textContent.trim(),label=el.getAttribute('aria-label')||el.closest('td')?.previousElementSibling?.textContent?.trim()||key;
+ const value='value'in el?el.value:el.textContent.trim();
if(seen.has(key)&&seen.get(key)!==value){seen.set(key,null);continue;}seen.set(key,value);fields.push({path:key,label:label.slice(0,200),value});
}
- for(const el of copy.querySelectorAll('input,textarea,select')){const original=document.getElementById(el.id),span=document.createElement('span');span.textContent=original?original.tagName==='SELECT'?original.selectedOptions?.[0]?.textContent||original.value:original.value||'':'';el.replaceWith(span);}
+ const originals=[...document.querySelectorAll('input,textarea,select')];
+ for(const el of copy.querySelectorAll('[xdatabind]')){
+ if(el.matches('input,textarea,select'))continue;
+ const values=hydrated.get(el.getAttribute('xdatabind')?.toLowerCase());if(values)el.textContent=values.map(v=>v.value).join('\n');
+ }
+ for(const [index,el]of [...copy.querySelectorAll('input,textarea,select')].entries()){
+ const original=originals[index],span=document.createElement('span');
+ const values=hydrated.get(original?.getAttribute('xdatabind')?.toLowerCase());
+ span.textContent=values?['radio','checkbox'].includes(original.type)?values.some(v=>v.value===original.value)?'☑':'☐':values.map(v=>v.value).join('\n'):original?['radio','checkbox'].includes(original.type)?original.checked?'☑':'☐':original.tagName==='SELECT'?original.selectedOptions?.[0]?.textContent||original.value:original.value||'':'';
+ if(original?.type==='hidden')span.hidden=true;el.replaceWith(span);
+ }
copy.querySelectorAll('script,iframe,object,embed,button,[printout="false"],#taskCommentForm').forEach(el=>el.remove());
return {html:copy.outerHTML,styles:Array.from(document.querySelectorAll('style')).map(e=>e.textContent),images:[],fields:fields.filter(f=>seen.get(f.path)!==null).filter((f,i,a)=>a.findIndex(x=>x.path===f.path)===i)};
- });
+ },tables);
if(snapshot.html.length>12000000||snapshot.fields.length>4000)throw fail('表单超出采集上限。');
if(!snapshot.fields.some(f=>f.value!==''))throw fail('只读表单未取得实际字段值,需核验表单加载接口;禁止使用空表单继续执行。');
snapshot.sourceUrl=url.href;snapshot.processVersion=String(row.processVersion||'');
@@ -48,7 +84,7 @@ class BpmOrderProvider{
const sample={...row,connectionId:connection.id,fields:Object.fromEntries(snapshot.fields.map(f=>[f.path,f.value])),brief:row.title};
this.checks={...this.checks,pdfExport:true,capturedAt:new Date().toISOString()};return {sample,snapshot};
}finally{await browser.close();}
- });
+ }).catch(error=>{this.checks={...this.checks,pdfExport:false,message:error.message};throw error;});
}
}
module.exports={BpmOrderProvider,detailURL};
diff --git a/tests/app/closure-providers.test.cjs b/tests/app/closure-providers.test.cjs
index 95d8d22..68995a3 100644
--- a/tests/app/closure-providers.test.cjs
+++ b/tests/app/closure-providers.test.cjs
@@ -5,6 +5,26 @@ const {BpmOrderProvider,detailURL}=require('../../src/modules/bpm/order-provider
const {OrderArchiveProvider,targetFor}=require('../../src/modules/storage/order-archive.cjs');
const {FileArea}=require('../../src/modules/storage/files.cjs');
const {MailStore}=require('../../src/modules/mail/store.cjs');
+const {loadData,loadForm}=require('../../src/modules/bpm/order-form.cjs');
+
+test('transient todo SSO entry follows only matching process and form and never persists its token',async()=>{
+ const target='https://bpm.skyworthdigital.com/YZSoft/Forms/Process.aspx?tid=21&pid=11',entry='https://bpm.skyworthdigital.com/sso/ssologin.aspx?ReturnUrl='+encodeURIComponent(target)+'&todo_token=fixture-secret&todo_account=fixture';
+ const final='https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/test.aspx?tid=21&pid=11',calls=[];
+ const request={get:async(url)=>{calls.push(url);return url===entry?{status:()=>302,headers:()=>({location:target})}:url===target?{status:()=>302,headers:()=>({location:final})}:{status:()=>200,body:async()=>Buffer.from('
form
')};}};
+ assert.equal((await loadForm(request,entry,detailURL)).url.href,final);assert.equal(calls.length,3);
+ const manager={run:(_,fn)=>fn(),authorize(){},sessions:new Map(),vault:()=>({read:async()=>({storageState:{cookies:[],origins:[]}})})};
+ const provider=new BpmOrderProvider({manager,client:{scan:async()=>[{taskId:'11',detailUrl:entry}]}});const rows=await provider.scan({id:'c'},{});assert.equal(rows[0].detailUrl,target);assert.doesNotMatch(JSON.stringify(rows),/fixture-secret|todo_token/);
+ await assert.rejects(loadForm({get:async()=>({status:()=>302,headers:()=>({location:final.replace('tid=21','tid=22')})})},entry,detailURL),/标识/);
+ await assert.rejects(loadForm({get:async()=>({status:()=>302,headers:()=>({location:'https://evil.test/login'})})},entry,detailURL),/范围/);
+});
+
+test('form data loader sends only the observed readonly process method and rejects login or invalid data',async()=>{
+ const requests=[],request={post:async(url,options)=>{requests.push({url,options});return {status:()=>200,body:async()=>Buffer.from(JSON.stringify({success:true,Tables:[{TableName:'Order',FormTable:true,Rows:[{Number:'123'}]}]}))};}};
+ const tables=await loadData(request,new URL('https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/test.aspx?tid=21&pid=11'));
+ assert.equal(tables[0].Rows[0].Number,'123');assert.equal(requests[0].url,'https://bpm.skyworthdigital.com/YZSoft/BPM/XMLService/DataProvider.ashx');assert.match(requests[0].options.data,/GetFormProcessData<\/Method>11<\/PID>/);assert.equal(requests[0].options.maxRedirects,0);
+ await assert.rejects(loadData({post:async()=>({status:()=>302})},new URL('https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/test.aspx?tid=21&pid=11')),/会话/);
+ await assert.rejects(loadData({post:async()=>({status:()=>200,body:async()=>Buffer.from('{"success":false}')})},new URL('https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/test.aspx?tid=21&pid=11')),/数据/);
+});
test('real todo routes retain instance, node, received time, version and V4 detail, excluding inform endpoints',async t=>{
const calls=[],server=http.createServer((req,res)=>{calls.push(req.url);if(req.url==='/')return res.end('');const v4=req.url.includes('work_v4');res.setHeader('Content-Type','application/json');res.end(JSON.stringify({total:v4?1:0,children:v4?[{taskId:'11',processInstanceId:21,processVersion:'1.4',processName:'备损订单更改评审',activityName:'订单专员(订单通知书)',startTime:'2026-10-19T09:01:00',serialNum:'SN11',processInstanceSubject:'订单号:123机芯号:ABC',executionPointerId:'https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/test.aspx?tid=21&pid=11'}]:[]}));});
await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>server.close(r)));
@@ -15,9 +35,9 @@ test('form URL boundaries reject credentials, redirects, arbitrary endpoints and
for(const value of [base+'&action=submit',base.replace('bpm.skyworthdigital.com','evil.test'),base.replace('https://','https://u:p@'),base.replace('/YZSoft/Forms/XForm/','/Redirect/'),'file:///tmp/x.aspx?tid=21&pid=11'])assert.throws(()=>detailURL(value));
});
test('readonly capture blocks page scripts, external requests and form submission, freezes actual field values',async t=>{
- let mutations=0;const server=http.createServer((req,res)=>{if(req.method==='POST'||req.url.includes('mutate'))mutations++;res.setHeader('Content-Type','text/html');res.end('');});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>server.close(r)));
+ let mutations=0;const server=http.createServer((req,res)=>{if(req.url==='/YZSoft/BPM/XMLService/DataProvider.ashx'){res.setHeader('Content-Type','application/json');return res.end(JSON.stringify({success:true,Tables:[{TableName:'Order',FormTable:true,Rows:[{Number:'123',Change:'actual'}]},{TableName:'Lines',FormTable:true,Rows:[{Value:'line-one'},{Value:'line-two'}]}]}));}if(req.method==='POST'||req.url.includes('mutate'))mutations++;res.setHeader('Content-Type','text/html');res.end('');});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>server.close(r)));
const manager={run:(_,fn)=>fn(),authorize(){},sessions:new Map(),vault:()=>({read:async()=>({storageState:{cookies:[],origins:[]}})})},provider=new BpmOrderProvider({manager,allowLocal:true});
- const result=await provider.capture({id:'c'},{},{detailUrl:`http://127.0.0.1:${server.address().port}/form.aspx?tid=1&pid=2`,processVersion:'1.4',title:'订单号:123'});assert.equal(result.sample.fields['Order.Number'],'123');assert.equal(mutations,0);assert.doesNotMatch(result.snapshot.html,/