feat(storage): require readable connections before adding servers

This commit is contained in:
阿白叔 committed 2026-10-17 14:12:27 +08:00
1 parent b34d51432d
commit 8417b1dff8
11 files changed
+100 -20

No files matched your search

+1 -1
View File
@@ -39,7 +39,7 @@
## 存储服务器与业务通知
- **存储服务器**:管理员粘贴完整 Windows 共享路径(例如 `\\210服务器\订单\归档`),自动识别主机、共享和子目录;名称可留空自动生成。默认“免填账号密码(使用 Windows 权限)”,直接复用部署机现有 SMB 会话或运行服务账号的共享访问权限,适用于已获授权和系统允许的免密共享。需要独立凭据时选择“指定账号”;无密码账号勾选“此账号无密码”。密码加密保存在部署机,编辑留空保留原密码;更换主机、共享或账号需重新录入。旧配置按指定账号方式继续使用。保存配置不连接服务器,点击“检查读写”会创建、读取并清理一个随机探测文件。配置维护要求部署机回环地址或可信 HTTPS。
- **存储服务器**:管理员粘贴完整 Windows 共享路径(例如 `\\210服务器\订单\归档`),自动识别主机、共享和子目录;名称可留空自动生成。默认“免填账号密码(使用 Windows 权限)”,直接复用部署机现有 SMB 会话或运行服务账号的共享访问权限,适用于已获授权和系统允许的免密共享。需要独立凭据时选择“指定账号”;无密码账号勾选“此账号无密码”。密码加密保存在部署机,编辑留空保留原密码;更换主机、共享或账号需重新录入。旧配置按指定账号方式继续使用。添加前先点击“检查连接”,能读取目录后才能保存;修改连接或重新启用时需重新检查,保存接口会再次确认可读取。草稿检查不保存配置、不创建文件;“检查读写”用于归档前的写权限验证,会创建、读取并清理随机探测文件。配置维护要求部署机回环地址或可信 HTTPS。
- **免填模式说明**:使用服务部署机上的权限及既有 SMB 会话,不是网页访问者电脑的身份。切换模式会清除托管凭据、重置检查状态并暂停该服务器的自动归档,但不会强制断开 Windows 已有共享会话;若已有其他账号连接,实际访问可能继续使用该会话,需由部署机管理员处理。服务器要求认证或 Windows 禁止来宾/空密码访问时仍可能被拒绝,本工具不自动更改这些系统设置。
- **文件管理**:管理员与操作员可浏览归档目录、创建子目录、下载文件和内嵌预览,将已有成功导出的 PDF 归档。目标存在相同内容时幂等完成;不同内容保留新文件,原件不覆盖。只读成员查看服务器和归档记录。启用自动归档后仅处理新导出的 PDF,历史文件由人选择归档;失败记录可通过重新选择同一任务重试。
- **文件预览**:在已托管服务器的目录中点击“预览”,支持 PDF、PNG/JPEG/GIF/WebP/BMP、文本(含 UTF-8、UTF-16 与 GB18030)、DOCX 和 XLSX。支持全屏、图片缩放与工作表切换;文本仅按原文显示。单文件预览及下载上限 64 MiB,文本预览上限 2 MiB;Office 展开内容最多 64 MiB、4096 个条目,Excel 每张表最多预览前 500 行、50 列。旧 DOC/XLS 与其他未支持格式可下载原文件。Office 预览以内容阅读为主,不保证与桌面 Office 排版完全一致,Excel 数值按原始值展示,不执行宏或重新计算公式。PDF 已关闭公网补充字体,缺少内嵌字体的文档可能出现字体替代。
+2
View File
@@ -13,6 +13,8 @@
| 密码 | 指定账号时由管理员在工作台录入;无密码账号明确勾选“此账号无密码”,不放资料表中 |
| 自动归档 | 是否作为新导出 PDF 的自动归档目标 |
填写后先点击“检查连接”,确认目录可读取再保存。检查失败不新增服务器;更改路径、访问方式或账号密码需要重查。浏览和预览只需读取权限,归档及自动归档需要另行通过“检查读写”。
## 业务通知来源
请提供一份脱敏来源对象样本,并标明以下字段的真实路径。支持中文、英文及嵌套对象点路径;不执行表达式。
@@ -0,0 +1,22 @@
# 添加存储前检查连接
日期:2026-10-17。
添加服务器时先点击“检查连接”,通过目录读取检查后才能保存。修改共享路径、访问方式、账号密码或重新启用已停用服务器时,检查结果失效;过期请求返回不会误解锁新表单。保存失败保留输入及错误原因。
草稿检查使用与保存相同的路径和凭据校验,并调用真实 SMB 客户端打开、枚举目标目录;不保存草稿,不创建探测文件,不把凭据返回给浏览器。POST `/api/storage/servers/check` 复用管理员及本机/HTTPS 校验。
保存接口对新增、连接信息改变和重新启用独立重读目录,失败则不新增/更新记录;并在最终写入时重新校验版本,防止并发覆盖。只读连接的初始状态为 readable=true、writable=false,归档前仍需检查写入权限。已有离线连接可以直接停用或改名。
待完成的检查任务受服务关闭流程管理,服务停止后不会写入配置。
验证命令与范围:
- `node --test tests/storage-http.test.cjs`:3 项,含草稿不落库、不写探测文件、检查后目录断开拒绝新增、无法读取拒绝改连接、离线可停用但不能重新启用。
- `node --test --test-concurrency=2 tests/storage.test.cjs tests/storage-preview.test.cjs tests/storage-preview-http.test.cjs`:13 项。
- `node --test tests/storage-ui.test.cjs`:1 项,新增按钮禁用/检查解锁及编辑重新检查,原凭据与归档流程回归。
- 现场隔离脚本 `output/verify-smb-precheck.cjs` 使用本机真实 SMB 共享、默认 SmbClient 和单独临时工作台,验证读到目录但尚无服务器记录、检查后删除目录导致保存 502、恢复后重新检查保存、预览与归档。
脚本及截图保存在本机忽略目录 output,不将测试凭据或样例文件加入仓库。正式工作台不添加测试服务器。独立只读审查覆盖版本竞争、停止时未决检查、凭据隔离及表单检查失效;建议的重新启用校验已补充。
上述验证全部通过,共 18 项;未运行全量测试集。语法检查和 git diff --check 通过。实际测试共享子目录已清理。
+3 -2
View File
@@ -7,10 +7,11 @@ async function storageApi({storage,workspace,user,url,route,method,body,request,
const audit=(action,detail)=>workspace?.record(user,action,detail);
if(route==='/api/storage'&&method==='GET'){reply(200,{servers:storage.store.servers(),settings:storage.store.settings(),archives:storage.store.archives()});return true;}
if(user.role==='viewer')fail('仅管理员和操作员可以操作归档文件。',403);
if(route==='/api/storage/servers'&&method==='POST'){
if((route==='/api/storage/servers'||route==='/api/storage/servers/check')&&method==='POST'){
if(user.role!=='admin')fail('仅管理员可以维护存储服务器。',403);
if(!secureBpmTransport(request,trustedProxy))fail('请在部署机本地或 HTTPS 页面维护存储账号。',403);
const saved=storage.saveServer(body);audit('保存存储服务器',saved.name);reply(body.id?200:201,saved);return true;
if(route.endsWith('/check')){reply(200,await storage.checkConnection(body));return true;}
const saved=await storage.saveServer(body);audit('保存存储服务器',saved.name);reply(body.id?200:201,saved);return true;
}
if(route==='/api/storage/settings'&&method==='POST'){if(user.role!=='admin')fail('仅管理员可以修改自动归档设置。',403);payload(body,['serverId','enabled']);const saved=storage.saveSettings(body);audit('保存自动归档设置',saved.enabled?'已启用':'已暂停');reply(200,saved);return true;}
const match=/^\/api\/storage\/servers\/([\w-]+)\/(check|files|folders|archive|file|preview-info|content)$/.exec(route);
+17 -3
View File
@@ -4,9 +4,23 @@ const {SmbClient,segments,inside}=require('./storage-files.cjs');
const fail=(message,status=400)=>Object.assign(new Error(message),{status});
const safe=e=>e.status?e:fail(({ENOENT:'找不到文件或归档目录,请检查路径。',EACCES:'没有共享目录访问权限。',EPERM:'没有共享目录操作权限。',ENOSPC:'存储服务器空间不足。',ENOTDIR:'指定路径不是目录。'})[e.code]||'存储操作未完成,请检查服务器与网络。',502);
class StorageService{
constructor({store,jobs,outputDir,client=new SmbClient()}){this.store=store;this.jobs=jobs;this.outputDir=outputDir;this.client=client;this.running=new Map();this.stopped=false;}
constructor({store,jobs,outputDir,client=new SmbClient()}){this.store=store;this.jobs=jobs;this.outputDir=outputDir;this.client=client;this.running=new Map();this.pendingChecks=new Set();this.stopped=false;}
busy(id){return this.running.has(id);}
saveServer(input){if(input?.id&&this.busy(input.id))throw fail('此服务器正在执行操作,请稍后保存。',409);return this.store.saveServer(input);}
async saveServer(input){
if(this.stopped)throw fail('存储服务正在停止。',503);
const snapshot=structuredClone(input),{changed}=this.store.prepareServer(snapshot);
if(snapshot.id&&this.busy(snapshot.id))throw fail('此服务器正在执行操作,请稍后保存。',409);
const readState=changed?await this.checkConnection(snapshot):null;
if(this.stopped)throw fail('存储服务正在停止。',503);
if(snapshot.id&&this.busy(snapshot.id))throw fail('此服务器正在执行操作,请稍后保存。',409);
return this.store.saveServer(snapshot,readState);
}
async checkConnection(input){
if(this.stopped)throw fail('存储服务正在停止。',503);
const {saved}=this.store.prepareServer(input);
const task=(async()=>{try{const area=await this.client.area(saved);await area.list('');return {readable:true,checkedAt:new Date().toISOString(),message:'连接成功,目标目录可读取。'};}catch(error){throw safe(error);}})();
this.pendingChecks.add(task);try{return await task;}finally{this.pendingChecks.delete(task);}
}
saveSettings(input){if(input?.enabled){const server=this.store.publicServer(input.serverId);if(!server.enabled||!server.state.readable||!server.state.writable)throw fail('请先启用服务器并检查读写成功。',409);}return this.store.saveSettings(input);}
run(id,work){
if(this.stopped)return Promise.reject(fail('存储服务正在停止。',503));
@@ -31,6 +45,6 @@ class StorageService{
});
}
async automatic(job){const settings=this.store.settings();if(!settings.enabled||job.status!=='success'||!job.createdAt||job.createdAt<settings.since)return null;return this.archive(settings.serverId,job.jobId,'','自动归档');}
async stop(){this.stopped=true;await Promise.allSettled([...this.running.values()]);}
async stop(){this.stopped=true;await Promise.allSettled([...this.running.values(),...this.pendingChecks]);}
}
module.exports={StorageService};
+7 -3
View File
@@ -22,7 +22,7 @@ class StorageStore{
secret(id){const row=this.row(id);try{const saved=this.vault.decode(id,row.payload);return {authMode:'credentials',passwordless:false,...saved,id,version:row.version,state:JSON.parse(row.state)};}catch{fail('存储凭据无法解密,请联系管理员。',503);}}
publicServer(id){const {password,...server}=this.secret(id);return {...server,hasPassword:!!password};}
servers(){return this.db.prepare('SELECT id FROM servers ORDER BY rowid').all().map(r=>this.publicServer(r.id));}
saveServer(input){
prepareServer(input){
const fields=['id','version','name','host','share','directory','username','password','enabled','state','hasPassword','createdAt','updatedAt','address','authMode','passwordless'];
if(!input||typeof input!=='object'||Array.isArray(input)||Object.keys(input).some(k=>!fields.includes(k)))fail('存储服务器配置无效。');
const old=input.id?this.secret(input.id):null;if(old&&input.version!==old.version)fail('服务器已被修改,请刷新后重试。',409);
@@ -53,9 +53,13 @@ class StorageStore{
if(typeof input.enabled!=='boolean')fail('请选择服务器是否启用。');
const name=input.name===undefined||input.name===''?(host+' / '+share).slice(0,80):text(input.name,'服务器名称',80);
const id=old?.id||crypto.randomUUID(),saved={name,host,share,directory,authMode,passwordless,username,password,enabled:input.enabled,createdAt:old?.createdAt||now(),updatedAt:now()};
const changed=!old||['host','share','directory','authMode','username','password'].some(k=>saved[k]!==old[k])||(!old.enabled&&saved.enabled);
return {id,saved,old,changed};
}
saveServer(input,readState){
const {id,saved,old,changed}=this.prepareServer(input);
let payload;try{payload=this.vault.encode(id,saved);}catch{fail('存储凭据加密不可用,请联系管理员。',503);}
const changed=!old||['host','share','directory','authMode','username','password'].some(k=>saved[k]!==old[k]);
const state=changed?{checkedAt:null,readable:false,writable:false,message:'待检查连接'}:old.state;
const state=changed?(readState?{checkedAt:readState.checkedAt,readable:true,writable:false,message:'目录可读取,写入权限尚未检查'}:{checkedAt:null,readable:false,writable:false,message:'待检查连接'}):old.state;
this.db.prepare('INSERT INTO servers VALUES(?,?,?,?) ON CONFLICT(id) DO UPDATE SET version=excluded.version,payload=excluded.payload,state=excluded.state').run(id,(old?.version||0)+1,payload,JSON.stringify(state));
if(old&&(!saved.enabled||changed)&&this.settings().serverId===id)this.saveSettings({serverId:id,enabled:false});
return this.publicServer(id);
+18 -1
View File
@@ -25,7 +25,7 @@ test('storage HTTP enforces roles, redacts passwords and archives only successfu
});
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=storage.saveServer(config);await fs.writeFile(path.join(outputDir,'new.pdf'),'%PDF-1.7\nnew');
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);
@@ -33,3 +33,20 @@ test('automatic storage is opt-in, starts with new jobs and never queues mail',a
const job=store.recordJob({jobId:'new-job',status:'success',path:path.join(outputDir,'new.pdf'),filename:'new.pdf',createdAt:new Date(Date.now()+1).toISOString()});await storage.automatic(job);
assert.deepEqual(await fs.readdir(remote),['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);
});
+2 -2
View File
@@ -5,7 +5,7 @@ const {Store}=require('../src/dashboard-store.cjs');const {StorageStore}=require
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=storage.saveServer({name:'托管服务器',host:'storage.company.test',share:'orders',directory:'',username:'archive',password:'Fixture-storage-password',enabled:true});
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];
@@ -21,7 +21,7 @@ test('preview endpoints reuse authentication and root restrictions, with correct
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);storage.saveServer({...saved,password:'',enabled:false});assert.equal((await request(url('preview-info'),operator)).status,409);
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=>{
+1 -1
View File
@@ -4,7 +4,7 @@ const {Store}=require('../src/dashboard-store.cjs');const {StorageStore}=require
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)}});storage.saveServer({name:'已托管服务器',host:'storage.company.test',share:'orders',directory:'',username:'archive',password:'Fixture-storage-password',enabled:true});
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;
+2 -1
View File
@@ -5,5 +5,6 @@ test('storage page edits redacted credentials, checks files and archives an expo
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'});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);
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.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.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.getByRole('button',{name:'归档到当前目录',exact:true}).click();await page.getByText('PDF 已归档。',{exact:true}).waitFor();assert.equal(await fs.readFile(path.join(remote,'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,[]);
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.getByRole('button',{name:'归档到当前目录',exact:true}).click();await page.getByText('PDF 已归档。',{exact:true}).waitFor();assert.equal(await fs.readFile(path.join(remote,'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,[]);
});
+25 -6
View File
@@ -16,16 +16,35 @@
<div class="mb-3"><label class="form-label" for="storage-auth">访问方式</label><select class="form-select" id="storage-auth"><option value="windows" ${mode==='windows'?'selected':''}>免填账号密码(使用 Windows 权限)</option><option value="credentials" ${mode==='credentials'?'selected':''}>指定账号</option></select><div class="form-hint">免填模式复用部署机已有 Windows 共享登录或服务账号权限,也适用于系统允许的免密共享。切换方式不会断开系统已有连接。</div></div>
<fieldset id="storage-credentials" class="row g-3 mb-3"><div class="col-md-6"><label class="form-label" for="storage-username">登录账号</label><input class="form-control" id="storage-username" value="${esc(s.username)}" maxlength="200" required autocomplete="off"></div><div class="col-md-6"><label class="form-label" for="storage-password">SMB 密码</label><input class="form-control" type="password" id="storage-password" maxlength="2048" autocomplete="new-password"><div class="form-hint">${s.id&&s.hasPassword?'留空保留现有密码;更换服务器、共享或账号时重新填写。':'密码加密保存在部署机。'}</div></div><div class="col-12"><label class="form-check"><input class="form-check-input" type="checkbox" id="storage-passwordless" ${s.passwordless?'checked':''}><span class="form-check-label">此账号无密码</span></label></div></fieldset>
<div class="mb-3"><label class="form-label" for="storage-name">服务器名称</label><input class="form-control" id="storage-name" value="${esc(s.name)}" maxlength="80" placeholder="可选,留空自动生成" autocomplete="off"></div>
<label class="form-check"><input class="form-check-input" type="checkbox" id="storage-active" ${s.enabled?'checked':''}><span class="form-check-label">启用服务器</span></label><div class="text-danger mt-3" id="storage-error" role="alert"></div></div><div class="card-footer btn-list"><button class="btn" type="button" id="storage-cancel">取消编辑</button><button class="btn btn-primary ms-auto" type="submit">保存服务器</button></div></form>`;
<label class="form-check"><input class="form-check-input" type="checkbox" id="storage-active" ${s.enabled?'checked':''}><span class="form-check-label">启用服务器</span></label><div class="text-secondary mt-3" id="storage-connection-status" role="status">${s.id?'修改连接信息后需重新检查。':'请先检查连接,确认目录可读取后再保存。'}</div><div class="text-danger mt-3" id="storage-error" role="alert"></div></div><div class="card-footer btn-list"><button class="btn" type="button" id="storage-cancel">取消编辑</button><button class="btn ms-auto" type="button" id="storage-connection-check">检查连接</button><button class="btn btn-primary" type="submit" ${s.id?'':'disabled'}>保存服务器</button></div></form>`;
const auth=host.querySelector('#storage-auth'),credentials=host.querySelector('#storage-credentials'),passwordless=host.querySelector('#storage-passwordless'),password=host.querySelector('#storage-password');
function syncAuth(){const custom=auth.value==='credentials';credentials.hidden=!custom;credentials.disabled=!custom;password.disabled=!custom||passwordless.checked;password.required=custom&&!passwordless.checked&&(!s.hasPassword||mode!=='credentials');}
auth.onchange=syncAuth;passwordless.onchange=syncAuth;syncAuth();
host.querySelector('#storage-cancel').onclick=()=>host.replaceChildren();
host.querySelector('form').onsubmit=async e=>{e.preventDefault();await action(e.submitter,async()=>{
const form=host.querySelector('form'),checkButton=host.querySelector('#storage-connection-check'),saveButton=form.querySelector('[type="submit"]'),status=host.querySelector('#storage-connection-status'),errorBox=host.querySelector('#storage-error');
let verified=!!s.id,checking=false,saving=false,revision=0;
const alive=()=>isActive()&&form.isConnected;
const update=()=>{saveButton.disabled=!verified||checking||saving;checkButton.disabled=checking||saving;};
function details(){
const input={...(s.id?{id:s.id,version:s.version}:{}),address:host.querySelector('#storage-address').value,name:host.querySelector('#storage-name').value,authMode:auth.value,enabled:host.querySelector('#storage-active').checked};
if(auth.value==='credentials')Object.assign(input,{username:host.querySelector('#storage-username').value,password:passwordless.checked?'':password.value,passwordless:passwordless.checked});
try{await api('/storage/servers',input);if(isActive()){notify('存储服务器已保存。');await render(container,isActive);}}catch(error){if(isActive())host.querySelector('#storage-error').textContent=error.message;}
});};host.scrollIntoView({block:'start',behavior:'smooth'});
if(auth.value==='credentials')Object.assign(input,{username:host.querySelector('#storage-username').value,password:passwordless.checked?'':password.value,passwordless:passwordless.checked});return input;
}
function invalidate(event){if(!['storage-address','storage-auth','storage-username','storage-password','storage-passwordless'].includes(event.target.id)&&!(event.target.id==='storage-active'&&!s.enabled&&event.target.checked))return;revision++;verified=false;errorBox.textContent='';status.textContent='连接信息已变更,请重新检查。';update();}
form.addEventListener('input',invalidate);form.addEventListener('change',invalidate);
checkButton.onclick=async()=>{
if(checking||saving||!form.reportValidity())return;
const at=revision;verified=false;checking=true;errorBox.textContent='';status.textContent='正在检查连接…';update();
try{const result=await api('/storage/servers/check',details());if(alive()&&at===revision){verified=result.readable===true;status.textContent=result.message;}}
catch(error){if(alive()&&at===revision){errorBox.textContent=error.message;status.textContent='连接检查失败,尚未保存。';}}
finally{checking=false;if(alive())update();}
};
host.querySelector('#storage-cancel').onclick=()=>host.replaceChildren();
form.onsubmit=async e=>{
e.preventDefault();if(saving||checking)return;if(!verified){errorBox.textContent='请先检查连接,确认目录可读取后再保存。';return;}
const input=details();saving=true;errorBox.textContent='';form.querySelectorAll('input,select,button').forEach(node=>node.disabled=true);
try{await api('/storage/servers',input);if(alive()){notify('存储服务器已保存。');await render(container,isActive);}}
catch(error){if(alive()){verified=false;errorBox.textContent=error.message;status.textContent='保存失败,请重新检查连接后重试。';}}
finally{saving=false;if(alive()){form.querySelectorAll('input,select,button').forEach(node=>node.disabled=false);syncAuth();update();}}
};update();host.scrollIntoView({block:'start',behavior:'smooth'});
}
if(admin){container.querySelector('#storage-add').onclick=()=>editor();container.querySelectorAll('[data-storage-edit]').forEach(b=>b.onclick=()=>editor(data.servers.find(s=>s.id===b.dataset.storageEdit)));container.querySelectorAll('[data-storage-check]').forEach(b=>b.onclick=()=>action(b,async()=>{await api('/storage/servers/'+b.dataset.storageCheck+'/check',{});if(isActive()){notify('存储服务器读写检查成功。');await render(container,isActive);}}));container.querySelector('#storage-auto').onsubmit=e=>{e.preventDefault();return action(e.submitter,async()=>{await api('/storage/settings',{serverId:container.querySelector('#storage-default').value,enabled:container.querySelector('#storage-enabled').checked});if(isActive()){notify('自动归档设置已保存。');await render(container,isActive);}});};}
let preview;