feat(storage): browse SMB shares and bound connection checks

This commit is contained in:
阿白叔 committed 2026-10-17 17:47:22 +08:00
1 parent 8417b1dff8
commit a785fa73d4
15 files changed
+277 -39

No files matched your search

+7 -3
View File
@@ -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};
+20
View File
@@ -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]||'读取共享目录失败,请检查服务器、网络与访问权限。'}));
}
});
+36
View File
@@ -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};
+5 -2
View File
@@ -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;}
+1
View File
@@ -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};
+24 -6
View File
@@ -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.createdAt<settings.since)return null;return this.archive(settings.serverId,job.jobId,'','自动归档');}
async stop(){this.stopped=true;await Promise.allSettled([...this.running.values(),...this.pendingChecks]);}
async stop(){this.stopped=true;for(const controller of this.probeControllers)controller.abort(fail('存储服务正在停止。',503));await Promise.allSettled([...this.running.values(),...this.pendingChecks]);}
}
module.exports={StorageService};
+6 -5
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));}
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 登录密码,或勾选此账号无密码。');