diff --git a/README.md b/README.md index 29b4f98..0969536 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ ## 存储服务器与业务通知 -- **存储服务器**:管理员粘贴完整 Windows 共享路径(例如 `\\210服务器\订单\归档`),自动识别主机、共享和子目录;名称可留空自动生成。默认“免填账号密码(使用 Windows 权限)”,直接复用部署机现有 SMB 会话或运行服务账号的共享访问权限,适用于已获授权和系统允许的免密共享。需要独立凭据时选择“指定账号”;无密码账号勾选“此账号无密码”。密码加密保存在部署机,编辑留空保留原密码;更换主机、共享或账号需重新录入。旧配置按指定账号方式继续使用。添加前先点击“检查连接”,能读取目录后才能保存;修改连接或重新启用时需重新检查,保存接口会再次确认可读取。草稿检查不保存配置、不创建文件;“检查读写”用于归档前的写权限验证,会创建、读取并清理随机探测文件。配置维护要求部署机回环地址或可信 HTTPS。 +- **存储服务器**:管理员可先填写服务器 IP / 主机名,点击“浏览”列出共享并逐层选择目录,也可粘贴完整 Windows 共享路径(例如 `\\210服务器\订单\归档`),自动识别主机、共享和子目录;名称可留空自动生成。默认“免填账号密码(使用 Windows 权限)”,直接复用部署机现有 SMB 会话或运行服务账号的共享访问权限,适用于已获授权和系统允许的免密共享。需要独立凭据时选择“指定账号”;无密码账号勾选“此账号无密码”。密码加密保存在部署机,编辑留空保留原密码;更换主机、共享或账号需重新录入。旧配置按指定账号方式继续使用。添加前先点击“检查连接”,能读取目录后才能保存;修改连接或重新启用时需重新检查,保存接口会再次确认可读取。服务器入口只用于选择共享,不会直接保存为文件目录。草稿检查不保存配置、不创建文件;检查/目录选择使用独立进程,15 秒超时并提供“取消操作”,取消后终止工作进程,避免网络目录等待占住工作台;“检查读写”用于归档前的写权限验证,会创建、读取并清理随机探测文件。配置维护要求部署机回环地址或可信 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 已关闭公网补充字体,缺少内嵌字体的文档可能出现字体替代。 diff --git a/docs/business-configuration.md b/docs/business-configuration.md index 42705dc..9f3d83d 100644 --- a/docs/business-configuration.md +++ b/docs/business-configuration.md @@ -7,13 +7,13 @@ | 项目 | 需要整理的内容 | |---|---| | 名称 | 便于同事识别的服务器名称 | -| 共享路径 | 从文件资源管理器复制完整路径,如 `\\服务器\共享\归档`,名称可自动生成 | +| 共享路径 | 可只填写服务器 IP / 主机名,再点击“浏览”选择共享和子目录;也可复制完整路径,如 `\\服务器\共享\归档`,名称可自动生成 | | 访问方式 | 默认免填账号密码,复用部署机现有 Windows SMB 会话/权限;或指定账号 | | 登录账号 | 指定账号时填写,域账号可使用 `域\账号` | | 密码 | 指定账号时由管理员在工作台录入;无密码账号明确勾选“此账号无密码”,不放资料表中 | | 自动归档 | 是否作为新导出 PDF 的自动归档目标 | -填写后先点击“检查连接”,确认目录可读取再保存。检查失败不新增服务器;更改路径、访问方式或账号密码需要重查。浏览和预览只需读取权限,归档及自动归档需要另行通过“检查读写”。 +填写服务器入口后点击“浏览”,进入共享并选择目录;也可对完整路径点击“检查连接”,确认目录可读取再保存。检查或浏览期间可取消,网络等待有 15 秒上限。检查失败不新增服务器;更改路径、访问方式或账号密码需要重查。浏览和预览只需读取权限,归档及自动归档需要另行通过“检查读写”。 ## 业务通知来源 diff --git a/docs/storage-browser-timeout-2026-10-17.md b/docs/storage-browser-timeout-2026-10-17.md new file mode 100644 index 0000000..58accce --- /dev/null +++ b/docs/storage-browser-timeout-2026-10-17.md @@ -0,0 +1,42 @@ +# 服务器共享浏览与连接等待修复 + +日期:2026-10-17。 + +原问题复现:StorageService.checkConnection 直接等待 Windows UNC 目录读取,未设总超时;注入永不返回的 list 可使 pendingChecks 一直保留。前端因此一直禁用检查/保存,缺少取消入口。 + +## 实现 + +- 表单接受单独 IP、主机名或 `\\服务器`,点击“浏览”调用 Windows NetShareEnum 枚举普通磁盘共享,再进入共享与子目录。支持上一级、选择当前目录和完整 UNC 路径。 +- 服务器入口检查成功仅用于列举共享;保存仍必须选择实际可读共享目录,根入口检查不会误解锁保存。 +- 草稿检查与目录选择在独立 Node 工作进程中运行;复用原有 FileArea 的逐段路径、根目录和链接限制。服务器枚举采用 Windows 原生 NetShareEnum,受正常 SMB 权限限制,隐藏管理共享不列出。显式账号通过 IPC$ 建立同服务器认证,不自动断开已有连接。 +- 后端总等待 15 秒,外部取消和关闭表单触发终止工作进程树。若树终止失败尝试直接终止工作进程,等待退出,最后有 1.5 秒清理上限;服务关闭等待最多 1.8 秒额外清理,避免无限等待。若系统拒绝终止进程,不能保证其下游系统组件即时结束。 +- 前端检查/浏览有 18 秒等待上限及“取消操作”,输入变更取消旧请求,旧结果不影响当前表单;保存响应有 45 秒上限,避免误以为结果已确定。 +- 每次列表最多 500 项;Native 枚举输出上限 384 KiB、工作进程结果上限 512 KiB,全部有界。密码只通过管道传给工作进程,不进入命令行或返回正文。 + +## OpenList 参考核实 + +检查 [OpenList v4.2.7 SMB util.go](https://github.com/OpenListTeam/OpenList/blob/v4.2.7/drivers/smb/util.go) 中的 Dial(ctx)、Mount(ShareName),以及 [driver.go](https://github.com/OpenListTeam/OpenList/blob/v4.2.7/drivers/smb/driver.go) 中 List/checkConn/ReadDir 的分步流程。上游仍显式配置 ShareName,不能据此声称它本身实现了本次的服务器共享选择器。此处采用独立编写的 Windows 原生实现,未复制 AGPL 后端源码;15 秒上限是本项目的实现选择。 + +## 验证范围 + +- 新增超时、取消、关闭服务、失败的 taskkill 退出后降级终止、501 个中文共享名输出上限回归。 +- HTTP 覆盖服务器根入口枚举、管理员/同源限制、根入口禁止保存、选定共享可保存;原凭据和目录限制继续回归。 +- 浏览器覆盖选择共享、进入子目录、取消/超时后恢复、重新检查和保存。 +- 现场使用本机 SMB 共享及独立临时工作台,脚本 `output/verify-smb-browser.cjs`,从只填127.0.0.1开始逐层选择;未向正式工作台添加测试配置。 +- 手工对独立进程强制1ms超时、主动取消,再次成功枚举本机9个共享,验证恢复能力。 + +边界:本次期限与进程隔离针对草稿连接检查和目录选择。已保存服务器的其他读写、下载及归档不是全部迁移至独立工作进程。服务器可能禁止枚举共享,此时仍可填写已知完整共享路径。 + + +验证完成: + +```powershell +node --test --test-concurrency=2 tests/storage-browse.test.cjs tests/storage-http.test.cjs tests/storage-picker-ui.test.cjs tests/storage-ui.test.cjs tests/storage-preview-ui.test.cjs +# 12 / 12 +node --test --test-concurrency=2 tests/storage-browse.test.cjs tests/storage.test.cjs tests/storage-http.test.cjs tests/storage-preview-http.test.cjs +# 较早一轮16 / 16;其中 Store 7项、preview HTTP 2项与最终轮不重复 +node --test --test-timeout=200000 output/verify-smb-browser.cjs +# 实际 SMB 1 / 1 +``` + +最终涉及22项独立测试全部通过,未运行全量测试集。现场临时共享目录已清理。独立审查指出并修复枚举输出缓冲不足及进程清理未观察退出两个问题,对应回归先失败后通过。截图见 `output/verification/storage-server-shares.png` 与 `storage-browser-success.png`。语法和差异空白检查通过。 diff --git a/scripts/smb-native.ps1 b/scripts/smb-native.ps1 index 34693a8..3318373 100644 --- a/scripts/smb-native.ps1 +++ b/scripts/smb-native.ps1 @@ -7,6 +7,27 @@ try { using System; using System.Runtime.InteropServices; public static class OrderSmbNative { + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + public struct SHARE_INFO_1 { public string name; public uint type; public string remark; } + [DllImport("Netapi32.dll", CharSet = CharSet.Unicode)] + public static extern int NetShareEnum(string server, int level, out IntPtr buffer, int length, out int read, out int total, ref int resume); + [DllImport("Netapi32.dll")] public static extern int NetApiBufferFree(IntPtr buffer); + public static string[] ListShares(string server) { + var names = new System.Collections.Generic.List(); int resume = 0, code; + do { + IntPtr buffer; int read, total; + code = NetShareEnum(server, 1, out buffer, 16384, out read, out total, ref resume); + try { + if (code != 0 && code != 234) throw new System.ComponentModel.Win32Exception(code); + int stride = Marshal.SizeOf(typeof(SHARE_INFO_1)); + for (int i = 0; i < read && names.Count < 501; i++) { + var item = (SHARE_INFO_1)Marshal.PtrToStructure(IntPtr.Add(buffer, i * stride), typeof(SHARE_INFO_1)); + if ((item.type & 255) == 0 && !item.name.EndsWith("$")) names.Add(item.name); + } + } finally { if (buffer != IntPtr.Zero) NetApiBufferFree(buffer); } + } while (code == 234 && names.Count < 501); + return names.ToArray(); + } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct NETRESOURCE { public int scope, type, displayType, usage; @@ -18,7 +39,18 @@ public static class OrderSmbNative { public static extern bool MoveFileExW(string existingName, string newName, int flags); } '@ - if ($orderSmbRequest.operation -eq 'connect') { + if ($orderSmbRequest.operation -eq 'shares') { + if ($orderSmbRequest.authMode -eq 'credentials') { + $orderSmbResource = New-Object OrderSmbNative+NETRESOURCE + $orderSmbResource.type = 0 + $orderSmbResource.remoteName = '\\' + $orderSmbRequest.host + '\IPC$' + $orderSmbCode = [OrderSmbNative]::WNetAddConnection2W([ref]$orderSmbResource, $orderSmbRequest.password, $orderSmbRequest.username, 4) + if ($orderSmbCode -ne 0) { @{ok=$false;code=$orderSmbCode} | ConvertTo-Json -Compress; exit } + } + $orderSmbNames = @([OrderSmbNative]::ListShares('\\' + $orderSmbRequest.host)) + @{ok=$true;code=0;shares=$orderSmbNames} | ConvertTo-Json -Compress -Depth 4 + exit + } elseif ($orderSmbRequest.operation -eq 'connect') { $orderSmbResource = New-Object OrderSmbNative+NETRESOURCE $orderSmbResource.type = 1 $orderSmbResource.remoteName = $orderSmbRequest.remote @@ -29,5 +61,8 @@ public static class OrderSmbNative { } else { throw 'Unsupported operation' } @{ ok = ($orderSmbCode -eq 0); code = $orderSmbCode } | ConvertTo-Json -Compress } catch { - @{ ok = $false; code = -1 } | ConvertTo-Json -Compress + $orderSmbCause = $_.Exception + while ($orderSmbCause.InnerException) { $orderSmbCause = $orderSmbCause.InnerException } + $orderSmbErrorCode = if ($orderSmbCause -is [ComponentModel.Win32Exception]) { $orderSmbCause.NativeErrorCode } else { -1 } + @{ ok = $false; code = $orderSmbErrorCode } | ConvertTo-Json -Compress } diff --git a/src/smb-native.cjs b/src/smb-native.cjs index f83fdcb..4f0a823 100644 --- a/src/smb-native.cjs +++ b/src/smb-native.cjs @@ -6,9 +6,9 @@ const path=require('node:path'); const messages={5:'存储服务器拒绝访问,请检查账号权限。',53:'找不到存储服务器,请检查地址与网络。',67:'找不到共享目录,请检查共享名称。',86:'SMB 账号或密码不正确。',1326:'SMB 账号或密码不正确。',1219:'此服务器已使用其他账号连接,请先由管理员处理 Windows SMB 凭据冲突。',183:'目标文件已存在。',80:'目标文件已存在。'}; function native(operation,input){ return new Promise((resolve,reject)=>{ - const child=execFile('powershell.exe',['-NoLogo','-NoProfile','-NonInteractive','-ExecutionPolicy','Bypass','-File',path.resolve(__dirname,'../scripts/smb-native.ps1')],{windowsHide:true,timeout:25000,maxBuffer:16384,encoding:'utf8'},(error,stdout)=>{ + const child=execFile('powershell.exe',['-NoLogo','-NoProfile','-NonInteractive','-ExecutionPolicy','Bypass','-File',path.resolve(__dirname,'../scripts/smb-native.ps1')],{windowsHide:true,timeout:25000,maxBuffer:operation==='shares'?384*1024:16384,encoding:'utf8'},(error,stdout)=>{ let result;try{result=JSON.parse(stdout.replace(/^\uFEFF/,''));}catch{} - if(result?.ok)return resolve(); + if(result?.ok)return resolve(result); const code=result?.code;const failure=Object.assign(new Error(messages[code]||'SMB 操作未完成,请检查网络、共享权限或服务器状态。'),{status:502}); if([80,183].includes(code))failure.code='EEXIST'; if(error?.killed)failure.message='SMB 操作超时,请检查服务器和网络。'; @@ -21,8 +21,12 @@ async function connect(server){ if(process.platform!=='win32')throw Object.assign(new Error('SMB 连接需要在 Windows 部署机运行。'),{status:503}); await native('connect',{remote:`\\\\${server.host}\\${server.share}`,username:server.username,password:server.password}); } +async function listShares(server){ + if(process.platform!=='win32')throw Object.assign(new Error('SMB 浏览需要在 Windows 部署机运行。'),{status:503}); + const result=await native('shares',{host:server.host,authMode:server.authMode,username:server.username,password:server.password});return result.shares||[]; +} async function publishExclusive(source,target){ if(process.platform==='win32')return native('publish',{source,target}); await fs.link(source,target);await fs.unlink(source); } -module.exports={connect,publishExclusive}; +module.exports={connect,listShares,publishExclusive}; diff --git a/src/smb-probe-worker.cjs b/src/smb-probe-worker.cjs new file mode 100644 index 0000000..f27c224 --- /dev/null +++ b/src/smb-probe-worker.cjs @@ -0,0 +1,20 @@ +'use strict'; +const {SmbClient,segments}=require('./storage-files.cjs'); +const native=require('./smb-native.cjs'); +let input='';process.stdin.setEncoding('utf8');process.stdin.on('data',chunk=>{input+=chunk;if(input.length>32768)process.exit(1);}); +process.stdin.on('end',async()=>{ + try{ + const server=JSON.parse(input),slash=String.fromCharCode(92),root=slash.repeat(2)+server.host; + let value; + if(!server.share){const names=await native.listShares(server);const entries=[]; + for(const name of names){try{if(segments(name).length===1)entries.push({name,type:'directory',address:root+slash+name});}catch{}} + value={serverRoot:true,readable:false,address:root,parent:null,entries:entries.slice(0,500),truncated:entries.length>500}; + }else{ + const area=await new SmbClient().area(server),listing=await area.list(''),parts=[server.share,...segments(server.directory)],address=root+slash+parts.join(slash); + value={serverRoot:false,readable:true,address,parent:parts.length===1?root:root+slash+parts.slice(0,-1).join(slash),entries:listing.entries.filter(entry=>entry.type==='directory').map(entry=>({...entry,address:address+slash+entry.name})),truncated:listing.truncated}; + } + process.stdout.write(JSON.stringify({ok:true,value})); + }catch(error){const messages={ENOENT:'找不到目标目录,请检查共享路径。',EACCES:'没有共享目录读取权限,请检查账号。',EPERM:'没有共享目录读取权限,请检查账号。',ENOTDIR:'目标路径不是目录。'}; + process.stdout.write(JSON.stringify({ok:false,status:error.status||502,error:error.status?error.message:messages[error.code]||'读取共享目录失败,请检查服务器、网络与访问权限。'})); + } +}); diff --git a/src/smb-probe.cjs b/src/smb-probe.cjs new file mode 100644 index 0000000..dcdd625 --- /dev/null +++ b/src/smb-probe.cjs @@ -0,0 +1,36 @@ +'use strict'; +const {spawn}=require('node:child_process'); +const path=require('node:path'); +const fail=(message,status)=>Object.assign(new Error(message),{status}); + +// UNC calls can wait inside Windows. Run draft reads outside the web process so +// cancellation also releases blocked filesystem calls, not just the HTTP wait. +function probe(server,{signal,timeoutMs=15000}={}){ + return new Promise((resolve,reject)=>{ + if(signal?.aborted)return reject(signal.reason?.status?signal.reason:fail('已取消连接操作。',499)); + const child=spawn(process.execPath,[path.join(__dirname,'smb-probe-worker.cjs')],{windowsHide:true,stdio:['pipe','pipe','pipe']}); + let settled=false,terminating=null,cleanupTimer=null,output='',size=0; + const finish=(error,result)=>{if(settled)return;settled=true;clearTimeout(timer);clearTimeout(cleanupTimer);signal?.removeEventListener('abort',cancel);error?reject(error):resolve(result);}; + const terminate=error=>{ + if(settled||terminating)return;terminating=error;clearTimeout(timer); + // Resolve cancellation after the worker closes, with a bounded final fallback. + cleanupTimer=setTimeout(()=>{child.kill('SIGKILL');finish(error);},1500); + if(!child.pid){finish(error);return;} + if(process.platform==='win32'){ + const killer=spawn('taskkill.exe',['/PID',String(child.pid),'/T','/F'],{windowsHide:true,stdio:'ignore'}); + killer.on('error',()=>child.kill());killer.once('exit',code=>{if(code!==0&&!settled)child.kill();}); + }else child.kill('SIGKILL'); + }; + const cancel=()=>terminate(signal.reason?.status?signal.reason:fail('已取消连接操作。',499)); + const timer=setTimeout(()=>terminate(fail('连接超时,请检查服务器地址、网络及共享权限后重试。',504)),timeoutMs); + signal?.addEventListener('abort',cancel,{once:true}); + child.stdin.on('error',()=>{});child.stderr.resume(); + child.on('error',()=>finish(fail('无法启动 SMB 连接检查。',503))); + child.stdout.setEncoding('utf8');child.stdout.on('data',chunk=>{size+=Buffer.byteLength(chunk);if(size>512*1024){terminate(fail('服务器返回的目录内容过多,请缩小浏览范围。',413));}else output+=chunk;}); + child.once('close',()=>{if(settled)return;if(terminating){finish(terminating);return;}let result;try{result=JSON.parse(output);}catch{} + if(result?.ok)finish(null,result.value);else finish(fail(result?.error||'连接检查失败,请检查服务器与共享权限。',result?.status||502)); + }); + child.stdin.end(JSON.stringify(server)); + }); +} +module.exports={probe}; diff --git a/src/storage-api.cjs b/src/storage-api.cjs index ff27eed..b0b691e 100644 --- a/src/storage-api.cjs +++ b/src/storage-api.cjs @@ -7,10 +7,13 @@ 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'||route==='/api/storage/servers/check')&&method==='POST'){ + if((route==='/api/storage/servers'||route==='/api/storage/servers/check'||route==='/api/storage/servers/browse')&&method==='POST'){ if(user.role!=='admin')fail('仅管理员可以维护存储服务器。',403); if(!secureBpmTransport(request,trustedProxy))fail('请在部署机本地或 HTTPS 页面维护存储账号。',403); - if(route.endsWith('/check')){reply(200,await storage.checkConnection(body));return true;} + if(route.endsWith('/check')||route.endsWith('/browse')){ + const controller=new AbortController(),abort=()=>{if(!response.writableEnded)controller.abort();};response.once('close',abort); + try{reply(200,await storage[route.endsWith('/browse')?'browseConnection':'checkConnection'](body,{signal:controller.signal}));}finally{response.removeListener('close',abort);}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;} diff --git a/src/storage-files.cjs b/src/storage-files.cjs index fc063a8..2e4e4e1 100644 --- a/src/storage-files.cjs +++ b/src/storage-files.cjs @@ -74,6 +74,7 @@ class FileArea{ } } class SmbClient{ + async browse(server,options){return require('./smb-probe.cjs').probe(server,options);} async area(server){if(server.authMode!=='windows')await native.connect(server);const boundary=path.win32.join('\\\\'+server.host,server.share),root=path.win32.join(boundary,...segments(server.directory));return new FileArea(root,{boundary});} } module.exports={FileArea,SmbClient,segments,inside,MAX_FILE}; diff --git a/src/storage-service.cjs b/src/storage-service.cjs index c4e66b7..af5f9b3 100644 --- a/src/storage-service.cjs +++ b/src/storage-service.cjs @@ -4,7 +4,7 @@ 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.pendingChecks=new Set();this.stopped=false;} + constructor({store,jobs,outputDir,client=new SmbClient(),checkTimeoutMs=15000}){this.store=store;this.jobs=jobs;this.outputDir=outputDir;this.client=client;this.running=new Map();this.pendingChecks=new Set();this.probeControllers=new Set();this.checkTimeoutMs=checkTimeoutMs;this.stopped=false;} busy(id){return this.running.has(id);} async saveServer(input){ if(this.stopped)throw fail('存储服务正在停止。',503); @@ -15,11 +15,29 @@ class StorageService{ if(snapshot.id&&this.busy(snapshot.id))throw fail('此服务器正在执行操作,请稍后保存。',409); return this.store.saveServer(snapshot,readState); } - async checkConnection(input){ + async probe(saved,{signal}={}){ 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);} + const controller=new AbortController();const cancel=()=>controller.abort(signal.reason?.status?signal.reason:fail('已取消连接操作。',499)); + if(signal?.aborted)cancel();else signal?.addEventListener('abort',cancel,{once:true}); + const timer=setTimeout(()=>controller.abort(fail('连接超时,请检查服务器地址、网络及共享权限后重试。',504)),this.checkTimeoutMs); + const task=(async()=>{let onAbort,work; + try{return await Promise.race([ + new Promise((resolve,reject)=>{onAbort=()=>reject(controller.signal.reason);if(controller.signal.aborted)onAbort();else controller.signal.addEventListener('abort',onAbort,{once:true});}), + work=(async()=>{if(controller.signal.aborted)throw controller.signal.reason; + if(this.client.browse)return await this.client.browse(saved,{signal:controller.signal}); + const area=await this.client.area(saved),listing=await area.list('');return {serverRoot:false,readable:true,entries:listing.entries.filter(e=>e.type==='directory'),truncated:listing.truncated}; + })() + ]);}catch(error){throw safe(error);}finally{if(controller.signal.aborted&&this.client.browse&&work){let cleanup;await Promise.race([work.catch(()=>{}),new Promise(resolve=>{cleanup=setTimeout(resolve,1800);})]);clearTimeout(cleanup);}clearTimeout(timer);signal?.removeEventListener('abort',cancel);if(onAbort)controller.signal.removeEventListener('abort',onAbort);this.probeControllers.delete(controller);} + })(); + this.pendingChecks.add(task);this.probeControllers.add(controller);try{return await task;}finally{this.pendingChecks.delete(task);this.probeControllers.delete(controller);} + } + async browseConnection(input,options){ + const {saved}=this.store.prepareServer(input,{allowServerRoot:true});return this.probe(saved,options); + } + async checkConnection(input,options){ + const {saved}=this.store.prepareServer(input,{allowServerRoot:true});const result=await this.probe(saved,options); + if(!saved.share)return {...result,readable:false,serverRoot:true,message:'已连接服务器,请浏览并选择一个共享目录。'}; + return {...result,readable:true,checkedAt:new Date().toISOString(),message:'连接成功,目标目录可读取。'}; } 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){ @@ -45,6 +63,6 @@ class StorageService{ }); } async automatic(job){const settings=this.store.settings();if(!settings.enabled||job.status!=='success'||!job.createdAt||job.createdAtthis.publicServer(r.id));} - prepareServer(input){ + prepareServer(input,{allowServerRoot=false}={}){ 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); @@ -30,13 +30,14 @@ class StorageStore{ if(input.address!==undefined){ const separator=String.fromCharCode(92);let address=text(input.address,'共享路径',1800); while(address.endsWith(separator))address=address.slice(0,-1); + if(allowServerRoot&&!address.includes(separator)&&!address.includes('/'))address=separator.repeat(2)+address; if(!address.startsWith(separator.repeat(2)))fail('请粘贴完整的 Windows 共享路径,需包含服务器和共享名称。'); const parts=address.slice(2).split(separator);hostInput=parts.shift(); - const directories=segments(parts.join('/'));if(!directories.length)fail('共享路径需要包含共享名称。'); - shareInput=directories[0];directoryInput=directories.slice(1).join('/'); + const directories=segments(parts.join('/'));if(!directories.length&&!allowServerRoot)fail('请先浏览服务器并选择一个共享目录。'); + shareInput=directories[0]||'';directoryInput=directories.slice(1).join('/'); } const host=text(hostInput,'服务器地址',253).toLowerCase();if(!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(host)||host.includes('..'))fail('服务器地址只填写主机名或 IPv4 地址。'); - const share=text(shareInput,'共享名称',80);if(segments(share).length!==1)fail('共享名称不能包含路径。'); + const share=allowServerRoot&&shareInput===''?'':text(shareInput,'共享名称',80);if(share&&segments(share).length!==1)fail('共享名称不能包含路径。'); const directory=segments(directoryInput).join('/'),authMode=input.authMode??old?.authMode??'credentials'; if(!['windows','credentials'].includes(authMode))fail('请选择有效的访问方式。'); if(input.passwordless!==undefined&&typeof input.passwordless!=='boolean')fail('请选择账号是否无密码。'); @@ -44,7 +45,7 @@ class StorageStore{ if(authMode==='credentials'){ username=text(input.username,'登录账号',200);passwordless=input.passwordless??old?.passwordless??false; if(!passwordless){ - const changedIdentity=old&&(host!==old.host||share!==old.share||username!==old.username||old.authMode!=='credentials'); + const changedIdentity=old&&(host!==old.host||(!allowServerRoot&&share!==old.share)||username!==old.username||old.authMode!=='credentials'); if(changedIdentity&&input.password==='')fail('更换服务器、共享或登录账号时,请重新填写密码。'); password=input.password===''&&old&&!changedIdentity?old.password:input.password; if(typeof password!=='string'||!password||password.length>2048)fail('请输入 SMB 登录密码,或勾选此账号无密码。'); diff --git a/tests/storage-browse.test.cjs b/tests/storage-browse.test.cjs new file mode 100644 index 0000000..aef825f --- /dev/null +++ b/tests/storage-browse.test.cjs @@ -0,0 +1,29 @@ +const {test}=require('node:test'),assert=require('node:assert/strict'); +const {StorageService}=require('../src/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/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/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); +}); diff --git a/tests/storage-http.test.cjs b/tests/storage-http.test.cjs index b39b79f..364f968 100644 --- a/tests/storage-http.test.cjs +++ b/tests/storage-http.test.cjs @@ -2,7 +2,7 @@ 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/dashboard-store.cjs');const {StorageStore}=require('../src/storage-store.cjs');const {StorageService}=require('../src/storage-service.cjs');const {FileArea}=require('../src/storage-files.cjs');const {createDashboard}=require('../src/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)}});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};} +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); @@ -50,3 +50,11 @@ test('draft connection check does not save, and unreadable storage cannot be add 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); +}); diff --git a/tests/storage-picker-ui.test.cjs b/tests/storage-picker-ui.test.cjs new file mode 100644 index 0000000..724c99a --- /dev/null +++ b/tests/storage-picker-ui.test.cjs @@ -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/dashboard-store.cjs'),{StorageStore}=require('../src/storage-store.cjs'),{StorageService}=require('../src/storage-service.cjs'),{FileArea,segments}=require('../src/storage-files.cjs'),{createDashboard}=require('../src/dashboard.cjs'),{loadPlaywright,browserOptions}=require('../src/runtime.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}); +}); diff --git a/web/storage.js b/web/storage.js index 3733d9a..8f0a597 100644 --- a/web/storage.js +++ b/web/storage.js @@ -12,36 +12,58 @@ const slash=String.fromCharCode(92),address=s.id?slash.repeat(2)+s.host+slash+s.share+(s.directory?slash+s.directory.split('/').join(slash):''):''; const host=container.querySelector('#storage-editor'),mode=s.authMode||'credentials'; host.innerHTML=`

${s.id?'管理服务器':'添加服务器'}

-
从文件资源管理器复制完整共享路径即可。
+
可先输入服务器 IP / 主机名,点击浏览选择共享及目录;也可粘贴完整共享路径。
免填模式复用部署机已有 Windows 共享登录或服务账号权限,也适用于系统允许的免密共享。切换方式不会断开系统已有连接。
${s.id&&s.hasPassword?'留空保留现有密码;更换服务器、共享或账号时重新填写。':'密码加密保存在部署机。'}
-
${s.id?'修改连接信息后需重新检查。':'请先检查连接,确认目录可读取后再保存。'}
`; +
${s.id?'修改连接信息后需重新检查。':'请先检查连接,确认目录可读取后再保存。'}
`; 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(); - 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 form=host.querySelector('form'),checkButton=host.querySelector('#storage-connection-check'),browseButton=host.querySelector('#storage-directory-browse'),cancelButton=host.querySelector('#storage-operation-cancel'),picker=host.querySelector('#storage-directory-picker'),saveButton=form.querySelector('[type="submit"]'),status=host.querySelector('#storage-connection-status'),errorBox=host.querySelector('#storage-error'),addressInput=host.querySelector('#storage-address'); + let verified=!!s.id,checking=false,saving=false,revision=0,operation=null; const alive=()=>isActive()&&form.isConnected; - const update=()=>{saveButton.disabled=!verified||checking||saving;checkButton.disabled=checking||saving;}; + const update=()=>{saveButton.disabled=!verified||checking||saving;checkButton.disabled=checking||saving;browseButton.disabled=checking||saving;cancelButton.hidden=!checking;}; 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}; + const input={...(s.id?{id:s.id,version:s.version}:{}),address:addressInput.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});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();} + async function request(route,input,signal,timeout=18000){ + const controller=new AbortController(),cancel=()=>controller.abort(signal.reason);let timedOut=false; + if(signal?.aborted)cancel();else signal?.addEventListener('abort',cancel,{once:true}); + const timer=setTimeout(()=>{timedOut=true;controller.abort();},timeout); + try{const response=await fetch('/api/storage/servers'+route,{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify(input),signal:controller.signal});const body=await response.json();if(!response.ok)throw new Error(body.error||'存储操作失败。');return body;} + catch(error){if(timedOut)throw new Error(route===''?'保存响应超时,请刷新列表确认保存结果。':'连接超时,请检查网络后重试。');throw error;} + finally{clearTimeout(timer);signal?.removeEventListener('abort',cancel);} + } + function cancelOperation(){const current=operation;operation=null;revision++;checking=false;verified=false;current?.abort();if(alive()){status.textContent='已取消连接操作,可修改后重试。';update();}} + cancelButton.onclick=cancelOperation; + 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; + if(operation)cancelOperation();revision++;verified=false;errorBox.textContent='';picker.hidden=true;status.textContent='连接信息已变更,请重新检查。';update(); + } form.addEventListener('input',invalidate);form.addEventListener('change',invalidate); - checkButton.onclick=async()=>{ + function showDirectories(result){ + picker.hidden=false;picker.innerHTML=`
${esc(result.address||addressInput.value)}${result.parent?'':''}${result.readable?'':''}
${(result.entries||[]).map((entry,index)=>``).join('')||'
没有可列出的子目录。
'}
${result.serverRoot?'
点击一个共享继续浏览;若服务器禁止列举共享,可直接填写完整共享路径。
':''}${result.truncated?'
仅显示前 500 项。
':''}
`; + picker.querySelectorAll('[data-picker-entry]').forEach(button=>button.onclick=()=>navigate(result.entries[Number(button.dataset.pickerEntry)].address)); + const up=picker.querySelector('[data-picker-up]');if(up)up.onclick=()=>navigate(result.parent); + const select=picker.querySelector('[data-picker-select]');if(select)select.onclick=()=>{addressInput.value=result.address;revision++;verified=true;picker.hidden=true;status.textContent='连接成功,目标目录可读取。';update();}; + } + function navigate(address){addressInput.value=address;revision++;verified=false;return runConnection(true);} + async function runConnection(browse){ 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(); + const at=revision,controller=new AbortController();operation=controller;verified=false;checking=true;errorBox.textContent='';status.textContent=browse?'正在浏览共享目录…':'正在检查连接…';picker.hidden=true;update(); + try{const result=await request(browse?'/browse':'/check',details(),controller.signal); + if(alive()&&operation===controller&&at===revision){if(result.address)addressInput.value=result.address;verified=result.readable===true;status.textContent=result.message||(result.serverRoot?'请选择一个共享目录。':'连接成功,目标目录可读取。');if(browse||result.serverRoot)showDirectories(result);} + }catch(error){if(alive()&&operation===controller&&at===revision){errorBox.textContent=error.message;status.textContent='连接操作未完成,尚未保存。';}} + finally{if(operation===controller){operation=null;checking=false;if(alive())update();}} + } + checkButton.onclick=()=>runConnection(false);browseButton.onclick=()=>runConnection(true); + const observer=new MutationObserver(()=>{if(!form.isConnected){cancelOperation();observer.disconnect();}});observer.observe(container,{childList:true,subtree:true}); + host.querySelector('#storage-cancel').onclick=()=>{cancelOperation();observer.disconnect();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);}} + e.preventDefault();if(saving||checking)return;if(!verified){errorBox.textContent='请先检查连接或浏览选择可读取目录。';return;} + const input=details();saving=true;errorBox.textContent='';status.textContent='正在确认目录并保存…';picker.hidden=true;form.querySelectorAll('input,select,button').forEach(node=>node.disabled=true); + try{await request('',input,undefined,45000);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'});