diff --git a/src/modules/bpm/list-client.cjs b/src/modules/bpm/list-client.cjs index dfcdbb9..d57a37c 100644 --- a/src/modules/bpm/list-client.cjs +++ b/src/modules/bpm/list-client.cjs @@ -21,9 +21,9 @@ function normalizeArrival(row,source){ 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}={}){ + constructor({baseURL='https://bpmn.skyworthdigital.com/',pageSize=100,allowLocal=false,sources=SOURCES,normalize=normalizeArrival}={}){ 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; + this.baseURL=u.href;this.pageSize=pageSize;this.sources=sources;this.normalize=normalize; } async scan(storageState){ if(!storageState)throw fail('BPM 会话需要续登。',401); @@ -39,13 +39,13 @@ class BpmListClient{ 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){ + for(const [source,route]of this.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);} + for(const raw of data.children){const row=this.normalize(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 列表分页不完整,请重新扫描。'); } diff --git a/src/modules/bpm/order-provider.cjs b/src/modules/bpm/order-provider.cjs new file mode 100644 index 0000000..3e3188f --- /dev/null +++ b/src/modules/bpm/order-provider.cjs @@ -0,0 +1,54 @@ +'use strict'; +const {BpmTodoClient}=require('./todo-client.cjs'); +const {loadPlaywright,browserOptions}=require('../../platform/browser.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); + 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:'尚未完成真实待办与表单采集检查。'};} + 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('此连接正在登录窗口中使用。'); + const saved=await this.manager.vault().read(connection.id);if(!saved?.storageState)throw fail('BPM 会话未保存,请前往 BPM 连接完成登录核验。',401); + 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;} + 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=>{ + 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}); + if(!response||response.status()!==200||page.url()!==url.href)throw fail('BPM 表单读取失败或登录已失效,请续登后重试。',401); + const snapshot=await page.evaluate(()=>{ + const copy=document.documentElement.cloneNode(true),fields=[],seen=new Map(); + for(const el of document.querySelectorAll('[xdatabind]')){ + const key=el.getAttribute('xdatabind');if(!key||key.length>250)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; + 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);} + 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)}; + }); + 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||''); + if(!snapshot.processVersion)throw fail('待办未提供流程版本,需要核验版本来源。'); + 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();} + }); + } +} +module.exports={BpmOrderProvider,detailURL}; diff --git a/src/modules/bpm/todo-client.cjs b/src/modules/bpm/todo-client.cjs new file mode 100644 index 0000000..d206ec2 --- /dev/null +++ b/src/modules/bpm/todo-client.cjs @@ -0,0 +1,12 @@ +'use strict'; +const {BpmListClient,normalizeArrival}=require('./list-client.cjs'); +// Observed portal sources: Yiez/workflow/worklist/Worklist.js and +// Skyworth/ToDoV2/panel/WorklistV4Panel.js (8.30x.014). Inform lists are excluded. +const TODO_SOURCES=[['portal-v8','bpm/worklist'],['portal-v4','skyworth/todo/v2/workflow/get_process_of_work_v4']]; +function normalizeTodo(raw,source){ + const row=normalizeArrival(raw,source); + if(!['string','number'].includes(typeof raw.processInstanceId)||!String(raw.processInstanceId))throw Object.assign(new Error('待办缺少流程实例标识。'),{status:502}); + return {source:'todo',portalSource:source,taskId:row.taskId,instanceId:String(raw.processInstanceId),revision:raw.revision??0,processName:row.processName,nodeName:row.activityName,receivedAt:row.arrivedAt,serialNum:row.serialNum,title:row.subject,processVersion:String(raw.processVersion??''),detailUrl:source==='portal-v4'&&typeof raw.executionPointerId==='string'?raw.executionPointerId:undefined}; +} +class BpmTodoClient extends BpmListClient{constructor(options={}){super({...options,sources:TODO_SOURCES,normalize:normalizeTodo});}} +module.exports={BpmTodoClient,normalizeTodo,TODO_SOURCES}; diff --git a/src/modules/dashboard/api.cjs b/src/modules/dashboard/api.cjs index 7b5820e..1871373 100644 --- a/src/modules/dashboard/api.cjs +++ b/src/modules/dashboard/api.cjs @@ -12,7 +12,7 @@ const handled=(...args)=>{reply(...args);return true;}; } if(route==='/api/settings') { if(request.method==='GET')return handled(200,store.settings()); - if(request.method==='POST'){if(user.role!=='admin')fail(403,'仅管理员可以修改配置。');return handled(200,store.saveSettings(body,body.version,user.username));} + if(request.method==='POST'){if(user.role!=='admin')fail(403,'仅管理员可以修改配置。');if(Object.hasOwn(body,'groups')||Object.hasOwn(body,'templates'))fail(410,'旧群组与通用模板写入已停用,请在分类规则维护收件人,在邮件模板维护类别关联。');return handled(200,store.saveSettings({...body,schedule:{...store.settings().schedule,...body.schedule}},body.version,user.username));} } if(route==='/api/jobs' && request.method==='GET')return handled(200,{jobs:store.jobs().map(publicJob)}); if(route==='/api/audit' && request.method==='GET')return handled(200,{audit:store.audit()}); diff --git a/src/modules/mail/api.cjs b/src/modules/mail/api.cjs index 2805468..56d772b 100644 --- a/src/modules/mail/api.cjs +++ b/src/modules/mail/api.cjs @@ -6,6 +6,10 @@ async function mailApi({mail,workspace,user,route,method,body,request,response,r if(method==='POST'&&user.role!=='admin')fail('仅管理员可以维护邮箱和确认模板。',403); if(route==='/api/mail'&&method==='GET'){reply(200,{historyOnly:mail.historyOnly===true,channels:store.channels(),templates:store.templates(),receipts:store.receipts(),sends:store.sends()});return true;} const audit=(action,detail)=>workspace?.record(user,action,detail); + if(route==='/api/mail/templates/categories'){ + if(method==='GET'){reply(200,{categories:require('../order-rules/catalog.cjs').seedRules().map(({id,name})=>({id,name})),bindings:store.categoryBindings()});return true;} + if(method==='POST'){if(mail.historyOnly)fail('只读邮件空间不能修改类别关联。',409);const saved=store.bindCategory(body);audit('mail.category.bind',saved.categoryId);reply(200,saved);return true;} + } if(route==='/api/mail/channels'&&method==='POST'){ if(!secureBpmTransport(request,trustedProxy))fail('请在部署机本地或 HTTPS 页面维护邮箱账号。',403); if(mail.historyOnly&&body?.readOnly!==true)fail('此空间只允许配置只读 IMAP 邮箱。',409); diff --git a/src/modules/mail/store.cjs b/src/modules/mail/store.cjs index 1d71500..571bd7b 100644 --- a/src/modules/mail/store.cjs +++ b/src/modules/mail/store.cjs @@ -57,6 +57,17 @@ class MailStore{ template(id){const r=this.db.prepare('SELECT * FROM templates WHERE id=?').get(id);if(!r)fail('模板不存在。',404);return {...this.decode(id,r.payload),id:r.id,channelId:r.channel_id,scope:r.scope,status:r.status,version:r.version,baseId:r.base_id,createdAt:r.created_at};} templates(){return ['pending','active','archived','rejected'].flatMap(status=>this.db.prepare('SELECT id,channel_id,scope,status,version,created_at,summary FROM templates WHERE status=? ORDER BY created_at DESC,rowid DESC LIMIT 200').all(status).map(r=>({...JSON.parse(r.summary),id:r.id,channelId:r.channel_id,scope:r.scope,status:r.status,version:r.version,createdAt:r.created_at})));} stats(){return Object.fromEntries(this.db.prepare('SELECT status,COUNT(*) AS count FROM templates GROUP BY status').all().map(r=>[r.status,r.count]));} + categoryBindings(){return JSON.parse(this.db.prepare("SELECT value FROM meta WHERE key='categoryBindings'").get()?.value||'[]');} + bindCategory(input){return this.transaction(()=>{ + const categories=require('../order-rules/catalog.cjs').seedRules(); + if(!input||Object.keys(input).some(k=>!['categoryId','templateId','version'].includes(k))||!categories.some(c=>c.id===input.categoryId)||typeof input.templateId!=='string')fail('请选择有效的 Excel 类别和模板。'); + const bindings=this.categoryBindings(),old=bindings.find(b=>b.categoryId===input.categoryId); + if(input.version!==(old?.version||0))fail('类别模板关联已变化,请刷新后重试。',409); + if(input.templateId&&this.template(input.templateId).status!=='active')fail('只能关联已确认生效的模板。',409); + const saved={categoryId:input.categoryId,templateId:input.templateId,version:(old?.version||0)+1}; + this.db.prepare("INSERT INTO meta VALUES('categoryBindings',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(JSON.stringify([...bindings.filter(b=>b.categoryId!==input.categoryId),saved]));return saved; + });} + categoryTemplate(categoryId){const binding=this.categoryBindings().find(b=>b.categoryId===categoryId);if(!binding?.templateId)return null;const template=this.template(binding.templateId);if(template.status!=='active')fail('类别关联的模板已变为历史版本,请重新确认关联。',409);return {...template,bindingVersion:binding.version};} activeId(channelId,scope){return this.db.prepare("SELECT id FROM templates WHERE channel_id=? AND scope=? AND status='active'").get(channelId,scope)?.id||null;} active(channelId,scope){const r=this.db.prepare("SELECT id FROM templates WHERE channel_id=? AND scope=? AND status='active'").get(channelId,scope);return r?this.template(r.id):null;} confirm(id,input,actor){return this.transaction(()=>{const t=this.template(id);if(t.status!=='pending'||input.version!==t.version)fail('模板状态已变化,请刷新。',409);if(t.channelId==='legacy'){this.row(input.channelId);t.channelId=input.channelId;}const subject=text(input.subject,'邮件标题',300);if(typeof input.scope!=='string'||input.scope.length>80||/[\[\]\x00-\x1f]/.test(input.scope))fail('产品线格式无效。');const scope=input.scope.trim(),current=this.activeId(t.channelId,scope);if(current!==(scope===t.scope?t.baseId:null))fail('该范围已有更新的模板,请重新导入后确认。',409); diff --git a/src/modules/notifications/api.cjs b/src/modules/notifications/api.cjs index 95dbaa9..a621030 100644 --- a/src/modules/notifications/api.cjs +++ b/src/modules/notifications/api.cjs @@ -4,11 +4,6 @@ async function notificationApi({notifications,workspace,user,route,method,body,r if(!route.startsWith('/api/notifications'))return false;if(!notifications)fail('业务通知服务暂不可用。',503); if(route==='/api/notifications'&&method==='GET'){reply(200,{settings:notifications.store.settings(),items:notifications.store.items(),batches:notifications.store.batches()});return true;} if(method!=='POST')fail('没有找到此通知操作。',404); - if(user.role==='viewer')fail('只读成员不能提交通知数据或修改配置。',403); - if(route==='/api/notifications/settings'){if(user.role!=='admin')fail('仅管理员可以修改业务通知配置。',403);const saved=notifications.saveSettings(body);workspace?.record(user,'保存业务通知配置',saved.enabled?'已启用':'已暂停');reply(200,saved);return true;} - if(route==='/api/notifications/preview'||route==='/api/notifications/events'){if(!body||Object.keys(body).some(k=>k!=='data'))fail('请提交来源数据对象。');const preview=route.endsWith('/preview');const result=preview?notifications.preview(body.data):notifications.ingest(body.data);if(!preview)workspace?.record(user,'通知数据入队',result.sourceId);reply(preview?200:201,result);return true;} - const retry=/^\/api\/notifications\/items\/([\w-]+)\/retry$/.exec(route);if(retry){if(user.role!=='admin')fail('仅管理员可以重新入队次数耗尽通知。',403);const result=notifications.retryItem(retry[1],body,user.username);workspace?.record(user,'重新入队次数耗尽通知',retry[1]+':'+body.note.trim());reply(200,result);return true;} - const match=/^\/api\/notifications\/batches\/([\w-]+)\/resolve$/.exec(route);if(match){if(user.role!=='admin')fail('仅管理员可以核验发送结果。',403);const result=notifications.resolve(match[1],body,user.username);workspace?.record(user,'核验通知发送结果',match[1]);reply(200,result);return true;} - fail('没有找到此通知操作。',404); + fail('旧通用通知入口已停用,请在业务设置的分类规则中维护 Excel 类别;历史记录保留只读查询。',410); } module.exports={notificationApi}; diff --git a/src/modules/storage/order-archive.cjs b/src/modules/storage/order-archive.cjs new file mode 100644 index 0000000..e442ed0 --- /dev/null +++ b/src/modules/storage/order-archive.cjs @@ -0,0 +1,57 @@ +'use strict'; +const path=require('node:path'); +const fs=require('node:fs/promises'); +const crypto=require('node:crypto'); +const {segments,inside}=require('./files.cjs'); +const {renderSnapshot}=require('../pdf/exporter.cjs'); +const fail=message=>Object.assign(new Error(message),{status:409}); +const day=value=>new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date(value)); +function targetFor(storage,directory){ + if(typeof directory!=='string'||!directory.startsWith('\\\\'))throw fail('请在分类规则选择已配置服务器的共享目录。'); + const parts=directory.slice(2).replace(/\//g,'\\').split('\\');segments(parts.slice(2).join('/')); + const candidates=storage.store.servers().filter(s=>s.enabled&&s.host.toLowerCase()===parts[0]?.toLowerCase()&&s.share.toLowerCase()===parts[1]?.toLowerCase()).map(server=>{ + const root=segments(server.directory),rest=parts.slice(2);return {server,root,rest}; + }).filter(({root,rest})=>root.every((p,i)=>p.toLowerCase()===rest[i]?.toLowerCase())).sort((a,b)=>b.root.length-a.root.length); + const selected=candidates[0];if(!selected||!selected.server.state.readable||!selected.server.state.writable)throw fail('规则目录没有匹配的已启用且读写核验成功的存储服务器,请前往存储服务器检查。'); + return {server:selected.server,relative:selected.rest.slice(selected.root.length).join('/')}; +} +class OrderArchiveProvider{ + constructor({storage,outputDir,renderer=renderSnapshot,clock=()=>new Date()}={}){this.storage=storage;this.outputDir=path.resolve(outputDir,'order-execution');this.renderer=renderer;this.clock=clock;this.last=null;} + capabilities(){return {automaticArchive:!!this.last?.success,checkedAt:this.last?.at,message:this.last?.message||'尚无经过实际生成和共享目录读回校验的订单归档。'};} + async probe(rule){ + try{ + const target=targetFor(this.storage,rule.archiveDirectory);await this.storage.check(target.server.id); + const generated=await this.renderer({html:'

订单归档能力核验

',styles:[],images:[],metadata:{order:'probe',project:'probe',model:'probe',serial:'probe'}},{outputDir:this.outputDir}); + const [root,file]=await Promise.all([fs.realpath(this.outputDir),fs.realpath(generated.path)]);if(!inside(root,file)||file===root)throw fail('核验输出超出工作目录。'); + const bytes=await fs.readFile(file);if(bytes.subarray(0,5).toString()!=='%PDF-')throw fail('PDF 运行环境检查失败。'); + this.last={success:true,at:this.clock().toISOString(),message:'PDF 运行环境及目标共享目录读写检查成功。'};return {...this.capabilities(),pdfExport:true}; + }catch(error){this.last={success:false,at:this.clock().toISOString(),message:error.message};throw error;} + } + async archive({order,rule,snapshot,taskId}){ + const event=order.event||order,chosen=rule.filenameDate==='appDate'?event.appDate:rule.filenameDate==='receivedAt'?event.receivedAt:this.clock(); + if(!['appDate','receivedAt','archiveDate'].includes(rule.filenameDate)||!Number.isFinite(+new Date(chosen)))throw fail('规则的文件名日期来源缺失或无效。'); + const target=targetFor(this.storage,rule.archiveDirectory),safe=v=>String(v||'').replace(/[<>:"/\\|?*\x00-\x1f]/g,'_').replace(/[. ]+$/g,'').slice(0,65); + const filename=[event.orderNo,day(chosen),event.serialNum||event.documentNum].map(safe).join('_')+'.pdf';segments(filename); + if(!event.orderNo||!(event.serialNum||event.documentNum))throw fail('归档文件缺少订单号或流程流水号。'); + // Renderer public extension contract remains its original four-field filename. + const renderInput={...snapshot,metadata:{order:String(event.orderNo),project:'流程归档',model:'订单',serial:String(event.serialNum||event.documentNum)}}; + let generated; + try{ + generated=await this.renderer(renderInput,{outputDir:this.outputDir}); + const [root,file]=await Promise.all([fs.realpath(this.outputDir),fs.realpath(generated.path)]);if(!inside(root,file)||file===root)throw fail('生成文件超出订单输出目录。'); + const local=await fs.readFile(file),digest=crypto.createHash('sha256').update(local).digest('hex');if(local.subarray(0,5).toString()!=='%PDF-')throw fail('订单 PDF 内容无效。'); + const receipt=await this.storage.run(target.server.id,async(server,signal)=>{ + const saved=await this.storage.operation(server,'archive',[file,filename,target.relative],signal); + const check=await this.storage.operation(server,'readFile',[saved.relativePath],signal),bytes=Buffer.from(check.bytes); + if(bytes.length!==local.length||crypto.createHash('sha256').update(bytes).digest('hex')!==digest||saved.sha256!==digest||saved.bytes!==bytes.length)throw fail('共享目录归档读回校验失败。');return saved; + }); + const evidence={archivedAt:this.clock().toISOString(),files:[{name:receipt.filename,path:path.win32.join('\\\\'+target.server.host,target.server.share,...segments(target.server.directory),...segments(receipt.relativePath)),sha256:digest,size:local.length,kind:'pdf'}]}; + this.last={success:true,at:evidence.archivedAt,message:'PDF 已生成、归档并读回校验。'};return evidence; + }catch(error){this.last={success:false,at:this.clock().toISOString(),message:error.message};throw error;} + } + async read(file){ + const directory=path.win32.dirname(file.path),target=targetFor(this.storage,directory); + const result=await this.storage.readFile(target.server.id,[target.relative,path.win32.basename(file.path)].filter(Boolean).join('/'));return Buffer.from(result.bytes); + } +} +module.exports={OrderArchiveProvider,targetFor}; diff --git a/src/modules/workspace/api.cjs b/src/modules/workspace/api.cjs index 628ed11..12cff21 100644 --- a/src/modules/workspace/api.cjs +++ b/src/modules/workspace/api.cjs @@ -9,7 +9,7 @@ function workspaceApi({workspace,store,user,route,method,body,reply,bpmSessions} const action=/^\/api\/exceptions\/([\w-]+)\/action$/.exec(route);if(action){reply(200,workspace.actOnException(action[1],body,user,members()));return true;} if(route==='/api/connections'){reply(201,workspace.createConnection(body,user,members()));return true;} const disable=/^\/api\/connections\/([\w-]+)\/disable$/.exec(route);if(disable){if(Object.keys(body).length)throw Object.assign(new Error('停用连接不接受额外数据。'),{status:400});reply(200,workspace.disableConnection(disable[1],user));return true;} - if(route==='/api/supervisor'){reply(200,workspace.saveSupervisor(body,user,members()));return true;} + if(route==='/api/supervisor')throw Object.assign(new Error('监管草稿已停用,请在系统健康和异常待办中查看实际运行结果。'),{status:410}); return false; } module.exports={workspaceApi}; diff --git a/tests/app/closure-providers.test.cjs b/tests/app/closure-providers.test.cjs new file mode 100644 index 0000000..95d8d22 --- /dev/null +++ b/tests/app/closure-providers.test.cjs @@ -0,0 +1,35 @@ +'use strict'; +const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path'),http=require('node:http'); +const {BpmTodoClient}=require('../../src/modules/bpm/todo-client.cjs'); +const {BpmOrderProvider,detailURL}=require('../../src/modules/bpm/order-provider.cjs'); +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'); +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))); + const client=new BpmTodoClient({baseURL:`http://127.0.0.1:${server.address().port}/`,allowLocal:true}),rows=await client.scan({cookies:[],origins:[]});assert.equal(rows.length,1);assert.equal(rows[0].source,'todo');assert.equal(rows[0].nodeName,'订单专员(订单通知书)');assert.equal(rows[0].processVersion,'1.4');assert.equal(rows[0].receivedAt,'2026-10-19T01:01:00.000Z');assert.equal(rows[0].instanceId,'21');assert.ok(calls.every(u=>!u.includes('inform'))); +}); +test('form URL boundaries reject credentials, redirects, arbitrary endpoints and mutation query fields',()=>{ + const base='https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/test.aspx?tid=21&pid=11';assert.equal(detailURL(base).href,base); + 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))); + 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,/{ + const dir=await fs.mkdtemp(path.join(os.tmpdir(),'closure-archive-'));t.after(()=>fs.rm(dir,{recursive:true,force:true}));const share=path.join(dir,'share');await fs.mkdir(share);const area=new FileArea(share),server={id:'s',host:'nas',share:'orders',directory:'',enabled:true,state:{readable:true,writable:true}};let corrupt=false; + const storage={store:{servers:()=>[server]},run:(_,fn)=>fn(server,new AbortController().signal),operation:async(_,method,args)=>{const result=await area[method](...args);if(corrupt&&method==='readFile')result.bytes=Buffer.from('%PDF-wrong');return result;},readFile:(_,relative)=>area.readFile(relative)}; + const renderer=async(_,options)=>{await fs.mkdir(options.outputDir,{recursive:true});const file=path.join(options.outputDir,'test.pdf');await fs.writeFile(file,'%PDF-fixture');return {path:file};},provider=new OrderArchiveProvider({storage,outputDir:dir,renderer}); + const input={order:{event:{orderNo:'123',serialNum:'SN',receivedAt:'2026-10-19T01:00:00Z'}},rule:{archiveDirectory:'\\\\nas\\orders\\category',filenameDate:'receivedAt'},snapshot:{html:'

order

'},taskId:'task'}; + const result=await provider.archive(input);assert.match(result.files[0].path,/123_2026-10-19_SN\.pdf$/);assert.equal(result.files[0].size,12);assert.equal((await provider.read(result.files[0])).toString(),'%PDF-fixture'); + assert.throws(()=>targetFor(storage,'\\\\nas\\other\\category'));assert.throws(()=>targetFor(storage,'\\\\nas\\orders\\..\\outside')); + corrupt=true;await assert.rejects(provider.archive(input),/读回/);assert.equal(provider.capabilities().automaticArchive,false); +}); +test('category bindings require an explicit active template and optimistic version, persist tombstones',async t=>{ + const dir=await fs.mkdtemp(path.join(os.tmpdir(),'closure-mail-')),store=new MailStore(dir);t.after(async()=>{store.close();await fs.rm(dir,{recursive:true,force:true});});store.migrateLegacy({subject:'test',body:'body'});const pending=store.templates()[0];assert.throws(()=>store.bindCategory({categoryId:'bs-change',templateId:pending.id,version:0}),e=>e.status===409);assert.equal(store.categoryBindings().length,0); + const parsed={subject:'test',scope:'',text:'body',html:'',sender:'source@company.test',attachments:[]};const channel=store.saveChannel({name:'test',email:'test@company.test',smtp:{host:'mail.test',port:465,security:'tls',user:'u',password:'test'},imap:{host:'mail.test',port:993,security:'tls',user:'u',password:'test'},senders:['source@company.test'],enabled:false});const p=store.ingest(channel.id,'1',1,parsed,Buffer.from('fixture'),1);store.confirm(p.id,{version:1,subject:'test',scope:'',useText:false},'admin'); + const bound=store.bindCategory({categoryId:'bs-change',templateId:p.id,version:0});assert.equal(bound.version,1);assert.equal(store.categoryTemplate('bs-change').id,p.id);assert.throws(()=>store.bindCategory({categoryId:'bs-change',templateId:'',version:0}),e=>e.status===409);store.bindCategory({categoryId:'bs-change',templateId:'',version:1});assert.equal(store.categoryTemplate('bs-change'),null);assert.equal(store.categoryBindings()[0].version,2); +}); diff --git a/tests/notifications/notifications-http.test.cjs b/tests/notifications/notifications-http.test.cjs index c7a8ce7..36956bc 100644 --- a/tests/notifications/notifications-http.test.cjs +++ b/tests/notifications/notifications-http.test.cjs @@ -1,16 +1,10 @@ 'use strict'; const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs/promises');const os=require('node:os');const path=require('node:path');const {Store}=require('../../src/modules/dashboard/store.cjs');const {NotificationStore}=require('../../src/modules/notifications/store.cjs');const {NotificationService}=require('../../src/modules/notifications/service.cjs');const {WorkspaceStore}=require('../../src/modules/workspace/store.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs'); -test('notification HTTP exposes configurable mapping and preview without sending, with role and origin checks',async t=>{ +test('retired notification HTTP preserves history and rejects all writes with clear reason',async t=>{ const dir=await fs.mkdtemp(path.join(os.tmpdir(),'notice-http-')),store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');for(const role of ['operator','viewer'])store.addUser({username:role,password:'Test-password-123',role},'admin');const notificationStore=new NotificationStore(path.join(dir,'notifications')),notifications=new NotificationService({store:notificationStore,mail:{},settings:()=>store.settings()}),workspace=new WorkspaceStore(path.join(dir,'workspace')),server=createDashboard({store,notifications,workspace,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(async()=>{await notifications.stop();server.closeAllConnections();await new Promise(r=>server.close(r));notificationStore.close();workspace.close();await fs.rm(dir,{recursive:true,force:true});});const base='http://127.0.0.1:'+server.address().port,call=(route,body,cookie,origin=base)=>fetch(base+route,{method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{'Content-Type':'application/json',Origin:origin}),...(cookie?{Cookie:cookie}:{})},body:body===undefined?undefined:JSON.stringify(body)}),login=async username=>(await call('/api/login',{username,password:'Test-password-123'})).headers.get('set-cookie').split(';')[0]; - assert.equal((await call('/api/notifications')).status,401);const admin=await login('admin'),operator=await login('operator'),viewer=await login('viewer');const config=notificationStore.settings();assert.equal((await call('/api/notifications/settings',config,operator)).status,403);assert.equal((await call('/api/notifications/settings',config,admin,'https://evil.test')).status,403);assert.equal((await call('/api/notifications/settings',config,admin)).status,200); - const data={id:'external-1',industry:'待配置产业',brief:'简要说明原文\n保持换行'};const preview=await(await call('/api/notifications/preview',{data},operator)).json();assert.equal(preview.event.brief,data.brief);assert.equal(notificationStore.items().length,0); - assert.equal((await call('/api/notifications/events',{data},viewer)).status,403);assert.equal((await call('/api/notifications/events',{data},operator)).status,201);assert.equal(notificationStore.items().length,1); - assert.equal((await call('/api/notifications',undefined,viewer)).status,200); - notificationStore.saveSettings({...notificationStore.settings(),maxAttempts:1});const item=notificationStore.items()[0],batchId=notificationStore.prepare([item],{to:[]});notificationStore.mark(batchId,'failed','fixture SMTP failure'); - const retry='/api/notifications/items/'+item.id+'/retry',evidence={batchId,note:'已修复 SMTP 并核实未发送'}; - assert.equal((await call(retry,evidence,viewer)).status,403);assert.equal((await call(retry,evidence,operator)).status,403); - assert.equal((await call(retry,{batchId,note:''},admin)).status,400);assert.equal((await call(retry,evidence,admin)).status,200); - assert.equal(notificationStore.items()[0].attempts,0);assert.equal((await call(retry,evidence,admin)).status,409); - const audit=workspace.db.prepare('SELECT value FROM audit').all().map(row=>JSON.parse(row.value));assert.equal(audit.filter(row=>row.action==='重新入队次数耗尽通知').length,1);assert.match(audit.find(row=>row.action==='重新入队次数耗尽通知').detail,/SMTP/); - + assert.equal((await call('/api/notifications')).status,401);const admin=await login('admin'),operator=await login('operator'),viewer=await login('viewer'); + const data={id:'historical-1',industry:'历史类别',brief:'历史内容'};notifications.ingest(data);const before=notificationStore.items(); + for(const cookie of [admin,operator,viewer])for(const route of ['/api/notifications/settings','/api/notifications/preview','/api/notifications/events','/api/notifications/items/old/retry','/api/notifications/batches/old/resolve']){const response=await call(route,{data},cookie);assert.equal(response.status,410);assert.match((await response.json()).error,/停用|分类规则/);} + assert.equal((await call('/api/notifications/settings',{},admin,'https://evil.test')).status,403); + const history=await (await call('/api/notifications',undefined,viewer)).json();assert.deepEqual(history.items,before);assert.deepEqual(notificationStore.items(),before); }); diff --git a/tests/workspace/workspace-http.test.cjs b/tests/workspace/workspace-http.test.cjs index 78abc1d..b4b2798 100644 --- a/tests/workspace/workspace-http.test.cjs +++ b/tests/workspace/workspace-http.test.cjs @@ -13,7 +13,7 @@ test('workspace API requires authentication and roles and preserves same-origin const readerLogin=await call('/api/login',{username:'reader',password:'Test-password-123'});const reader=readerLogin.headers.get('set-cookie').split(';')[0]; assert.equal((await call('/api/workspace',undefined,reader)).status,200);assert.equal((await call('/api/exceptions',{title:'示例',component:'pdf',priority:'normal',description:'',owner:''},reader)).status,403); const opLogin=await call('/api/login',{username:'operator',password:'Test-password-123'});const operator=opLogin.headers.get('set-cookie').split(';')[0]; - assert.equal((await call('/api/connections',{name:'示例连接',owner:'operator'},operator)).status,403);assert.equal((await call('/api/supervisor',{version:1,defaultOwner:'operator',notifyChannel:'manual',maxAttempts:1},operator)).status,403); + assert.equal((await call('/api/connections',{name:'示例连接',owner:'operator'},operator)).status,403);assert.equal((await call('/api/supervisor',{version:1,defaultOwner:'operator',notifyChannel:'manual',maxAttempts:1},operator)).status,410); const made=await call('/api/exceptions',{title:'示例',component:'pdf',priority:'normal',description:'',owner:''},operator);assert.equal(made.status,201);const item=await made.json();const claimed=await call('/api/exceptions/'+item.id+'/action',{version:1,action:'claim'},operator);assert.equal(claimed.status,200);assert.equal((await claimed.json()).owner,'operator'); assert.equal((await call('/api/connections',{name:'示例连接',owner:'operator'},cookie)).status,201);assert.equal((await call('/workspace.js')).status,200); });