/** Runs against a disposable production instance; never writes to ./data or the hosted site. */ import assert from 'node:assert/strict'; import { spawn, execFile } from 'node:child_process'; import { promisify } from 'node:util'; import { mkdtemp, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { createServer } from 'node:net'; import { randomBytes } from 'node:crypto'; import { DatabaseSync } from 'node:sqlite'; const directory=await mkdtemp(join(tmpdir(),'demand-selfhost-test-')); const port=await new Promise(resolve=>{const s=createServer();s.listen(0,'127.0.0.1',()=>{const p=s.address().port;s.close(()=>resolve(p));});}); const origin=`http://127.0.0.1:${port}`; const basePath=process.env.NEXT_PUBLIC_BASE_PATH||''; const secret=()=>randomBytes(24).toString('base64url'); const initial=secret(),adminPassword=secret(),memberInitial=secret(),memberPassword=secret(); let processHandle,logs='',checks=0; const verify=(condition,message)=>{assert(condition,message);checks++;}; async function start(){ processHandle=spawn(process.execPath,['scripts/start.mjs'],{cwd:process.cwd(),env:{...process.env,NODE_ENV:'production',HOSTNAME:'127.0.0.1',PORT:String(port),APP_URL:origin,DATA_DIR:directory,INITIAL_ADMIN_USERNAME:'test_admin',INITIAL_ADMIN_PASSWORD:initial,INITIAL_ADMIN_DISPLAY_NAME:'测试管理员',LOGIN_CLIENT_IP_HEADER:'x-test-client-ip'},stdio:['ignore','pipe','pipe']}); processHandle.stdout.on('data',chunk=>{logs+=chunk.toString()});processHandle.stderr.on('data',chunk=>{logs+=chunk.toString()}); for(let i=0;i<160;i++){if(processHandle.exitCode!==null)throw new Error('Test server exited: '+logs);try{const r=await fetch(origin+basePath+'/api/health');if(r.ok)return;}catch{}await new Promise(resolve=>setTimeout(resolve,150));} throw new Error('Test server did not become ready: '+logs); } async function stop(){if(processHandle&&processHandle.exitCode===null){processHandle.kill('SIGTERM');await new Promise(resolve=>processHandle.once('exit',resolve));}} async function call(path,{body,cookie,method,headers}={}){ const r=await fetch(origin+basePath+path,{method:method??(body?'POST':'GET'),redirect:'manual',headers:{'x-test-client-ip':'198.51.100.10',...(body?{'Content-Type':'application/json',Origin:origin}:{}),...(cookie?{Cookie:cookie}:{}),...headers},body:body?JSON.stringify(body):undefined}); const text=await r.text();let data;try{data=JSON.parse(text)}catch{data=text} return {status:r.status,data,headers:r.headers,cookie:r.headers.get('set-cookie')?.split(';')[0]}; } try{ await start(); verify((await call('/api/demands')).status===401,'anonymous demands denied'); verify((await call('/api/admin/users')).status===401,'anonymous account administration denied'); verify((await call('/api/documents/'+encodeURIComponent('开发SOP_公示版.md'))).status===401,'SOP requires authentication'); verify((await call('/api/demands',{headers:{'oai-authenticated-user-id':'spoof','oai-authenticated-user-email':'spoof@example.com'}})).status===401,'hosted identity header cannot authenticate'); verify((await call('/api/auth/login',{body:{username:'test_admin',password:initial},headers:{'x-test-client-ip':'','x-forwarded-for':'198.51.100.11'}})).status===403,'missing trusted client address cannot fall back to a spoofed forwarding header'); verify((await call('/api/auth/login',{body:{username:'test_admin',password:initial},headers:{'x-test-client-ip':'198.51.100.11, 198.51.100.12'}})).status===403,'trusted client address must be one valid IP'); let login=await call('/api/auth/login',{body:{username:'test_admin',password:initial}}); verify(login.status===200&&!!login.cookie,'bootstrap admin can log in'); verify(login.headers.get('set-cookie').includes(`Path=${basePath||'/'};`),'session cookie scoped to configured base path'); let admin=login.cookie; verify(login.data.user.mustChangePassword,'bootstrap password change required'); verify((await call('/api/admin/users',{cookie:admin})).status===403,'unchanged initial password cannot administer'); verify((await call('/api/auth/password',{cookie:admin,body:{currentPassword:initial,newPassword:adminPassword},headers:{Origin:'https://untrusted.example'}})).status===403,'cross-origin password change blocked'); const changed=await call('/api/auth/password',{cookie:admin,body:{currentPassword:initial,newPassword:adminPassword}}); verify(changed.status===200,'bootstrap password changed'); login=await call('/api/auth/login',{body:{username:'test_admin',password:adminPassword}});admin=login.cookie; verify(login.status===200&&!login.data.user.mustChangePassword,'password change retained'); verify((await call('/api/admin/users',{cookie:admin})).status===200,'admin list available'); const created=await call('/api/admin/users',{cookie:admin,body:{username:'business_one',displayName:'业务测试用户',password:memberInitial,role:'user'}}); verify(created.status===200||created.status===201,'admin creates an allowed account: '+JSON.stringify(created.data)); const accountList=await call('/api/admin/users',{cookie:admin}); const member=accountList.data.users.find(u=>u.username==='business_one'); verify(!!member,'created account listed'); const memberId=member.userId??member.id; verify(!JSON.stringify(accountList.data).includes('password_hash'),'password hashes not returned'); let memberLogin=await call('/api/auth/login',{body:{username:'business_one',password:memberInitial}}); verify(memberLogin.status===200&&memberLogin.data.user.mustChangePassword,'new account forced to change password'); verify((await call('/api/demands',{cookie:memberLogin.cookie})).status===403,'initial password cannot use business API'); verify((await call('/api/auth/password',{cookie:memberLogin.cookie,body:{currentPassword:memberInitial,newPassword:memberPassword}})).status===200,'member sets own password'); memberLogin=await call('/api/auth/login',{body:{username:'business_one',password:memberPassword}});let memberCookie=memberLogin.cookie; verify((await call('/api/admin/users',{cookie:memberCookie})).status===403,'regular user cannot administer accounts'); verify((await call('/api/documents/'+encodeURIComponent('附件01_需求登记模板.md'),{cookie:memberCookie})).status===200,'authorized user can download template'); verify((await call('/api/documents/'+encodeURIComponent('附件02_需求文档模板.md')+'?format=json')).status===401,'document preview requires authentication'); verify((await call('/api/documents/'+encodeURIComponent('附件02_需求文档模板.md')+'?format=docx')).status===401,'Word download requires authentication'); const preview=await call('/api/documents/'+encodeURIComponent('附件02_需求文档模板.md')+'?format=json',{cookie:memberCookie}); verify(preview.status===200&&preview.data.content.includes('背景与目标')&&preview.data.content.includes('开发责任人'),'authenticated preview provides the canonical template content'); for(const name of ['开发SOP_公示版.md','附件01_需求登记模板.md','附件02_需求文档模板.md','附件03_数据来源填写模板.md','附件04_验收记录模板.md','附件05_需求变更记录模板.md','附件06_缺陷记录模板.md','附件07_发布记录模板.md']){ const response=await fetch(origin+basePath+'/api/documents/'+encodeURIComponent(name)+'?format=docx',{headers:{Cookie:memberCookie}}); const bytes=new Uint8Array(await response.arrayBuffer()); verify(response.status===200&&response.headers.get('content-type').includes('wordprocessingml')&&response.headers.get('content-disposition').includes(encodeURIComponent(name.replace('.md','.docx')))&&bytes[0]===0x50&&bytes[1]===0x4b,'Word download is a genuine DOCX archive: '+name); } verify((await call('/api/documents/'+encodeURIComponent('附件02_需求文档模板.md')+'?format=invalid',{cookie:memberCookie})).status===400,'unsupported document format is rejected'); verify((await call('/api/documents/not-a-template?format=docx',{cookie:memberCookie})).status===404,'unknown document cannot read arbitrary files'); const fields={title:'仅本地自动测试的需求',project:'测试项目',module:'业务模块',type:'新增功能',proposer:'测试用户',department:'业务部门',source:'本地测试',owner:'测试用户',background:'业务背景',impact:'业务岗位',goal:'期望结果',expectedDate:'',noFixedDate:true,dateReason:'',scope:'',outOfScope:'',criteria:'',priority:'P2',priorityReason:'',dataSource:'',dataContact:'',noData:true,risk:'',pending:'',references:'',version:'v1.0'}; const demand=await call('/api/demands',{cookie:memberCookie,body:{action:'create',mode:'register',fields}}); verify(demand.status===200,'member registers a demand'); verify((await call('/api/demands',{cookie:admin})).data.demands.some(d=>d.id===demand.data.demand.id&&!d.access.business&&d.access.developer),'new formal demand defaults to administrator development'); verify((await call('/api/demands',{cookie:admin,body:{action:'cancel',id:demand.data.demand.id,revision:1,reason:'不应成功'}})).status===403,'default developer cannot cancel business demand'); const reviewFields={...fields,title:'本地测试:评审时确定方案',criteria:'业务人员按订单状态查询后,结果均符合所选状态。',priorityReason:'减少业务查询耗时',risk:'无',pending:'无'}; const reviewDemand=await call('/api/demands',{cookie:memberCookie,body:{action:'create',mode:'review',fields:reviewFields}}); verify(reviewDemand.status===200&&reviewDemand.data.demand.reviewReady,'business can submit for review before the developer proposes scope'); verify(reviewDemand.data.demand.fields.scope===''&&reviewDemand.data.demand.fields.outOfScope==='','review submission does not invent a solution or exclusions'); const reviewedUpdate=await call('/api/demands',{cookie:memberCookie,body:{action:'update',id:demand.data.demand.id,revision:1,mode:'review',fields:{...reviewFields,title:fields.title}}}); verify(reviewedUpdate.status===200&&reviewedUpdate.data.demand.reviewReady,'registered demand can be completed and submitted without a solution'); const missingCriteria=await call('/api/demands',{cookie:memberCookie,body:{action:'create',mode:'review',fields:{...reviewFields,title:'本地测试:缺少业务验收标准',criteria:''}}}); verify(missingCriteria.status===400&&missingCriteria.data.error.includes('验收标准'),'review still requires business acceptance criteria'); const legacyFields={...reviewFields,scope:'原有功能说明',outOfScope:'原有范围外事项'}; // Simulate a record created before review ownership was introduced, using only this disposable database. const legacyDatabase=new DatabaseSync(join(directory,'demand-center.sqlite')); legacyDatabase.prepare('UPDATE demands SET payload = ? WHERE id = ?').run(JSON.stringify({...reviewDemand.data.demand,review:undefined,fields:legacyFields}),reviewDemand.data.demand.id); legacyDatabase.close(); const legacyVisible=(await call('/api/demands',{cookie:admin})).data.demands.find(d=>d.id===reviewDemand.data.demand.id); verify(legacyVisible.access.developer&&legacyVisible.review.developer.username==='test_admin'&&legacyVisible.revision===1,'unassigned legacy demand automatically resolves administrator without changing revision'); const legacyDemand=await call('/api/demands',{cookie:memberCookie,body:{action:'update',id:reviewDemand.data.demand.id,revision:1,mode:'review',fields:legacyFields}}); verify(legacyDemand.status===200,'existing solution fields remain compatible'); const preserved=await call('/api/demands',{cookie:memberCookie,body:{action:'update',id:legacyDemand.data.demand.id,revision:2,mode:'review',fields:{...legacyDemand.data.demand.fields,background:'更新业务背景'}}}); verify(preserved.status===200&&preserved.data.demand.fields.scope===legacyFields.scope&&preserved.data.demand.fields.outOfScope===legacyFields.outOfScope,'business edits preserve existing solution content'); async function createDeveloper(username){ const password=secret(),nextPassword=secret(); const response=await call('/api/admin/users',{cookie:admin,body:{username,displayName:username,password,role:'user'}}); verify(response.status===201||response.status===200,'provision developer account'); let session=await call('/api/auth/login',{body:{username,password}}); verify((await call('/api/auth/password',{cookie:session.cookie,body:{currentPassword:password,newPassword:nextPassword}})).status===200,'developer changes initial password'); session=await call('/api/auth/login',{body:{username,password:nextPassword}}); return session; } const developer=await createDeveloper('developer_one'); const replacement=await createDeveloper('developer_two'); let reviewRecord=preserved.data.demand; async function reviewCall(cookie,action,extra={}){ const response=await call('/api/demands',{cookie,body:{action,id:reviewRecord.id,revision:reviewRecord.revision,...extra}}); if(response.status===200)reviewRecord=response.data.demand; return response; } verify((await call('/api/demands',{cookie:developer.cookie})).data.demands.length===0,'unassigned developer sees no other users demands'); verify((await reviewCall(memberCookie,'assign-developer',{username:'business_one'})).status===400,'business owner cannot assign self as developer'); verify((await reviewCall(memberCookie,'assign-developer',{username:'missing-developer'})).status===400,'unknown developer account rejected'); verify((await reviewCall(memberCookie,'confirm-solution',{proposalVersion:1,confirm:true})).status===409,'legacy content cannot be confirmed before developer submits a proposal'); verify((await reviewCall(memberCookie,'assign-developer',{username:'developer_one'})).status===200,'business owner assigns developer'); const visible=await call('/api/demands',{cookie:developer.cookie}); verify(visible.data.demands.length===1&&visible.data.demands[0].id===reviewRecord.id&&visible.data.demands[0].access.developer&&!visible.data.demands[0].access.business,'assigned developer sees exactly the shared demand with developer permissions'); verify((await call('/api/demands',{cookie:admin})).data.demands.some(d=>d.id===reviewRecord.id&&!d.access.business&&!d.access.developer),'administrator can observe an assigned demand without business or developer permissions'); const beforeAdminWrites=JSON.stringify(reviewRecord); for(const action of ['update','cancel','change','accept','assign-developer','propose-solution','confirm-solution','return-solution']){ const denied=await reviewCall(admin,action,{mode:'review',fields:reviewRecord.fields,reason:'不应修改',content:'不应变更',username:'developer_two',scope:'不应代提',outOfScope:'无',proposalVersion:1,confirm:true,comment:'不应代确认',results:['通过'],notes:'无'}); verify(denied.status===404,'administrator read access does not permit '+action); } const afterAdminWrites=(await call('/api/demands',{cookie:memberCookie})).data.demands.find(d=>d.id===reviewRecord.id); verify(JSON.stringify(afterAdminWrites)===beforeAdminWrites,'administrator write attempts leave the persisted demand unchanged'); verify((await reviewCall(developer.cookie,'cancel',{reason:'must fail'})).status===403,'developer cannot cancel business demand'); verify((await reviewCall(developer.cookie,'update',{mode:'review',fields:reviewRecord.fields})).status===403,'developer cannot edit business fields'); verify((await reviewCall(developer.cookie,'assign-developer',{username:'developer_two'})).status===403,'developer cannot delegate access'); verify((await reviewCall(memberCookie,'propose-solution',{scope:'业务方不能代填',outOfScope:'无'})).status===403,'business owner cannot impersonate developer proposal'); verify((await reviewCall(memberCookie,'update',{mode:'review',fields:{...reviewRecord.fields,scope:'绕过界面修改方案'}})).status===403,'business update cannot mutate developer solution fields'); verify((await reviewCall(developer.cookie,'propose-solution',{scope:' ',outOfScope:'无'})).status===400,'blank proposal rejected'); const revisionBeforeProposal=reviewRecord.revision; verify((await reviewCall(developer.cookie,'propose-solution',{scope:'F-01:按状态筛选订单',outOfScope:'不修改历史订单',developer:{userId:memberId}})).status===200,'developer submits proposal'); verify(reviewRecord.review.proposals[0].version===1&&reviewRecord.review.proposals[0].developer.userId===developer.data.user.userId&&reviewRecord.fields.scope==='F-01:按状态筛选订单','proposal version and actor are assigned by server'); verify((await reviewCall(developer.cookie,'confirm-solution',{proposalVersion:1,confirm:true})).status===403,'developer cannot confirm own proposal for business'); verify((await reviewCall(developer.cookie,'propose-solution',{scope:'静默覆盖',outOfScope:'无'})).status===409,'pending proposal cannot be silently overwritten'); verify((await reviewCall(memberCookie,'confirm-solution',{proposalVersion:0,confirm:true})).status===409,'wrong proposal version rejected'); verify((await reviewCall(memberCookie,'confirm-solution',{proposalVersion:1,confirm:true,revision:revisionBeforeProposal})).status===409,'stale record revision rejected'); verify((await reviewCall(memberCookie,'confirm-solution',{proposalVersion:1,confirm:false})).status===400,'explicit business confirmation required'); verify((await reviewCall(memberCookie,'return-solution',{proposalVersion:1,comment:''})).status===400,'return requires actionable feedback'); verify((await reviewCall(memberCookie,'return-solution',{proposalVersion:1,comment:'补充异常场景'})).status===200,'business requests revision'); verify((await reviewCall(developer.cookie,'propose-solution',{scope:'F-01:按状态筛选订单;空数据展示暂无订单',outOfScope:'不修改历史订单'})).status===200,'developer submits revised proposal'); verify(reviewRecord.review.proposals.length===2&&reviewRecord.review.proposals[0].decision.result==='changes_requested','previous proposal and feedback are retained'); verify((await reviewCall(memberCookie,'confirm-solution',{proposalVersion:2,confirm:true,comment:'业务已核对'})).status===200,'business confirms revised solution'); const confirmed=structuredClone(reviewRecord.review.proposals[1]); verify(confirmed.decision.actor.userId===memberId&&!!confirmed.decision.time&&confirmed.decision.result==='confirmed','confirmation stores actual business actor and time'); verify((await reviewCall(memberCookie,'confirm-solution',{proposalVersion:2,confirm:true})).status===409,'same version cannot be confirmed twice'); verify((await reviewCall(memberCookie,'update',{mode:'review',fields:{...reviewRecord.fields,goal:'新增业务目标'}})).status===200,'business can amend requirements'); verify(!!reviewRecord.review.proposals[1].invalidated&&reviewRecord.review.proposals[1].decision.time===confirmed.decision.time&&reviewRecord.fields.scope===confirmed.scope,'business edit invalidates approval while preserving the proposal and its confirmation'); verify((await reviewCall(memberCookie,'confirm-solution',{proposalVersion:2,confirm:true})).status===409,'invalidated solution cannot be reconfirmed without developer review'); verify((await reviewCall(developer.cookie,'propose-solution',{scope:'F-01:根据新目标调整筛选结果',outOfScope:'不修改历史订单'})).status===200,'developer proposes against amended business requirements'); verify(reviewRecord.review.proposals[2].businessFields.goal==='新增业务目标','proposal retains business requirement snapshot'); verify((await reviewCall(memberCookie,'confirm-solution',{proposalVersion:3,confirm:true})).status===200,'new business version confirmed'); verify((await reviewCall(memberCookie,'return-solution',{proposalVersion:3,comment:'再补充筛选条件'})).status===200,'business may request changes to an approved version'); verify(!!reviewRecord.review.proposals[2].invalidated&&reviewRecord.review.proposals[2].decision.result==='confirmed','reopened approval keeps original confirmation record'); verify((await reviewCall(memberCookie,'assign-developer',{username:'developer_two'})).status===200,'business reassigns development'); verify((await call('/api/demands',{cookie:developer.cookie})).data.demands.length===0,'reassignment revokes previous developer visibility'); verify((await reviewCall(developer.cookie,'propose-solution',{scope:'旧责任人写入',outOfScope:'无'})).status===404,'previous developer can no longer write'); verify((await reviewCall(replacement.cookie,'propose-solution',{scope:'F-01:新责任人提出完整方案',outOfScope:'无'})).status===200,'replacement developer can submit next version'); verify(reviewRecord.review.proposals.at(-1).version===4&&reviewRecord.review.proposals.at(-1).developer.userId===replacement.data.user.userId,'versions remain monotonic across reassignment'); verify((await reviewCall(memberCookie,'confirm-solution',{proposalVersion:4,confirm:true})).status===200,'business confirms replacement proposal'); await stop();await start(); const afterRestart=(await call('/api/demands',{cookie:replacement.cookie})).data.demands.find(d=>d.id===reviewRecord.id); verify(afterRestart.review.proposals.length===4&&afterRestart.review.proposals.at(-1).decision.result==='confirmed','assignment, proposal history and confirmations survive restart'); verify((await call('/api/demands',{cookie:memberCookie})).data.demands.some(d=>d.id===demand.data.demand.id),'records and sessions survive server restart'); async function upload(cookie,name,content,overrideOrigin=origin){ const form=new FormData();form.append('file',new Blob([content]),name); const response=await fetch(origin+basePath+'/api/attachments',{method:'POST',headers:{Origin:overrideOrigin,...(cookie?{Cookie:cookie}:{})},body:form}); return {status:response.status,data:await response.json()}; } const attachmentContent='需求说明:\nUnicode 文档'; verify((await upload(undefined,'需求说明.html',attachmentContent)).status===401,'anonymous upload rejected'); verify((await upload(memberCookie,'需求说明.html',attachmentContent,'https://untrusted.example')).status===403,'cross-origin upload rejected'); verify((await upload(memberCookie,'空文件.txt','')).status===400,'empty upload rejected'); verify((await upload(memberCookie,'超限.bin',new Uint8Array(20*1024*1024+1))).status===413,'oversized upload rejected by server'); const uploaded=await upload(memberCookie,'需求说明.html',attachmentContent); verify(uploaded.status===201&&uploaded.data.attachment.name==='需求说明.html','authenticated upload returns filename and metadata'); const file=uploaded.data.attachment; const downloadPath='/api/attachments/'+file.id; verify((await call('/api/attachments',{cookie:memberCookie})).data.attachments.some(a=>a.id===file.id),'unsaved attachments can be recovered after reload'); verify((await call(downloadPath)).status===401,'anonymous download rejected'); verify((await call(downloadPath,{cookie:admin})).status===404,'administrator cannot download another users staged file'); verify((await call('/api/attachments',{cookie:admin})).data.attachments.every(a=>a.id!==file.id),'administrator cannot list another users staged files'); verify((await call(downloadPath,{cookie:admin,method:'DELETE',headers:{Origin:origin}})).status===409,'administrator cannot delete another users staged file'); verify((await call(downloadPath,{cookie:replacement.cookie})).status===404,'developer cannot access file before it is attached to shared demand'); const ownDownload=await call(downloadPath,{cookie:memberCookie}); verify(ownDownload.status===200&&ownDownload.data===attachmentContent,'uploaded bytes round-trip unchanged'); verify(ownDownload.headers.get('content-disposition').startsWith('attachment;')&&ownDownload.headers.get('content-disposition').includes(encodeURIComponent(file.name))&&ownDownload.headers.get('content-type')==='application/octet-stream'&&ownDownload.headers.get('content-security-policy').includes('sandbox'),'active content is downloaded with a safe Unicode filename and sandbox headers'); verify((await reviewCall(memberCookie,'update',{mode:'review',fields:reviewRecord.fields,attachmentIds:[file.id]})).status===200,'attachment binds atomically when saving demand'); verify(reviewRecord.attachments[0].id===file.id&&reviewRecord.review.proposals.at(-1).invalidated.reason.includes('附件'),'new reference material invalidates previous review approval'); verify((await call('/api/attachments',{cookie:memberCookie})).data.attachments.every(a=>a.id!==file.id),'saved attachment is no longer listed as staged'); verify((await call(downloadPath,{cookie:replacement.cookie})).status===200,'assigned developer can download demand attachment'); const adminDownload=await call(downloadPath,{cookie:admin}); verify(adminDownload.status===200&&adminDownload.data===attachmentContent,'administrator can download exact bytes of formal demand attachments'); verify((await call(downloadPath,{cookie:admin,method:'DELETE',headers:{Origin:origin}})).status===409,'administrator read access does not permit deleting bound attachments'); verify((await call(downloadPath,{cookie:developer.cookie})).status===404,'former developer cannot download shared attachment'); verify((await call(downloadPath,{cookie:memberCookie,method:'DELETE',headers:{Origin:origin}})).status===409,'bound files cannot be deleted via staging cleanup'); const foreign=await upload(replacement.cookie,'other.txt','other account file'); verify((await reviewCall(memberCookie,'update',{mode:'review',fields:reviewRecord.fields,attachmentIds:[foreign.data.attachment.id]})).status===400,'cannot claim another users uploaded file'); const unchanged=(await call('/api/demands',{cookie:memberCookie})).data.demands.find(d=>d.id===reviewRecord.id); verify(unchanged.revision===reviewRecord.revision&&unchanged.attachments[0].id===file.id,'failed attachment save leaves demand and existing files unchanged'); verify((await reviewCall(replacement.cookie,'propose-solution',{scope:'方案包含新参考文件',outOfScope:'无'})).status===200,'developer reviews new attachment'); const attachmentVersion=reviewRecord.review.proposals.at(-1).version; verify(reviewRecord.review.proposals.at(-1).businessAttachments[0].id===file.id,'review snapshot includes the exact attachments considered'); verify((await reviewCall(memberCookie,'confirm-solution',{proposalVersion:attachmentVersion,confirm:true})).status===200,'business confirms solution with reference attachment'); verify((await reviewCall(memberCookie,'update',{mode:'review',fields:reviewRecord.fields,attachmentIds:[]})).status===200,'business removes current attachment'); verify(reviewRecord.attachments.length===0&&reviewRecord.review.proposals.at(-1).businessAttachments[0].id===file.id,'removed attachment is retained in historical review'); verify((await call(downloadPath,{cookie:replacement.cookie})).data===attachmentContent,'historical review attachment remains downloadable by current participants'); verify((await call(downloadPath,{cookie:admin})).data===attachmentContent,'administrator can download retained historical review attachments'); const temporary=await upload(memberCookie,'临时附件.txt','temporary file'); verify((await call('/api/attachments/'+temporary.data.attachment.id,{cookie:memberCookie,method:'DELETE',headers:{Origin:origin}})).status===200,'discarding staged attachment cleans up stored bytes'); verify((await call('/api/attachments/'+temporary.data.attachment.id,{cookie:memberCookie})).status===404,'discarded staged attachment is unavailable'); const draftUpload=await upload(memberCookie,'草稿附件.txt','draft persistence'); const draftWithFile=await call('/api/demands',{cookie:memberCookie,body:{action:'create',mode:'draft',fields:{...fields,title:'含附件草稿'},attachmentIds:[draftUpload.data.attachment.id]}}); verify(draftWithFile.status===200&&draftWithFile.data.demand.attachments.length===1,'new draft saves attached file'); const draftRecord=draftWithFile.data.demand; verify((await call('/api/demands',{cookie:admin})).data.demands.every(d=>d.id!==draftRecord.id),'administrator cannot read another users draft'); verify((await call('/api/attachments/'+draftUpload.data.attachment.id,{cookie:admin})).status===404,'administrator cannot download another users draft attachment'); const legacyClient=await call('/api/demands',{cookie:memberCookie,body:{action:'update',mode:'draft',id:draftRecord.id,revision:draftRecord.revision,fields:{...draftRecord.fields,title:'旧客户端保留附件'}}}); verify(legacyClient.status===200&&legacyClient.data.demand.attachments[0].id===draftUpload.data.attachment.id,'old clients omitting attachmentIds do not drop attachments'); const removedFile=await call('/api/demands',{cookie:memberCookie,body:{action:'update',mode:'draft',id:draftRecord.id,revision:legacyClient.data.demand.revision,fields:legacyClient.data.demand.fields,attachmentIds:[]}}); verify(removedFile.status===200&&(await call('/api/attachments/'+draftUpload.data.attachment.id,{cookie:memberCookie})).status===404,'unreferenced removed files are deleted'); const privateUpload=await upload(memberCookie,'发布后可见.txt','draft becomes formal'); const privateDraft=await call('/api/demands',{cookie:memberCookie,body:{action:'create',mode:'draft',fields:{...reviewFields,title:'管理员查看范围回归'},attachmentIds:[privateUpload.data.attachment.id]}}); verify(privateDraft.status===200,'create a private draft for visibility transition'); const adminDraft=await call('/api/demands',{cookie:admin,body:{action:'create',mode:'draft',fields:{...fields,title:'管理员自己的草稿'}}}); verify(adminDraft.status===200&&adminDraft.data.demand.access.business,'administrator keeps business permissions on own drafts'); const adminList=(await call('/api/demands',{cookie:admin})).data.demands; verify(adminList.some(d=>d.id===adminDraft.data.demand.id)&&adminList.every(d=>d.id!==privateDraft.data.demand.id),'administrator sees own draft but not another users draft'); const published=await call('/api/demands',{cookie:memberCookie,body:{action:'update',mode:'review',id:privateDraft.data.demand.id,revision:privateDraft.data.demand.revision,fields:privateDraft.data.demand.fields}}); verify(published.status===200&&(await call('/api/demands',{cookie:admin})).data.demands.some(d=>d.id===published.data.demand.id),'publishing a draft makes it visible to administrators'); verify((await call('/api/attachments/'+privateUpload.data.attachment.id,{cookie:admin})).data==='draft becomes formal','publishing also enables administrator attachment download'); verify((await call('/api/demands?role=admin',{cookie:developer.cookie})).data.demands.every(d=>d.id!==published.data.demand.id),'regular users cannot request administrator visibility'); verify(published.data.demand.review.developer.username==='test_admin','publishing a draft automatically assigns the administrator'); const adminParticipant=(await call('/api/demands',{cookie:admin})).data.demands.find(d=>d.id===published.data.demand.id); verify(adminParticipant.access.developer&&!adminParticipant.access.business,'default assignment grants only developer participation'); const adminProposal=await call('/api/demands',{cookie:admin,body:{action:'propose-solution',id:adminParticipant.id,revision:adminParticipant.revision,scope:'F-01:明确指派后提交',outOfScope:'无'}}); verify(adminProposal.status===200,'default administrator may submit developer proposal'); verify((await call('/api/demands',{cookie:admin,body:{action:'confirm-solution',id:adminParticipant.id,revision:adminProposal.data.demand.revision,proposalVersion:1,confirm:true}})).status===403,'assigned administrator still cannot replace business confirmation'); const adminReassigned=await call('/api/demands',{cookie:memberCookie,body:{action:'assign-developer',id:adminParticipant.id,revision:adminProposal.data.demand.revision,username:'developer_two'}}); verify(adminReassigned.status===200,'business owner can reassign an administrator developer'); const observerAgain=(await call('/api/demands',{cookie:admin})).data.demands.find(d=>d.id===adminParticipant.id); verify(observerAgain&&!observerAgain.access.developer&&!observerAgain.access.business,'former developer retains only administrator reading access'); verify((await call('/api/demands',{cookie:admin,body:{action:'propose-solution',id:adminParticipant.id,revision:observerAgain.revision,scope:'不应成功',outOfScope:'无'}})).status===404,'reassigned administrator loses proposal permission'); const cancelObserved=await call('/api/demands',{cookie:memberCookie,body:{action:'cancel',id:adminParticipant.id,revision:observerAgain.revision,reason:'结束测试需求'}}); verify(cancelObserved.status===200&&(await call('/api/demands',{cookie:admin})).data.demands.some(d=>d.id===adminParticipant.id&&d.status==='已取消'),'cancelled formal demands stay visible to administrators'); const roleDatabase=new DatabaseSync(join(directory,'demand-center.sqlite')); roleDatabase.prepare('UPDATE accounts SET role = ? WHERE id = ?').run('user',login.data.user.userId); try{ verify((await call('/api/demands',{cookie:admin})).data.demands.every(d=>d.id!==reviewRecord.id),'administrator visibility is revoked on the next request after role removal'); verify((await call(downloadPath,{cookie:admin})).status===404,'attachment downloads also recheck the current account role'); }finally{roleDatabase.prepare('UPDATE accounts SET role = ? WHERE id = ?').run('admin',login.data.user.userId);roleDatabase.close();} const backupPath=join(directory,'attachment-backup.sqlite'); await promisify(execFile)(process.execPath,['scripts/backup.mjs',backupPath],{env:{...process.env,DATA_DIR:directory}}); const backupDatabase=new DatabaseSync(backupPath,{readOnly:true}); const backedUp=backupDatabase.prepare('SELECT content FROM attachments WHERE id = ?').get(file.id); verify(Buffer.from(backedUp.content).toString()===attachmentContent,'online database backup includes exact file contents'); backupDatabase.close(); await stop();await start(); verify((await call(downloadPath,{cookie:replacement.cookie})).data===attachmentContent,'attachment download survives production server restart'); const disabled=await call('/api/admin/users',{method:'PATCH',cookie:admin,body:{id:memberId,action:'disable'}}); verify(disabled.status===200,'admin disables user'); verify((await call('/api/demands',{cookie:memberCookie})).status===401,'disabled account session immediately invalid'); verify((await call('/api/auth/login',{body:{username:'business_one',password:memberPassword}})).status===401,'disabled account cannot log in'); verify((await call('/api/admin/users',{method:'PATCH',cookie:admin,body:{id:memberId,action:'enable'}})).status===200,'admin re-enables user'); memberLogin=await call('/api/auth/login',{body:{username:'business_one',password:memberPassword}});memberCookie=memberLogin.cookie; for(let attempt=0;attempt<5;attempt++){ verify((await call('/api/auth/login',{body:{username:'business_one',password:'Incorrect password for regression'}})).status===401,'incorrect password consumes account attempt'); } verify((await call('/api/auth/login',{body:{username:'business_one',password:memberPassword}})).status===429,'account is locked before administrator recovery'); const resetPassword=secret(); verify((await call('/api/admin/users',{method:'PATCH',cookie:admin,body:{id:memberId,action:'reset-password',password:resetPassword}})).status===200,'administrator resets password'); verify((await call('/api/demands',{cookie:memberCookie})).status===401,'password reset revokes old session'); const recovered=await call('/api/auth/login',{body:{username:'business_one',password:resetPassword}}); verify(recovered.status===200&&recovered.data.user.mustChangePassword,'reset password clears old account lock immediately and forces change'); const adminId=login.data.user.userId; verify((await call('/api/admin/users',{method:'PATCH',cookie:admin,body:{id:adminId,action:'disable'}})).status>=400,'administrator cannot disable self'); verify((await call('/api/auth/logout',{method:'POST',cookie:admin,headers:{Origin:origin}})).status===200,'logout succeeds'); verify((await call('/api/admin/users',{cookie:admin})).status===401,'logout revokes session'); const retry=await call('/api/auth/login',{body:{username:'test_admin',password:initial}});verify(retry.status===401,'initial bootstrap password cannot overwrite changed password on restart'); for(let attempt=0;attempt<60;attempt++){ assert.equal((await call('/api/auth/login',{body:{username:`unknown-source-test-${attempt}`,password:'Incorrect source test password'},headers:{'x-test-client-ip':'198.51.100.77'}})).status,401); } verify((await call('/api/auth/login',{body:{username:'unknown-source-test-over-limit',password:'Incorrect source test password'},headers:{'x-test-client-ip':'198.51.100.77','x-forwarded-for':'198.51.100.78'}})).status===429,'source limit applies across usernames and ignores unrelated spoofed headers'); verify((await call('/api/auth/login',{body:{username:'test_admin',password:adminPassword}})).status===200,'one exhausted source does not prevent another source from logging in'); console.log(`${checks} self-hosted authentication, authorization and persistence checks passed.`); }catch(error){console.error(error);process.exitCode=1;}finally{await stop();await rm(directory,{recursive:true,force:true});}