Files
order-notification-automation/src/modules/storage/smb-operation.cjs
T

64 lines
5.2 KiB
JavaScript

'use strict';
const {fork,spawn}=require('node:child_process');
const path=require('node:path');
const MAX_FILE=64*1024*1024,MAX_META=512*1024;
const operations=new Set(['check','list','mkdir','readPdf','previewInfo','readPreview','readFile','archive']);
const fail=(message,status)=>Object.assign(new Error(message),{status});
function validate(operation,value){
let binary=0,metadata=0,nodes=0;
function visit(v,depth=0){
if(++nodes>10000||depth>20)throw fail('存储响应无效。',502);
if(Buffer.isBuffer(v)){binary+=v.length;if(binary>MAX_FILE)throw fail('文件超过工作台读取上限。',413);return;}
if(v===null||typeof v==='boolean'||typeof v==='number'){if(typeof v==='number'&&!Number.isFinite(v))throw fail('存储响应无效。',502);return;}
if(typeof v==='string'){metadata+=Buffer.byteLength(v);if(metadata>MAX_META)throw fail('存储响应内容过多。',413);return;}
if(typeof v!=='object'||Object.getPrototypeOf(v)!==Object.prototype&&!Array.isArray(v))throw fail('存储响应无效。',502);
for(const [key,item] of Object.entries(v)){metadata+=Buffer.byteLength(key);if(metadata>MAX_META)throw fail('存储响应内容过多。',413);visit(item,depth+1);}
}
visit(value);
if(!value||typeof value!=='object'||Array.isArray(value))throw fail('存储响应无效。',502);
if(['readPdf','readPreview','readFile'].includes(operation)&&!Buffer.isBuffer(value.bytes))throw fail('存储文件响应无效。',502);
if(['readPreview','readFile'].includes(operation)&&value.total!==undefined){
const {total,start,end,status,bytes}=value,valid=Number.isSafeInteger(total)&&total>=0&&total<=MAX_FILE&&Number.isSafeInteger(start)&&Number.isSafeInteger(end);
const layout=status===416?start===0&&end===-1&&bytes.length===0:
status===200?start===0&&end===total-1&&bytes.length===total:
status===206&&total>0&&start>=0&&start<=end&&end<total&&bytes.length===end-start+1;
if(!valid||!layout)throw fail('存储分段响应无效。',502);
}
if(operation==='list'&&(!Array.isArray(value.entries)||value.entries.length>500||typeof value.path!=='string'||typeof value.truncated!=='boolean'||value.entries.some(e=>!e||typeof e.name!=='string'||!['directory','file','blocked'].includes(e.type))))throw fail('存储目录响应无效。',502);
if(operation==='check'&&(value.readable!==true||value.writable!==true))throw fail('存储检查响应无效。',502);
if(operation==='archive'&&(!Number.isSafeInteger(value.bytes)||value.bytes<0||value.bytes>MAX_FILE||!/^[a-f0-9]{64}$/.test(value.sha256)||typeof value.filename!=='string'||typeof value.relativePath!=='string'))throw fail('归档响应无效。',502);
return value;
}
function execute(server,operation,args=[],{signal,timeoutMs=15000,deadline,workerPath=path.join(__dirname,'smb-operation-worker.cjs')}={}){
if(!operations.has(operation))return Promise.reject(fail('存储操作无效。',400));
if(signal?.aborted)return Promise.reject(signal.reason?.status?signal.reason:fail('已取消存储操作。',499));
const remaining=deadline===undefined?timeoutMs:Math.min(timeoutMs,deadline-Date.now());
if(!Number.isFinite(remaining)||remaining<=0)return Promise.reject(fail('存储操作超时。',504));
return new Promise((resolve,reject)=>{
// Credentials travel only on the private IPC channel, never argv/stdout/stderr.
const child=fork(workerPath,[],{windowsHide:true,serialization:'advanced',detached:process.platform!=='win32',stdio:['ignore','ignore','ignore','ipc']});
let response,error,received=false,closed=false,terminating=false;
const kill=()=>{if(closed)return;if(process.platform==='win32'){
const killer=spawn('taskkill.exe',['/PID',String(child.pid),'/T','/F'],{windowsHide:true,stdio:'ignore',timeout:1500});
killer.once('error',()=>child.kill('SIGKILL'));killer.once('exit',code=>{if(code!==0&&!closed)child.kill('SIGKILL');});
}else{try{process.kill(-child.pid,'SIGKILL');}catch{child.kill('SIGKILL');}}};
const terminate=e=>{if(terminating)return;terminating=true;error ||= e;kill();};
const cancel=()=>terminate(signal.reason?.status?signal.reason:fail('已取消存储操作。',499));
const timer=setTimeout(()=>terminate(fail('存储操作超时,请检查服务器与网络。',504)),remaining);
signal?.addEventListener('abort',cancel,{once:true});
child.on('message',message=>{
if(error)return;
if(received)return terminate(fail('存储响应无效。',502));received=true;
try{if(!message||typeof message.ok!=='boolean')throw fail('存储响应无效。',502);
if(message.ok)response=validate(operation,message.value);
else error=fail('存储操作未完成,请检查路径、权限或服务器状态。',[400,403,404,409,413,415,499,502,503,504].includes(message.status)?message.status:502);
}catch(e){terminate(e);}
});
child.on('error',()=>{error ||= fail('无法启动存储工作进程。',503);});
child.once('close',(code)=>{closed=true;clearTimeout(timer);signal?.removeEventListener('abort',cancel);if(error)reject(error);else if(code!==0||!received)reject(fail('存储工作进程未正常完成。',502));else resolve(response);});
child.send({server,operation,args},e=>{if(e)terminate(fail('无法发送存储操作。',503));});
if(signal?.aborted)cancel();
});
}
module.exports={execute,validate};