diff --git a/src/modules/assistant/diagnostic-context.cjs b/src/modules/assistant/diagnostic-context.cjs index b076d0e..e37fd96 100644 --- a/src/modules/assistant/diagnostic-context.cjs +++ b/src/modules/assistant/diagnostic-context.cjs @@ -7,9 +7,19 @@ function canReadJob(deps,user,job){ const connectionId=job?.connectionId||job?.metadata?.connectionId||job?.source?.connectionId; return canReadConnection(deps.workspace,user,connectionId); } -function diagnosticContext(deps,user){ +function canReadArchive(deps,user,archive){ + if(user.role==='admin'||canReadJob(deps,user,archive))return true; + try{const job=typeof deps.dashboard?.job==='function'?deps.dashboard.job(archive?.jobId):(deps.dashboard?.jobs?.()||[]).find(j=>j.jobId===archive?.jobId);return canReadJob(deps,user,job);}catch{return false;} +} +function diagnosticContext(deps,user,diagnostic){ const value=require('./policy.cjs').snapshot(deps,user); - return {...value,observedAt:value.at,scope:{runs:{limit:10},archives:{limit:15},jobs:{limit:15},exceptions:{limit:15},business:{limit:15}},commands:COMMANDS}; + const result={...value,observedAt:value.at,scope:{runs:{limit:10},archives:{limit:15},jobs:{limit:15},exceptions:{limit:15},business:{limit:15}},commands:COMMANDS}; + if(diagnostic?.targetId){ + const checked=validateDiagnostic(diagnostic,deps,user); + if(checked.command==='archive'){const a=deps.storage.store.archives().find(item=>item.id===checked.targetId);result.selectedTarget={id:a.id,serverId:a.serverId,jobId:a.jobId,status:a.status,orderNumber:a.orderNumber,error:require('../../shared/redact.cjs').redact(a.error)};} + else result.selectedTarget=(checked.command==='bpm'?value.connections:value.servers).find(item=>item.id===checked.targetId); + } + return result; } function validateDiagnostic(value,deps,user){ if(value===undefined)return undefined; @@ -19,8 +29,9 @@ function validateDiagnostic(value,deps,user){ return {command:value.command}; } if(typeof value.targetId!=='string'||!/^[\w-]{1,100}$/.test(value.targetId))throw fail('请选择有效诊断目标。'); + if(value.command==='archive'){const archive=deps.storage?.store.archives().find(a=>a.id===value.targetId);if(!archive||!canReadArchive(deps,user,archive))throw fail('诊断目标不可见或已变化。',403);return {command:value.command,targetId:value.targetId};} const current=diagnosticContext(deps,user),rows={bpm:current.connections,storage:current.servers,archive:current.archives}[value.command]; if(!rows.some(item=>item.id===value.targetId))throw fail('诊断目标不可见或已变化。',403); return {command:value.command,targetId:value.targetId}; } -module.exports={diagnosticContext,validateDiagnostic,canReadJob,COMMANDS}; +module.exports={diagnosticContext,validateDiagnostic,canReadJob,canReadArchive,COMMANDS}; diff --git a/src/modules/assistant/policy.cjs b/src/modules/assistant/policy.cjs index f3e85d6..68603c3 100644 --- a/src/modules/assistant/policy.cjs +++ b/src/modules/assistant/policy.cjs @@ -7,8 +7,8 @@ function snapshot({workspace,scanner,storage,dashboard,orderRules,orderExecution const connections=w.connections.filter(authorized).map(c=>({id:c.id,name:redact(c.name),status:c.status,checkedAt:c.checkedAt})),ids=new Set(connections.map(c=>c.id)); const runs=(scanner?.store.status().runs||[]).filter(r=>ids.has(r.connectionId)).slice(0,10).map(r=>({connectionId:r.connectionId,status:r.status,startedAt:r.startedAt,finishedAt:r.finishedAt,seen:r.seen,added:r.added,message:redact(r.message)})); const servers=(storage?.store.servers()||[]).map(s=>({id:s.id,name:redact(s.name),enabled:s.enabled,state:{readable:s.state.readable,writable:s.state.writable,message:redact(s.state.message)}})); - const readable=require('./diagnostic-context.cjs').canReadJob,jobRows=(dashboard?.recentJobs?dashboard.recentJobs(100):dashboard?.jobs()||[]),jobMap=new Map(jobRows.map(j=>[j.jobId,j])); - const archives=(storage?.store.archives()||[]).filter(a=>user.role==='admin'||readable({workspace},user,a)||readable({workspace},user,jobMap.get(a.jobId))).slice(0,15).map(a=>({id:a.id,serverId:a.serverId,jobId:a.jobId,status:a.status,orderNumber:a.orderNumber,error:redact(a.error)})); + const {canReadJob:readable,canReadArchive}=require('./diagnostic-context.cjs'),jobRows=(dashboard?.recentJobs?dashboard.recentJobs(100):dashboard?.jobs()||[]); + const archives=(storage?.store.archives()||[]).filter(a=>canReadArchive({workspace,dashboard},user,a)).slice(0,15).map(a=>({id:a.id,serverId:a.serverId,jobId:a.jobId,status:a.status,orderNumber:a.orderNumber,error:redact(a.error)})); const jobs=jobRows.filter(j=>readable({workspace},user,j)).slice(0,15).map(j=>({jobId:j.jobId,status:j.status,orderNumber:j.metadata?.order,error:redact(j.error)})); const exceptions=w.exceptions.filter(e=>user.role==='admin'||e.owner===user.username).slice(0,15).map(e=>({id:e.id,title:redact(e.title),status:e.status,component:e.component,owner:e.owner})); return {at:new Date().toISOString(),role:user.role,connections,runs,servers,archives,jobs,exceptions,business:require('./business-context.cjs').businessContext({orderRules,workspace},user),fieldMapping:require('./field-skill.cjs').coverage({workspace,orderRules,orderExecution},user)}; @@ -23,7 +23,7 @@ function checkAction(action,deps,user){ } if(action.kind==='scan_bpm'){const c=deps.workspace?.getConnection(action.targetId);if(!c||c.status==='disabled'||!(user.role==='admin'||c.owner===user.username))throw fail('没有扫描此 BPM 连接的权限。',403);} if(action.kind==='check_storage'){if(user.role!=='admin')throw fail('存储连接检查仅管理员可执行。',403);const s=deps.storage?.store.servers().find(s=>s.id===action.targetId);if(!s?.enabled)throw fail('存储服务器不存在或已停用。',409);} - if(action.kind==='retry_archive'){const a=deps.storage?.store.archives().find(a=>a.id===action.targetId);if(!a||!['error','interrupted'].includes(a.status))throw fail('仅可重试已明确失败的归档记录。',409);if(user.role!=='admin'&&!snapshot(deps,user).archives.some(row=>row.id===a.id))throw fail('没有重试此归档的权限。',403);const s=deps.storage.store.servers().find(s=>s.id===a.serverId);if(!s?.enabled)throw fail('归档服务器不可用。',409);} + if(action.kind==='retry_archive'){const a=deps.storage?.store.archives().find(a=>a.id===action.targetId);if(!a||!['error','interrupted'].includes(a.status))throw fail('仅可重试已明确失败的归档记录。',409);if(!require('./diagnostic-context.cjs').canReadArchive(deps,user,a))throw fail('没有重试此归档的权限。',403);const s=deps.storage.store.servers().find(s=>s.id===a.serverId);if(!s?.enabled)throw fail('归档服务器不可用。',409);} return action; } function parseResponse(raw,deps,user){ diff --git a/src/modules/assistant/service.cjs b/src/modules/assistant/service.cjs index 670de10..660020b 100644 --- a/src/modules/assistant/service.cjs +++ b/src/modules/assistant/service.cjs @@ -2,7 +2,7 @@ const {fail}=require('./store.cjs'),{cleanMessage,snapshot,checkAction,parseResponse}=require('./policy.cjs'),{redact}=require('../../shared/redact.cjs'); class AssistantService{ constructor({store,runtime,journal,repairFactory,...deps}){this.store=store;this.runtime=runtime;this.journal=journal;this.repairFactory=repairFactory;this.deps=deps;this.running=new Map();this.actions=new Set();this.stopped=false;} - context(user){return require('./diagnostic-context.cjs').diagnosticContext(this.deps,user);} + context(user,diagnostic){return require('./diagnostic-context.cjs').diagnosticContext(this.deps,user,diagnostic);} async check(){const config=this.store.secretSettings();return {...await this.runtime.probe(config.runtimePath),modelConfigured:!!(config.apiBase&&config.model&&config.apiKey)};} record(id,principal,step,status,detail){return this.journal?.append({operationId:id,actor:principal.user.id,step,status,detail});} operations(principal,{beforeId}={}){const users=principal.user.role==='admin'?this.deps.dashboard?.users?.()||[]:[];return (this.journal?.list({actor:principal.user.id,isAdmin:principal.user.role==='admin',beforeId})||[]).map(e=>({...e,actorLabel:e.actor===principal.user.id?principal.user.username:users.find(u=>u.id===e.actor)?.username||e.actor}));} @@ -15,7 +15,7 @@ class AssistantService{ this.store.conversation(id,principal.user.id);if([...this.running.values()].some(r=>r.conversationId===id))throw fail('当前对话正在回复,请等待或停止。',409); if(this.running.size>=2)throw fail('助手正在处理其他对话,请稍后重试。',429); const config=this.store.secretSettings();if(!config.enabled||!config.runtimePath||!config.apiBase||!config.model||!config.apiKey)throw fail('请管理员先配置并启用 DSH 助手。',409); - const context=require('./dsh-runtime.cjs').prepareContext(JSON.parse(JSON.stringify({...this.context(principal.user),...(repair?{repair}:{}),...(diagnostic?{diagnostic:requestPayload.diagnostic}:{})},(_key,value)=>typeof value==='string'?cleanMessage(value,config.apiKey):value))); + const context=require('./dsh-runtime.cjs').prepareContext(JSON.parse(JSON.stringify({...this.context(principal.user,diagnostic),...(repair?{repair}:{}),...(diagnostic?{diagnostic:requestPayload.diagnostic}:{})},(_key,value)=>typeof value==='string'?cleanMessage(value,config.apiKey):value))); const history=this.store.history(id,principal.user.id).map(t=>({user:cleanMessage(redact(t.text),config.apiKey),assistant:cleanMessage(redact(t.reply),config.apiKey)})); const turn=this.store.beginTurn(id,principal.user.id,cleanMessage(redact(text.trim(),4000),config.apiKey),{requestId,requestPayload,diagnosticSnapshot:context}),controller=new AbortController(); if(this.journal&&config.apiKey&&!this.journal.secrets.includes(config.apiKey))this.journal.secrets.push(config.apiKey); diff --git a/tests/assistant/diagnostic-workspace-ui.test.cjs b/tests/assistant/diagnostic-workspace-ui.test.cjs index 4c066bd..05ecbae 100644 --- a/tests/assistant/diagnostic-workspace-ui.test.cjs +++ b/tests/assistant/diagnostic-workspace-ui.test.cjs @@ -35,3 +35,6 @@ test('local status commands clear an old diagnostic target before the next ordin const {page,store,assistant}=await fixture(t);assistant.deps.workspace={snapshot:()=>({connections:[{id:'bpm-a',name:'测试连接 A',owner:'admin',status:'connected'}],exceptions:[]}),getConnection:()=>({id:'bpm-a',owner:'admin'})};store.saveSettings({...store.settings(),enabled:true,runtimePath:process.execPath,apiBase:'https://fixture.example/anthropic',model:'fixture',apiKey:'TEST_ONLY_KEY',allowActions:false});await page.reload(); const input=page.getByLabel('发送给 DSH',{exact:true});await input.fill('/bpm');await input.press('Enter');await page.getByRole('option',{name:/测试连接 A/}).click();await input.fill('/status');await input.press('Enter');await page.getByRole('heading',{name:'诊断概况',exact:true}).waitFor();await input.fill('查看全部运行状态');const submitted=page.waitForRequest(r=>r.url().endsWith('/messages'));await page.getByRole('button',{name:'发送',exact:true}).click();assert.equal((await submitted).postDataJSON().diagnostic,undefined); }); +test('assistant Markdown keeps text and safe links without loading images or executable HTML',{timeout:90000},async t=>{ + const {page}=await fixture(t);const result=await page.evaluate(()=>{const host=document.createElement('div'),escape=value=>String(value).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));host.innerHTML=AssistantConversation.markdown('\n\n[bad](javascript:alert%281%29) ![remote](https://example.invalid/track.png) [safe](https://example.com/docs)\n\n```html\n\n```',escape);return {images:host.querySelectorAll('img').length,scripts:host.querySelectorAll('script').length,links:[...host.querySelectorAll('a')].map(a=>({href:a.href,rel:a.rel})),text:host.textContent};});assert.equal(result.images,0);assert.equal(result.scripts,0);assert.deepEqual(result.links,[{href:'https://example.com/docs',rel:'noopener noreferrer'}]);assert.match(result.text,//); +}); diff --git a/tests/assistant/workspace-http.test.cjs b/tests/assistant/workspace-http.test.cjs index a3cf086..529a816 100644 --- a/tests/assistant/workspace-http.test.cjs +++ b/tests/assistant/workspace-http.test.cjs @@ -25,6 +25,13 @@ test('diagnosis and recovery cannot use another connection owner\'s export or ar const data=await(await f.call('/api/assistant/context',undefined,cookie)).json();assert.deepEqual(data.jobs.map(x=>x.jobId),['own-pdf']);assert.deepEqual(data.archives.map(x=>x.id),['mine']); assert.throws(()=>require('../../src/modules/assistant/policy.cjs').checkAction({kind:'retry_archive',targetId:'secret'},f.assistant.deps,{username:'member',role:'operator'}),e=>e.status===403); }); +test('archive authorization is independent of diagnostic recent-list truncation',async t=>{ + const f=await fixture(t),user={username:'member',role:'operator'},target={id:'older',jobId:'old-job',serverId:'shared',status:'error'};f.assistant.deps.dashboard={recentJobs:()=>[],job:id=>id==='old-job'?{jobId:id,connectionId:'own'}:null}; + f.assistant.deps.storage.store.archives=()=>[...Array.from({length:16},(_,i)=>({id:'new-'+i,connectionId:'own',serverId:'shared',status:'error'})),target]; + assert.doesNotThrow(()=>require('../../src/modules/assistant/policy.cjs').checkAction({kind:'retry_archive',targetId:'older'},f.assistant.deps,user)); + assert.deepEqual(require('../../src/modules/assistant/diagnostic-context.cjs').validateDiagnostic({command:'archive',targetId:'older'},f.assistant.deps,user),{command:'archive',targetId:'older'}); + const cookie=await f.login('member'),c=await(await f.call('/api/assistant/conversations',{},cookie)).json();let actual;f.assistant.runtime.chat=async input=>{actual=input.context;return JSON.stringify({reply:'diagnosed',actions:[]});};f.store.saveSettings({...f.store.settings(),enabled:true,runtimePath:process.execPath,apiBase:'https://fixture.example/anthropic',model:'fixture',apiKey:'TEST_ONLY_KEY',allowActions:false});const sent=await f.call('/api/assistant/conversations/'+c.id+'/messages',{text:'分析旧归档',diagnostic:{command:'archive',targetId:'older'}},cookie);assert.equal(sent.status,202);const turn=await sent.json();await f.assistant.running.get(turn.id)?.task;assert.equal(actual.selectedTarget.id,'older'); +}); test('diagnostic command targets are validated at the API rather than trusted from display names',async t=>{ const f=await fixture(t),cookie=await f.login('member'),created=await(await f.call('/api/assistant/conversations',{},cookie)).json(); f.store.saveSettings({...f.store.settings(),enabled:true,runtimePath:process.execPath,apiBase:'https://fixture.example/anthropic',model:'test',apiKey:'TEST_ONLY_KEY',allowActions:false});