refactor: organize source web and tests by business module

This commit is contained in:
abaishu0730 committed 2026-10-19 08:45:51 +08:00
1 parent 9854d2d5c2
commit 2aed328774
113 files changed
+189 -183

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
const {test}=require('node:test'),assert=require('node:assert/strict');
const {StorageService}=require('../../src/modules/storage/service.cjs');
test('a stalled connection check times out and releases pending state',async()=>{
const service=new StorageService({store:{prepareServer:()=>({saved:{host:'server',share:'orders'}})},client:{area:async()=>({list:()=>new Promise(()=>{})})},checkTimeoutMs:40});
await assert.rejects(service.checkConnection({}),e=>e.status===504);assert.equal(service.pendingChecks.size,0);await service.stop();
});
test('cancelled connection checks settle without saving',async()=>{
const controller=new AbortController(),service=new StorageService({store:{prepareServer:()=>({saved:{host:'server',share:'orders'}})},client:{area:async()=>({list:()=>new Promise(()=>{})})},checkTimeoutMs:100});
const promise=service.checkConnection({},{signal:controller.signal});controller.abort();await assert.rejects(promise,e=>e.status===499);assert.equal(service.pendingChecks.size,0);await service.stop();
});
test('shutdown aborts a pending read instead of waiting for the network',async()=>{
const service=new StorageService({store:{prepareServer:()=>({saved:{host:'server',share:'orders'}})},client:{area:async()=>({list:()=>new Promise(()=>{})})},checkTimeoutMs:10000});
const checked=assert.rejects(service.checkConnection({}),e=>e.status===503);await service.stop();await checked;assert.equal(service.pendingChecks.size,0);
});
test('failed Windows tree termination falls back and waits for worker closure',{skip:process.platform!=='win32'},async t=>{
const {EventEmitter}=require('node:events'),{PassThrough}=require('node:stream'),cp=require('node:child_process');let kills=0,closed=false;
const child=new EventEmitter();child.pid=123;child.stdin=new PassThrough();child.stdout=new PassThrough();child.stderr=new PassThrough();child.kill=()=>{kills++;queueMicrotask(()=>{closed=true;child.emit('close',1);});};
t.mock.method(cp,'spawn',(file)=>{if(file===process.execPath)return child;const killer=new EventEmitter();queueMicrotask(()=>killer.emit('exit',1));return killer;});
const key=require.resolve('../../src/modules/storage/smb-probe.cjs');delete require.cache[key];t.after(()=>delete require.cache[key]);const {probe}=require(key);
await assert.rejects(probe({host:'server'},{timeoutMs:5}),e=>e.status===504);assert.equal(kills,1);assert.equal(closed,true);
});
test('share enumeration reserves enough bounded output for hundreds of Unicode names',async t=>{
const cp=require('node:child_process'),names=Array.from({length:501},(_,i)=>'共享目录'.repeat(10)+i),payload=JSON.stringify({ok:true,shares:names});
t.mock.method(cp,'execFile',(file,args,options,callback)=>{assert.ok(options.maxBuffer>=Buffer.byteLength(payload));return {stdin:{on(){},end(){callback(null,payload);}}};});
const key=require.resolve('../../src/modules/storage/smb-native.cjs');delete require.cache[key];t.after(()=>delete require.cache[key]);const {listShares}=require(key);assert.deepEqual(await listShares({host:'server',authMode:'windows'}),names);
});
+60
View File
@@ -0,0 +1,60 @@
'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 {StorageStore}=require('../../src/modules/storage/store.cjs');const {StorageService}=require('../../src/modules/storage/service.cjs');const {FileArea}=require('../../src/modules/storage/files.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs');
const config={name:'210',host:'storage.company.test',share:'orders',directory:'',username:'archive',password:'Private-storage-password',enabled:true};
async function fixture(t){const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-storage-http-'));const outputDir=path.join(dir,'pdf'),remote=path.join(dir,'remote');await fs.mkdir(outputDir);await fs.mkdir(remote);const 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 storageStore=new StorageStore(path.join(dir,'storage'));const storage=new StorageService({store:storageStore,jobs:store,outputDir,client:{area:async()=>new FileArea(remote),browse:async server=>server.share?{...await new FileArea(remote).list(''),serverRoot:false,readable:true,address:'shared'}:{serverRoot:true,readable:false,address:String.fromCharCode(92).repeat(2)+server.host,entries:[{name:'orders',type:'directory',address:String.fromCharCode(92).repeat(2)+server.host+String.fromCharCode(92)+'orders'}]}}});const server=createDashboard({store,storage,outputDir});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(async()=>{await storage.stop();server.closeAllConnections();await new Promise(r=>server.close(r));storageStore.close();await fs.rm(dir,{recursive:true,force:true});});const base='http://127.0.0.1:'+server.address().port;const 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)});const login=async username=>(await call('/api/login',{username,password:'Test-password-123'})).headers.get('set-cookie').split(';')[0];return {dir,outputDir,remote,store,storage,storageStore,call,login};}
test('storage HTTP enforces roles, redacts passwords and archives only successful in-root PDFs',async t=>{
const {dir,outputDir,store,storageStore,call,login}=await fixture(t);assert.equal((await call('/api/storage')).status,401);
const admin=await login('admin'),operator=await login('operator'),viewer=await login('viewer');
assert.equal((await call('/api/storage/servers',config,operator)).status,403);assert.equal((await call('/api/storage/servers',config,admin,'https://evil.test')).status,403);
const quick=await call('/api/storage/servers',{address:String.raw`\\storage.company.test\orders`,authMode:'windows',enabled:true},admin);assert.equal(quick.status,201);const quickServer=await quick.json();assert.equal(quickServer.authMode,'windows');assert.equal(quickServer.hasPassword,false);assert.equal(quickServer.username,'');assert.equal((await call(`/api/storage/servers/${quickServer.id}/check`,{},admin)).status,200);
const invalid=await call('/api/storage/servers',{address:String.raw`\\storage.company.test\orders\..\outside`,authMode:'windows',enabled:true},admin);assert.equal(invalid.status,400);
const saved=await call('/api/storage/servers',config,admin);assert.equal(saved.status,201);const server=await saved.json();assert.equal(server.password,undefined);
assert.doesNotMatch(JSON.stringify(await(await call('/api/storage',undefined,viewer)).json()),/Private-storage/);
assert.equal((await call(`/api/storage/servers/${server.id}/files`,undefined,viewer)).status,403);
assert.equal((await call(`/api/storage/servers/${server.id}/check`,{},admin)).status,200);
const overview=await(await call('/api/overview',undefined,admin)).json();assert.equal(overview.connections.find(c=>c.name==='存储服务器').ready,true);
await fs.writeFile(path.join(outputDir,'order.pdf'),'%PDF-1.7\nHTTP document');store.recordJob({jobId:'job-1',status:'success',path:path.join(outputDir,'order.pdf'),filename:'order.pdf',metadata:{order:'001234'}});
assert.equal((await call(`/api/storage/servers/${server.id}/archive`,{jobId:'job-1',directory:'产业A'},viewer)).status,403);
const archived=await call(`/api/storage/servers/${server.id}/archive`,{jobId:'job-1',directory:'产业A'},operator);assert.equal(archived.status,200);assert.equal((await archived.json()).status,'success');
assert.equal(storageStore.archives().length,1);
const downloaded=await call(`/api/storage/servers/${server.id}/file?path=${encodeURIComponent('产业A/001234/order.pdf')}`,undefined,operator);assert.equal(downloaded.status,200);assert.equal(await downloaded.text(),'%PDF-1.7\nHTTP document');
store.recordJob({jobId:'outside',status:'success',path:path.join(dir,'outside.pdf'),filename:'outside.pdf'});await fs.writeFile(path.join(dir,'outside.pdf'),'%PDF-1.7\noutside');
assert.equal((await call(`/api/storage/servers/${server.id}/archive`,{jobId:'outside',directory:''},admin)).status,400);
});
test('automatic storage is opt-in, starts with new jobs and never queues mail',async t=>{
const {outputDir,remote,store,storage,storageStore}=await fixture(t);const server=await storage.saveServer(config);await fs.writeFile(path.join(outputDir,'new.pdf'),'%PDF-1.7\nnew');
const old=store.recordJob({jobId:'old-job',status:'success',path:path.join(outputDir,'new.pdf'),filename:'new.pdf',createdAt:'2000-01-01T00:00:00Z'});
await storage.automatic(old);assert.deepEqual(await fs.readdir(remote),[]);
await assert.rejects(Promise.resolve().then(()=>storage.saveSettings({serverId:server.id,enabled:true})),e=>e.status===409);
await storage.check(server.id);storage.saveSettings({serverId:server.id,enabled:true});await storage.automatic(old);assert.deepEqual(await fs.readdir(remote),[]);
const job=store.recordJob({jobId:'new-job',status:'success',path:path.join(outputDir,'new.pdf'),filename:'new.pdf',metadata:{order:'7654321'},createdAt:new Date(Date.now()+1).toISOString()});await storage.automatic(job);
assert.deepEqual(await fs.readdir(remote),['7654321']);assert.deepEqual(await fs.readdir(path.join(remote,'7654321')),['new.pdf']);assert.equal(storageStore.archives()[0].status,'success');
});
test('draft connection check does not save, and unreadable storage cannot be added',async t=>{
const {remote,storageStore,call,login}=await fixture(t),admin=await login('admin'),operator=await login('operator');
const draft={address:String.fromCharCode(92).repeat(2)+'storage.company.test'+String.fromCharCode(92)+'orders',authMode:'windows',enabled:true};
assert.equal((await call('/api/storage/servers/check',draft,operator)).status,403);
assert.equal((await call('/api/storage/servers/check',draft,admin,'https://evil.test')).status,403);
const checked=await call('/api/storage/servers/check',draft,admin);assert.equal(checked.status,200);assert.equal((await checked.json()).readable,true);assert.equal(storageStore.servers().length,0);assert.deepEqual(await fs.readdir(remote),[]);
await fs.rmdir(remote);
assert.equal((await call('/api/storage/servers/check',draft,admin)).status,502);
assert.equal((await call('/api/storage/servers',draft,admin)).status,502);assert.equal(storageStore.servers().length,0);
await fs.mkdir(remote);const saved=await call('/api/storage/servers',draft,admin);assert.equal(saved.status,201);const server=await saved.json();assert.equal(server.state.readable,true);assert.equal(server.state.writable,false);
assert.deepEqual(await fs.readdir(remote),[]);
const unavailable={...server,address:String.fromCharCode(92).repeat(2)+'storage.company.test'+String.fromCharCode(92)+'orders'+String.fromCharCode(92)+'new',name:'changed',password:''};await fs.rmdir(remote);
assert.equal((await call('/api/storage/servers',unavailable,admin)).status,502);assert.equal(storageStore.servers()[0].version,server.version);assert.equal(storageStore.servers()[0].name,server.name);
const disabled=await call('/api/storage/servers',{...server,password:'',enabled:false},admin);assert.equal(disabled.status,200);const reenable=await call('/api/storage/servers',{...await disabled.json(),password:'',enabled:true},admin);assert.equal(reenable.status,502);assert.equal(storageStore.servers()[0].enabled,false);
});
test('server-only input lists shares without allowing server-root saves',async t=>{
const {call,login,storageStore}=await fixture(t),admin=await login('admin'),operator=await login('operator'),input={address:'storage.company.test',authMode:'windows',enabled:true};
assert.equal((await call('/api/storage/servers/browse',input,operator)).status,403);assert.equal((await call('/api/storage/servers/browse',input,admin,'https://evil.test')).status,403);
const browse=await call('/api/storage/servers/browse',input,admin);assert.equal(browse.status,200);const result=await browse.json();assert.equal(result.serverRoot,true);assert.equal(result.entries[0].name,'orders');assert.equal(result.password,undefined);
const check=await call('/api/storage/servers/check',input,admin);assert.equal(check.status,200);assert.equal((await check.json()).readable,false);assert.equal((await call('/api/storage/servers',input,admin)).status,400);assert.equal(storageStore.servers().length,0);
const selected={...input,address:result.entries[0].address};const saved=await call('/api/storage/servers',selected,admin);assert.equal(saved.status,201);assert.equal(storageStore.servers().length,1);
});
@@ -0,0 +1,34 @@
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
const {Store}=require('../../src/modules/dashboard/store.cjs'),{StorageStore}=require('../../src/modules/storage/store.cjs'),{StorageService}=require('../../src/modules/storage/service.cjs'),{FileArea}=require('../../src/modules/storage/files.cjs');
async function fixture(t){
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-group-')),remote=path.join(dir,'remote'),output=path.join(dir,'pdf');await fs.mkdir(remote);await fs.mkdir(output);
const jobs=new Store(path.join(dir,'users')),store=new StorageStore(path.join(dir,'storage')),service=new StorageService({store,jobs,outputDir:output,client:{area:async()=>new FileArea(remote)}});
t.after(async()=>{await service.stop();store.close();await fs.rm(dir,{recursive:true,force:true});});const server=await service.saveServer({address:String.fromCharCode(92).repeat(2)+'files.test'+String.fromCharCode(92)+'orders',authMode:'windows',enabled:true});
const add=async(id,order,filename=id+'.pdf')=>{const file=path.join(output,filename);await fs.writeFile(file,'%PDF-1.7\n'+id);return jobs.recordJob({jobId:id,status:'success',filename,path:file,...(order===undefined?{}:{metadata:{order}}),createdAt:new Date(Date.now()+1000).toISOString()});};return {dir,remote,output,jobs,store,service,server,add};
}
test('BPM six digit order creates one folder and reuses an existing folder for all order documents',async t=>{
const {remote,store,service,server,add}=await fixture(t);assert.equal(store.settings().orderPrefixLength,undefined);
await fs.mkdir(path.join(remote,'001234'));await fs.writeFile(path.join(remote,'001234','keep.txt'),'preserve');
await Promise.all([add('first','001234'),add('second','001234'),add('third','001234')]);
const results=await Promise.all(['first','second','third'].map(id=>service.archive(server.id,id)));assert.deepEqual(await fs.readdir(remote),['001234']);assert.deepEqual((await fs.readdir(path.join(remote,'001234'))).sort(),['first.pdf','keep.txt','second.pdf','third.pdf']);assert.equal(results[0].relativePath,'001234/first.pdf');assert.equal(results[0].orderNumber,'001234');assert.equal(results[0].orderNumberLength,6);
const again=await service.archive(server.id,'first');assert.equal(again.relativePath,results[0].relativePath);assert.equal((await fs.readdir(path.join(remote,'001234'))).length,4);
const inOrder=await service.archive(server.id,'first','001234');assert.equal(inOrder.relativePath,'001234/first.pdf');assert.deepEqual((await fs.readdir(path.join(remote,'001234'))).sort(),['first.pdf','keep.txt','second.pdf','third.pdf']);
});
test('BPM seven digit orders stay seven digits for automatic and manual archives',async t=>{
const {remote,store,service,server,add}=await fixture(t);await service.check(server.id);service.saveSettings({serverId:server.id,enabled:true});
const automatic=await add('automatic','7654321');assert.equal((await service.automatic(automatic)).relativePath,'7654321/automatic.pdf');
await add('manual','7654321');assert.equal((await service.archive(server.id,'manual','归档')).relativePath,'归档/7654321/manual.pdf');
assert.deepEqual((await fs.readdir(remote)).sort(),['7654321','归档']);assert.equal(store.settings().orderPrefixLength,undefined);
});
test('missing, short or unsafe order IDs fail visibly and do not create misplaced folders',async t=>{
const {remote,store,service,server,add,jobs}=await fixture(t);
for(const [id,order]of [['missing',undefined],['short','12345'],['path','../123456789'],['invalid','123456:bad'],['long','1234567890'],['ambiguous','123456/7654321']]){await add(id,order);await assert.rejects(service.archive(server.id,id),e=>e.status===400);assert.equal(store.archives().find(a=>a.jobId===id).status,'error');}
assert.deepEqual(await fs.readdir(remote),[]);
await add('legacy',undefined,'0098765432_PROJECT_MODEL_NOTICE.pdf');await assert.rejects(service.archive(server.id,'legacy'),e=>e.status===400);assert.deepEqual(await fs.readdir(remote),[]);
await add('metadata','1234567','9999999999_PROJECT_MODEL_NOTICE.pdf');assert.equal((await service.archive(server.id,'metadata')).relativePath,'1234567/9999999999_PROJECT_MODEL_NOTICE.pdf');
await add('conflict','123456');jobs.recordJob({jobId:'conflict',bpmOrder:{field:'OFR_WY_Applicant.OrderNum',value:'654321'}});await assert.rejects(service.archive(server.id,'conflict'),e=>e.status===400);
});
test('an order folder that is a file or link is rejected without overwriting it',async t=>{
const {dir,remote,service,server,add}=await fixture(t);await add('collision','123456');await fs.writeFile(path.join(remote,'123456'),'keep');await assert.rejects(service.archive(server.id,'collision'));assert.equal(await fs.readFile(path.join(remote,'123456'),'utf8'),'keep');
const outside=path.join(dir,'outside');await fs.mkdir(outside);await fs.symlink(outside,path.join(remote,'654321'),'junction');await add('link','654321');await assert.rejects(service.archive(server.id,'link'));assert.deepEqual(await fs.readdir(outside),[]);
});
+19
View File
@@ -0,0 +1,19 @@
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
const {Store}=require('../../src/modules/dashboard/store.cjs'),{StorageStore}=require('../../src/modules/storage/store.cjs'),{StorageService}=require('../../src/modules/storage/service.cjs'),{FileArea,segments}=require('../../src/modules/storage/files.cjs'),{createDashboard}=require('../../src/app/dashboard.cjs'),{loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
test('directory picker selects shares and folders; cancel and timeout unlock the form',{timeout:150000},async t=>{
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'storage-picker-')),remote=path.join(dir,'remote');await fs.mkdir(path.join(remote,'子目录'),{recursive:true});const store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');const storageStore=new StorageStore(path.join(dir,'storage'));let aborted=0;
const slash=String.fromCharCode(92),address=(server)=>slash.repeat(2)+server.host+(server.share?slash+[server.share,...segments(server.directory)].join(slash):'');
const client={area:async server=>new FileArea(path.join(remote,...segments(server.directory)),{boundary:remote}),browse:async(server,{signal})=>{
if(server.host==='slow.test'){signal.addEventListener('abort',()=>aborted++,{once:true});return new Promise(()=>{});}
const current=address(server);if(!server.share)return {serverRoot:true,readable:false,address:current,parent:null,entries:[{name:'orders',address:current+slash+'orders'}]};
const listing=await(await client.area(server)).list(''),parts=[server.share,...segments(server.directory)];return {serverRoot:false,readable:true,address:current,parent:slash.repeat(2)+server.host+(parts.length>1?slash+parts.slice(0,-1).join(slash):''),entries:listing.entries.filter(e=>e.type==='directory').map(e=>({...e,address:current+slash+e.name}))};
}};
const storage=new StorageService({store:storageStore,jobs:store,outputDir:dir,client,checkTimeoutMs:10000}),server=createDashboard({store,storage,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));let browser;t.after(async()=>{await browser?.close();await storage.stop();server.closeAllConnections();await new Promise(r=>server.close(r));storageStore.close();await fs.rm(dir,{recursive:true,force:true});});
browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage({viewport:{width:1280,height:950}});page.setDefaultTimeout(15000);const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto('http://127.0.0.1:'+server.address().port+'/#storage');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'添加服务器',exact:true}).click();
const input=page.getByLabel('共享路径',{exact:true}),save=page.getByRole('button',{name:'保存服务器',exact:true});await input.fill('files.test');await page.getByRole('button',{name:'浏览',exact:true}).click();await page.getByRole('button',{name:'orders',exact:true}).waitFor();assert.equal(await save.isDisabled(),true);assert.equal(storageStore.servers().length,0);
await page.getByRole('button',{name:'orders',exact:true}).click();await page.getByRole('button',{name:'子目录',exact:true}).click();await page.getByRole('button',{name:'选择此目录',exact:true}).click();assert.equal(await input.inputValue(),slash.repeat(2)+'files.test'+slash+'orders'+slash+'子目录');assert.equal(await save.isDisabled(),false);
await input.fill('slow.test');await page.getByRole('button',{name:'检查连接',exact:true}).click();await page.getByRole('button',{name:'取消操作',exact:true}).click();await page.getByText('已取消连接操作,可修改后重试。',{exact:true}).waitFor();assert.equal(await page.getByRole('button',{name:'检查连接',exact:true}).isEnabled(),true);assert.equal(await save.isDisabled(),true);
storage.checkTimeoutMs=80;await page.getByRole('button',{name:'检查连接',exact:true}).click();await page.getByText(/连接超时,请检查服务器地址/).waitFor();assert.equal(await page.getByRole('button',{name:'检查连接',exact:true}).isEnabled(),true);assert.equal(storageStore.servers().length,0);assert.equal(aborted>=1,true);
storage.checkTimeoutMs=10000;await input.fill(slash.repeat(2)+'files.test'+slash+'orders'+slash+'子目录');await page.getByRole('button',{name:'检查连接',exact:true}).click();await page.getByText('连接成功,目标目录可读取。',{exact:true}).waitFor();await save.click();await page.getByRole('button',{name:'管理服务器',exact:true}).waitFor();assert.equal(storageStore.servers()[0].directory,'子目录');assert.deepEqual(errors,[]);
await fs.mkdir(path.resolve('output/verification'),{recursive:true});await page.screenshot({path:path.resolve('output/verification/storage-picker-tested.png'),fullPage:true});
});
@@ -0,0 +1,31 @@
'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 {StorageStore}=require('../../src/modules/storage/store.cjs');const {StorageService}=require('../../src/modules/storage/service.cjs');const {FileArea}=require('../../src/modules/storage/files.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs');const {makePreviewFiles}=require('../fixtures/storage-preview-files.cjs');
async function setup(t){
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-preview-http-')),remote=path.join(dir,'remote');await fs.mkdir(remote);await makePreviewFiles(remote);
const 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 storageStore=new StorageStore(path.join(dir,'storage')),storage=new StorageService({store:storageStore,jobs:store,outputDir:dir,client:{area:async()=>new FileArea(remote)}}),managed=await storage.saveServer({name:'托管服务器',host:'storage.company.test',share:'orders',directory:'',username:'archive',password:'Fixture-storage-password',enabled:true});
const server=createDashboard({store,storage,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));const base='http://127.0.0.1:'+server.address().port;
t.after(async()=>{await storage.stop();server.closeAllConnections();await new Promise(r=>server.close(r));storageStore.close();await fs.rm(dir,{recursive:true,force:true});});
const request=(route,cookie,extra={})=>fetch(base+route,{headers:{...(cookie?{Cookie:cookie}:{}),...extra}}),login=async username=>(await fetch(base+'/api/login',{method:'POST',headers:{Origin:base,'Content-Type':'application/json'},body:JSON.stringify({username,password:'Test-password-123'})})).headers.get('set-cookie').split(';')[0];
return {request,login,storage,managed,remote};
}
test('preview endpoints reuse authentication and root restrictions, with correct content and byte ranges',async t=>{
const {request,login,managed,storage,remote}=await setup(t),prefix='/api/storage/servers/'+managed.id;
const url=action=>prefix+'/'+action+'?path='+encodeURIComponent('说明.txt');assert.equal((await request(url('preview-info'))).status,401);const operator=await login('operator'),viewer=await login('viewer');assert.equal((await request(url('preview-info'),viewer)).status,403);
const info=await request(url('preview-info'),operator);assert.equal(info.status,200);assert.equal((await info.json()).kind,'text');
const text=await request(url('content'),operator);assert.equal(text.status,200);assert.match(text.headers.get('content-type'),/^text\/plain/);assert.match(await text.text(),/^<script>/);
const imageURL=prefix+'/content?path=sample.png',image=await request(imageURL,operator,{Range:'bytes=0-7'});assert.equal(image.status,206);assert.match(image.headers.get('content-range'),/^bytes 0-7\//);assert.deepEqual([...new Uint8Array(await image.arrayBuffer())],[137,80,78,71,13,10,26,10]);
assert.equal((await request(imageURL,operator,{Range:'bytes=999999-'})).status,416);
assert.equal((await request(prefix+'/content?path=bad.png',operator)).status,415);assert.equal((await request(prefix+'/preview-info?path=..%2Foutside.txt',operator)).status,400);
const outside=path.join(remote,'..','outside');await fs.mkdir(outside);await fs.writeFile(path.join(outside,'secret.txt'),'secret');await fs.symlink(outside,path.join(remote,'redirect'),'junction');assert.equal((await request(prefix+'/content?path=redirect%2Fsecret.txt',operator)).status,400);
const file=await request(prefix+'/file?path=unknown.bin',operator);assert.equal(file.status,200);assert.match(file.headers.get('content-disposition'),/^attachment/);assert.equal((await file.arrayBuffer()).byteLength,4);
const saved=storage.store.publicServer(managed.id);await storage.saveServer({...saved,password:'',enabled:false});assert.equal((await request(url('preview-info'),operator)).status,409);
});
test('preview shell isolates renderer permissions and serves all open-source assets locally',async t=>{
const {request}=await setup(t),page=await request('/storage-preview.html');assert.equal(page.status,200);const csp=page.headers.get('content-security-policy');assert.match(csp,/frame-ancestors 'self'/);assert.match(csp,/connect-src 'self'/);assert.doesNotMatch(csp,/https:/);
for(const route of ['/storage-preview.js','/storage-preview-office.js','/vendor/embedpdf/embedpdf.js','/vendor/embedpdf/pdfium.wasm','/vendor/docx/docx-preview.js','/vendor/jszip/jszip.min.js','/vendor/exceljs/exceljs.min.js','/vendor/photoswipe/photoswipe.esm.js','/vendor/photoswipe/photoswipe.css']){const asset=await request(route);assert.equal(asset.status,200,route);assert.ok((await asset.arrayBuffer()).byteLength>0);}
assert.equal((await request('/vendor/embedpdf/package.json')).status,404);assert.ok([401,404].includes((await request('/vendor/docx/../../package.json')).status));
});
+24
View File
@@ -0,0 +1,24 @@
'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 {StorageStore}=require('../../src/modules/storage/store.cjs');const {StorageService}=require('../../src/modules/storage/service.cjs');const {FileArea}=require('../../src/modules/storage/files.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs');const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');const {makePreviewFiles}=require('../fixtures/storage-preview-files.cjs');
test('already-managed storage previews real files locally in an isolated frame',{timeout:240000},async t=>{
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'storage-preview-ui-')),remote=path.join(dir,'remote');await fs.mkdir(remote);await makePreviewFiles(remote);
const store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');const storageStore=new StorageStore(path.join(dir,'storage')),storage=new StorageService({store:storageStore,jobs:store,outputDir:dir,client:{area:async()=>new FileArea(remote)}});await storage.saveServer({name:'已托管服务器',host:'storage.company.test',share:'orders',directory:'',username:'archive',password:'Fixture-storage-password',enabled:true});
const server=createDashboard({store,storage,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));let browser;
t.after(async()=>{await browser?.close();await storage.stop();server.closeAllConnections();await new Promise(r=>server.close(r));storageStore.close();await fs.rm(dir,{recursive:true,force:true});});
browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(15000);const errors=[],external=[],failed=[],consoleErrors=[],previewRequests=[];page.on('console',m=>{if(m.type()==='error'||m.type()==='warning')consoleErrors.push(m.text());});page.on('response',r=>{if(r.url().includes('/vendor/embedpdf/'))previewRequests.push({url:r.url(),status:r.status()});});page.on('pageerror',e=>errors.push(e.message));page.on('request',r=>{if(/^https?:/.test(r.url())&&!r.url().startsWith(base+'/'))external.push(r.url());});page.on('requestfailed',r=>failed.push({url:r.url(),error:r.failure()?.errorText}));const base='http://127.0.0.1:'+server.address().port;
const documentPage=await browser.newPage();await documentPage.setContent('<html><body><h1>PDF preview sample</h1><p>Original PDF content.</p></body></html>');await fs.writeFile(path.join(remote,'sample.pdf'),await documentPage.pdf({format:'A4'}));await documentPage.close();
await page.goto(base+'/#storage');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'浏览目录',exact:true}).click();
const frame=()=>page.frameLocator('iframe[title="文件内容预览"]');
async function open(filename){await page.locator('#storage-browser .list-group-item').filter({has:page.getByText(filename,{exact:true})}).getByRole('button',{name:'预览',exact:true}).click();}
await open('说明.txt');await frame().locator('#preview-text').waitFor();assert.equal(await frame().locator('#preview-text').textContent(),'<script>window.previewExecuted=true</script>\n第二行原文');assert.equal(await frame().locator('body').evaluate(()=>{try{void parent.document.body;return false;}catch{return window.previewExecuted!==true;}}),true);
await open('sample.docx');await frame().getByText('DOCX preview original text',{exact:true}).waitFor();
await open('sample.xlsx');await frame().getByRole('cell',{name:'42',exact:true}).waitFor();assert.equal(await frame().locator('img[src=x]').count(),0);await frame().getByLabel('工作表',{exact:true}).selectOption('1');await frame().getByRole('cell',{name:'Second sheet',exact:true}).waitFor();
await fs.mkdir(path.resolve('output/verification'),{recursive:true});await page.screenshot({path:path.resolve('output/verification/storage-preview-xlsx.png'),fullPage:true});
await open('sample.png');await frame().getByRole('button',{name:'放大图片',exact:true}).click();await frame().locator('.pswp--open').waitFor();
await open('sample.pdf');try{await frame().locator('#preview-pdf img[src^="blob:"]').first().waitFor({timeout:60000});}catch(error){t.diagnostic(JSON.stringify({failed,errors,external,consoleErrors,previewRequests,body:await frame().locator('body').evaluate(body=>{function read(node){return [...node.childNodes].map(n=>n.nodeType===3?n.textContent:n.nodeType===1&&!['STYLE','SCRIPT'].includes(n.tagName)?read(n.shadowRoot||n):'').join(' ');}return read(body);})}));throw error;}
assert.equal(await frame().locator('#preview-pdf img[src^="blob:"]').first().evaluate(async image=>{await image.decode();return image.naturalWidth>10&&image.naturalHeight>10;}),true);await page.screenshot({path:path.resolve('output/verification/storage-preview-pdf.png'),fullPage:true});
await open('old.doc');await frame().getByText(/旧版 Office 格式/).waitFor();await page.getByRole('button',{name:'关闭预览',exact:true}).click();assert.equal(await page.locator('iframe[title="文件内容预览"]').count(),0);
await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.deepEqual(external,[]);assert.deepEqual(errors,[]);
});
+31
View File
@@ -0,0 +1,31 @@
'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 {FileArea}=require('../../src/modules/storage/files.cjs');
const {makePreviewFiles}=require('../fixtures/storage-preview-files.cjs');
async function fixture(t){const root=await fs.mkdtemp(path.join(os.tmpdir(),'order-preview-files-'));t.after(()=>fs.rm(root,{recursive:true,force:true}));await makePreviewFiles(root);return {root,area:new FileArea(root)};}
test('managed file metadata distinguishes local preview formats and generic downloads',async t=>{
const {area}=await fixture(t);
for(const [file,kind] of [['说明.txt','text'],['sample.png','image'],['sample.docx','docx'],['sample.xlsx','xlsx']]){const info=await area.previewInfo(file);assert.equal(info.kind,kind);assert.equal(info.canPreview,true);assert.equal(info.filename,file);assert.ok(info.bytes>0);}
for(const file of ['sample.docx','sample.xlsx'])assert.ok((await area.readPreview(file)).bytes.length>0);
const legacy=await area.previewInfo('old.doc');assert.equal(legacy.canPreview,false);assert.equal(legacy.kind,'unsupported');assert.equal((await area.readFile('unknown.bin')).bytes.length,4);
});
test('previews validate bytes, preserve Chinese text and reject invalid or oversized documents',async t=>{
const {area,root}=await fixture(t);assert.equal((await area.readPreview('gbk.txt')).bytes.toString(),'中文');assert.match((await area.readPreview('说明.txt')).bytes.toString(),/\n第二行原文$/);
await assert.rejects(area.readPreview('bad.png'),e=>e.status===415);await assert.rejects(area.readPreview('unknown.bin'),e=>e.status===415);
await fs.writeFile(path.join(root,'fake.docx'),'not a zip');await assert.rejects(area.readPreview('fake.docx'),e=>e.status===415);
await fs.writeFile(path.join(root,'large.txt'),'');await fs.truncate(path.join(root,'large.txt'),2*1024*1024+1);assert.equal((await area.previewInfo('large.txt')).canPreview,false);await assert.rejects(area.readPreview('large.txt'),e=>e.status===413);
await assert.rejects(area.readPreview('../secret.txt'),e=>e.status===400);
});
test('Office preview refuses oversized ZIP expansion metadata',async t=>{
const {root,area}=await fixture(t),buffer=await fs.readFile(path.join(root,'sample.docx'));let position=buffer.indexOf(Buffer.from([0x50,0x4b,0x01,0x02]));assert.ok(position>=0);buffer.writeUInt32LE(70*1024*1024,position+24);await fs.writeFile(path.join(root,'bomb.docx'),buffer);await assert.rejects(area.readPreview('bomb.docx'),e=>e.status===413);
});
test('Office preview rejects forged understated ZIP expansion sizes before browser parsing',async t=>{
const {root,area}=await fixture(t),JSZip=require('jszip'),zip=new JSZip();zip.file('[Content_Types].xml','types');zip.file('word/document.xml','x'.repeat(1024*1024));
const bytes=await zip.generateAsync({type:'nodebuffer',compression:'DEFLATE'});
for(let offset=0;offset<bytes.length-28;offset++)if(bytes.readUInt32LE(offset)===0x02014b50)bytes.writeUInt32LE(1,offset+24);
await fs.writeFile(path.join(root,'understated.docx'),bytes);await assert.rejects(area.readPreview('understated.docx'),e=>[413,415].includes(e.status));
});
+10
View File
@@ -0,0 +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 {StorageStore}=require('../../src/modules/storage/store.cjs');const {StorageService}=require('../../src/modules/storage/service.cjs');const {FileArea}=require('../../src/modules/storage/files.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs');const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
test('storage page edits redacted credentials, checks files and archives an exported PDF', {timeout:150000}, async t=>{
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'storage-ui-')),remote=path.join(dir,'remote'),output=path.join(dir,'output');await fs.mkdir(remote);await fs.mkdir(output);const store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');await fs.writeFile(path.join(output,'order.pdf'),'%PDF-1.7\nUI test');store.recordJob({jobId:'ui-job',filename:'order.pdf',path:path.join(output,'order.pdf'),status:'success',metadata:{order:'001234'}});const storageStore=new StorageStore(path.join(dir,'storage')),storage=new StorageService({store:storageStore,jobs:store,outputDir:output,client:{area:async()=>new FileArea(remote)}}),server=createDashboard({store,storage,outputDir:output});await new Promise(r=>server.listen(0,'127.0.0.1',r));let browser;t.after(async()=>{await browser?.close();await storage.stop();server.closeAllConnections();await new Promise(r=>server.close(r));storageStore.close();await fs.rm(dir,{recursive:true,force:true});});browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(30000);const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto('http://127.0.0.1:'+server.address().port+'/#storage');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'添加服务器',exact:true}).click();
assert.equal(await page.getByLabel('访问方式',{exact:true}).inputValue(),'windows');assert.equal(await page.getByLabel('登录账号',{exact:true}).isVisible(),false);await page.getByLabel('访问方式',{exact:true}).selectOption('credentials');
for(const [label,value]of Object.entries({'服务器名称':'210 归档','共享路径':String.raw`\\storage.company.test\orders`,'登录账号':'archive','SMB 密码':'UI-test-password'}))await page.getByLabel(label,{exact:true}).fill(value);
assert.equal(await page.getByRole('button',{name:'保存服务器',exact:true}).isDisabled(),true);await page.getByRole('button',{name:'检查连接',exact:true}).click();await page.getByText('连接成功,目标目录可读取。',{exact:true}).waitFor();await page.getByLabel('共享路径',{exact:true}).fill(String.raw`\\storage.company.test\orders\new`);assert.equal(await page.getByRole('button',{name:'保存服务器',exact:true}).isDisabled(),true);await page.getByLabel('共享路径',{exact:true}).fill(String.raw`\\storage.company.test\orders`);await page.getByRole('button',{name:'检查连接',exact:true}).click();await page.getByText('连接成功,目标目录可读取。',{exact:true}).waitFor();
const saveResponse=page.waitForResponse(r=>r.url().endsWith('/api/storage/servers')&&r.request().method()==='POST',{timeout:45000});await page.getByRole('button',{name:'保存服务器',exact:true}).click();const savedResponse=await saveResponse;assert.equal(savedResponse.status(),201,await savedResponse.text());await page.getByRole('button',{name:'检查读写',exact:true}).click();await page.getByText('共享目录读写正常',{exact:true}).waitFor();await page.getByRole('button',{name:'管理服务器',exact:true}).click();assert.equal(await page.getByLabel('SMB 密码',{exact:true}).inputValue(),'');await page.getByLabel('此账号无密码',{exact:true}).check();await page.getByRole('button',{name:'检查连接',exact:true}).click();await page.getByText('连接成功,目标目录可读取。',{exact:true}).waitFor();await page.getByRole('button',{name:'保存服务器',exact:true}).click();await page.getByRole('button',{name:'管理服务器',exact:true}).waitFor();assert.equal(storageStore.secret(storageStore.servers()[0].id).password,'');await page.getByRole('button',{name:'管理服务器',exact:true}).click();await page.getByLabel('访问方式',{exact:true}).selectOption('windows');await page.getByRole('button',{name:'检查连接',exact:true}).click();await page.getByText('连接成功,目标目录可读取。',{exact:true}).waitFor();await page.getByRole('button',{name:'保存服务器',exact:true}).click();await page.getByRole('button',{name:'管理服务器',exact:true}).waitFor();assert.equal(storageStore.servers()[0].authMode,'windows');await page.getByRole('button',{name:'浏览目录',exact:true}).click();await page.getByLabel('新目录名称',{exact:true}).fill('产业A');await page.getByRole('button',{name:'创建目录',exact:true}).click();await page.getByText('产业A',{exact:true}).waitFor();await page.getByLabel('归档 PDF',{exact:true}).selectOption('ui-job');await page.getByText('将按 BPM 订单号自动创建或复用子目录。',{exact:true}).waitFor();await page.getByRole('button',{name:'归档到当前目录',exact:true}).click();await page.getByText('PDF 已归档。',{exact:true}).waitFor();assert.equal(await fs.readFile(path.join(remote,'001234','order.pdf'),'utf8'),'%PDF-1.7\nUI test');await fs.mkdir(path.resolve('output/verification'),{recursive:true});await page.evaluate(()=>window.scrollTo(0,0));await page.screenshot({path:path.resolve('output/verification/storage-desktop.png'),fullPage:true});await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.deepEqual(errors,[]);
});
+82
View File
@@ -0,0 +1,82 @@
'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 {StorageStore}=require('../../src/modules/storage/store.cjs');
const {FileArea}=require('../../src/modules/storage/files.cjs');
const config={name:'210 归档',host:'storage.company.test',share:'orders',directory:'通知书',username:'DOMAIN\\archive',password:'Storage-secret-123',enabled:true};
async function fixture(t){const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-storage-'));t.after(()=>fs.rm(dir,{recursive:true,force:true}));return dir;}
test('storage persists encrypted credentials, keeps blank passwords and rejects stale or changed identities',async t=>{
let store;t.after(()=>store?.close());const dir=await fixture(t);store=new StorageStore(dir);
const saved=store.saveServer(config);assert.equal(saved.hasPassword,true);assert.equal(saved.password,undefined);
assert.doesNotMatch(JSON.stringify(store.servers()),/Storage-secret/);
assert.doesNotMatch((await fs.readFile(path.join(dir,'storage.sqlite'))).toString('utf8'),/Storage-secret-123/);
assert.equal(store.secret(saved.id).password,'Storage-secret-123');
assert.equal(store.saveServer({...saved,password:'',name:'归档服务器'}).version,2);
assert.throws(()=>store.saveServer({...saved,password:''}),e=>e.status===409);
const current=store.publicServer(saved.id);
assert.throws(()=>store.saveServer({...current,host:'other.company.test',password:''}),e=>e.status===400);
assert.throws(()=>store.saveServer({...current,directory:'../outside',password:''}),e=>e.status===400);
assert.throws(()=>store.saveServer({...current,share:'orders\\other',password:''}),e=>e.status===400);
store.close();store=new StorageStore(dir);assert.equal(store.secret(saved.id).password,'Storage-secret-123');
const record=store.beginArchive(saved.id,'job-1','admin','');assert.equal(record.status,'running');
store.close();store=new StorageStore(dir);assert.equal(store.archives()[0].status,'interrupted');
for(let index=0;index<101;index++)store.beginArchive(saved.id,'later-'+index,'admin','');
assert.equal(store.finishArchive(record.id,'success',{filename:'old.pdf'}).status,'success');
});
test('file area publishes real PDFs idempotently and preserves different same-name content',async t=>{
const dir=await fixture(t),root=path.join(dir,'remote');await fs.mkdir(root);const area=new FileArea(root);
await area.check();assert.deepEqual(await fs.readdir(root),[]);
await area.mkdir('产业A');const file=path.join(dir,'source.pdf');await fs.writeFile(file,'%PDF-1.7\nfirst document\n%%EOF');
const first=await area.archive(file,'订单.pdf','产业A');assert.equal(first.filename,'订单.pdf');assert.equal(first.bytes,29);
assert.equal((await area.readPdf('产业A/订单.pdf')).bytes.toString(),'%PDF-1.7\nfirst document\n%%EOF');
const again=await area.archive(file,'订单.pdf','产业A');assert.equal(again.relativePath,first.relativePath);
await fs.writeFile(file,'%PDF-1.7\nsecond document\n%%EOF');
const second=await area.archive(file,'订单.pdf','产业A');assert.notEqual(second.filename,first.filename);
assert.equal((await fs.readdir(path.join(root,'产业A'))).length,2);
assert.equal((await area.readPdf('产业A/订单.pdf')).bytes.toString(),'%PDF-1.7\nfirst document\n%%EOF');
assert.deepEqual((await area.list('')).entries.map(e=>e.name),['产业A']);
});
test('file area rejects parent paths, alternate streams, symlinks and non-PDF sources',async t=>{
const dir=await fixture(t),root=path.join(dir,'remote'),outside=path.join(dir,'outside');await fs.mkdir(root);await fs.mkdir(outside);const area=new FileArea(root);
for(const relative of ['../outside','C:\\secret','\\\\other\\share','a:stream','CON','folder./secret','a/../b'])await assert.rejects(area.list(relative),e=>e.status===400);
await fs.symlink(outside,path.join(root,'escape'),'junction');await assert.rejects(area.mkdir('escape/nested'),e=>e.status===400);
const file=path.join(dir,'not.pdf');await fs.writeFile(file,'not a PDF');await assert.rejects(area.archive(file,'file.pdf',''),e=>e.status===400);
await assert.rejects(area.readPdf('not.txt'),e=>e.status===400);
});
test('configured archive root cannot escape through an intermediate directory junction',async t=>{
const dir=await fixture(t),share=path.join(dir,'share'),outside=path.join(dir,'outside');await fs.mkdir(share);await fs.mkdir(path.join(outside,'nested'),{recursive:true});await fs.symlink(outside,path.join(share,'redirect'),'junction');
const area=new FileArea(path.join(share,'redirect','nested'),{boundary:share});
await assert.rejects(area.list(''),e=>e.status===400);
assert.deepEqual(await fs.readdir(path.join(outside,'nested')),[]);
});
test('storage accepts a complete UNC path and Windows identity without credentials',async t=>{
let store;t.after(()=>store?.close());const dir=await fixture(t);store=new StorageStore(dir);
const saved=store.saveServer({address:String.raw`\\files.example.test\orders\归档`,authMode:'windows',enabled:true});
assert.equal(saved.host,'files.example.test');assert.equal(saved.share,'orders');assert.equal(saved.directory,'归档');assert.equal(saved.name,'files.example.test / orders');assert.equal(saved.authMode,'windows');assert.equal(saved.hasPassword,false);assert.equal(store.secret(saved.id).password,'');
for(const address of [String.raw`\\server`,String.raw`\\server\orders\..\secret`,'C:/local','https://server/orders'])assert.throws(()=>store.saveServer({address,authMode:'windows',enabled:true}),e=>e.status===400);
const credentials=store.saveServer(config);const switched=store.saveServer({...credentials,authMode:'windows'});assert.equal(store.secret(switched.id).password,'');assert.equal(switched.username,'');
});
test('explicit passwordless account does not accidentally retain a saved password',async t=>{
let store;t.after(()=>store?.close());const dir=await fixture(t);store=new StorageStore(dir);const saved=store.saveServer(config);
const passwordless=store.saveServer({...saved,authMode:'credentials',passwordless:true,password:''});assert.equal(store.secret(saved.id).password,'');assert.equal(passwordless.hasPassword,false);
assert.equal(store.saveServer({...passwordless,password:''}).passwordless,true);
assert.throws(()=>store.saveServer({...store.publicServer(saved.id),passwordless:false,password:''}),e=>e.status===400);
});
test('Windows identity mode uses UNC access without requesting a new SMB login',async t=>{
const native=require('../../src/modules/storage/smb-native.cjs');let calls=0;t.mock.method(native,'connect',async()=>{calls++;});
const {SmbClient}=require('../../src/modules/storage/files.cjs'),client=new SmbClient();
const area=await client.area({host:'files.example.test',share:'orders',directory:'archive',authMode:'windows'});assert.equal(calls,0);assert.equal(area.root,path.resolve(String.raw`\\files.example.test\orders\archive`));
await client.area({...config,authMode:'credentials'});assert.equal(calls,1);
await client.area(config);assert.equal(calls,2);
});