110 lines
9.2 KiB
JavaScript
110 lines
9.2 KiB
JavaScript
'use strict';
|
|
const fs=require('node:fs/promises');
|
|
const path=require('node:path');
|
|
const crypto=require('node:crypto');
|
|
const native=require('./smb-native.cjs');
|
|
const {describePreview,validatePreview}=require('./preview.cjs');
|
|
const MAX_FILE=64*1024*1024;
|
|
const fail=(message,status=400)=>Object.assign(new Error(message),{status});
|
|
function segments(relative=''){
|
|
if(typeof relative!=='string'||relative.length>1500||/^[\\/]|[<>:"|?*\x00-\x1f]/.test(relative))throw fail('请使用归档目录内的相对路径。');
|
|
if(!relative)return [];
|
|
const parts=relative.replace(/\\/g,'/').split('/');
|
|
if(parts.some(p=>!p||p==='.'||p==='..'||/[. ]$/.test(p)||/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(p)||p.length>200))throw fail('目录或文件名无效,不能跳转到归档根目录之外。');
|
|
return parts;
|
|
}
|
|
function inside(root,file){const rel=path.relative(root,file);return !path.isAbsolute(rel)&&rel!=='..'&&!rel.startsWith('..'+path.sep);}
|
|
function digest(bytes){return crypto.createHash('sha256').update(bytes).digest('hex');}
|
|
function byteRange(value,total){
|
|
if(!Number.isSafeInteger(total)||total<0)throw fail('存储文件大小无效。',502);
|
|
const invalid={status:416,start:0,end:-1};
|
|
if(value===undefined)return {status:200,start:0,end:total-1};
|
|
const match=typeof value==='string'&&/^bytes=(\d*)-(\d*)$/.exec(value);if(!match||!total||(!match[1]&&!match[2]))return invalid;
|
|
const first=match[1]?Number(match[1]):null,last=match[2]?Number(match[2]):null;
|
|
if(first!==null&&!Number.isSafeInteger(first)||last!==null&&!Number.isSafeInteger(last))return invalid;
|
|
const start=first===null?Math.max(0,total-last):first,end=first===null||last===null?total-1:Math.min(last,total-1);
|
|
return start<0||start>end||start>=total?invalid:{status:206,start,end};
|
|
}
|
|
async function readExact(handle,start,length){
|
|
const buffer=Buffer.alloc(length);let offset=0;
|
|
while(offset<length){const result=await handle.read(buffer,offset,length-offset,start+offset);if(!result.bytesRead)throw fail('文件正在更新,请稍后重试。',409);offset+=result.bytesRead;}
|
|
return buffer;
|
|
}
|
|
const unchanged=(a,b)=>['dev','ino','size','mtimeNs','ctimeNs'].every(key=>a[key]===b[key]);
|
|
async function pdf(file){const info=await fs.stat(file);if(!info.isFile()||info.size>MAX_FILE)throw fail('PDF 必须为不超过 64 MiB 的文件。');const bytes=await fs.readFile(file);if(bytes.length>MAX_FILE||bytes.subarray(0,5).toString()!=='%PDF-')throw fail('文件不是有效的 PDF。');return bytes;}
|
|
class FileArea{
|
|
constructor(root,{boundary=root}={}){this.root=path.resolve(root);this.boundary=path.resolve(boundary);if(!inside(this.boundary,this.root))throw fail('归档根目录超出共享目录。');}
|
|
async resolve(relative='',create=false){
|
|
const prefix=segments(path.relative(this.boundary,this.root)),parts=[...prefix,...segments(relative)];let current=this.boundary;
|
|
const rootInfo=await fs.lstat(current);if(rootInfo.isSymbolicLink()||!rootInfo.isDirectory())throw fail('归档根目录不可用或为目录链接。');
|
|
const realRoot=await fs.realpath(current);
|
|
for(const [index,part]of parts.entries()){
|
|
current=path.join(current,part);
|
|
if(create&&index>=prefix.length)try{await fs.mkdir(current);}catch(e){if(e.code!=='EEXIST')throw e;}
|
|
const info=await fs.lstat(current);if(info.isSymbolicLink())throw fail('不能访问目录链接。');
|
|
if(!inside(realRoot,await fs.realpath(current)))throw fail('路径超出归档根目录。');
|
|
}
|
|
return current;
|
|
}
|
|
async list(relative='',options={}){
|
|
const directory=await this.resolve(relative),entries=[];let truncated=false;
|
|
const prefix=typeof options?.prefix==='string'&&options.prefix?options.prefix.toLowerCase():'';
|
|
const iterator=await fs.opendir(directory);
|
|
for await(const entry of iterator){if(entry.name.startsWith('.order-'))continue;if(prefix&&!entry.name.toLowerCase().startsWith(prefix))continue;if(entries.length>=500){truncated=true;break;}entries.push({name:entry.name,type:entry.isSymbolicLink()?'blocked':entry.isDirectory()?'directory':'file'});}
|
|
entries.sort((a,b)=>(a.type==='directory'?0:1)-(b.type==='directory'?0:1)||a.name.localeCompare(b.name,'zh-CN'));
|
|
return {path:segments(relative).join('/'),entries,truncated};
|
|
}
|
|
async mkdir(relative){if(!segments(relative).length)throw fail('请输入要创建的目录名称。');await this.resolve(relative,true);return {path:segments(relative).join('/')};}
|
|
async check(){
|
|
const root=await this.resolve(''),file=path.join(root,'.order-probe-'+crypto.randomUUID()),bytes=crypto.randomBytes(32);let owned=false;
|
|
try{await fs.writeFile(file,bytes,{flag:'wx'});owned=true;if(!(await fs.readFile(file)).equals(bytes))throw fail('共享目录读写校验失败。',502);}finally{if(owned)await fs.unlink(file);}
|
|
return {readable:true,writable:true};
|
|
}
|
|
async readPdf(relative){if(path.extname(relative).toLowerCase()!=='.pdf')throw fail('仅支持下载归档 PDF。');const file=await this.resolve(relative);return {bytes:await pdf(file),filename:path.basename(file)};}
|
|
async previewInfo(relative){const file=await this.resolve(relative),stat=await fs.stat(file);if(!stat.isFile())throw fail('请选择文件进行预览。');return describePreview(path.basename(file),stat.size);}
|
|
async readFile(relative,limit=MAX_FILE,{range,previewPdf=false}={}){
|
|
const file=await this.resolve(relative),handle=await fs.open(file,'r');
|
|
try{const stat=await handle.stat({bigint:true}),total=Number(stat.size),filename=path.basename(file);if(!stat.isFile())throw fail('请选择要读取的文件。');if(!Number.isSafeInteger(total)||total>limit)throw fail('文件超过工作台读取上限。',413);
|
|
if(previewPdf){const info=describePreview(filename,total);if(info.kind!=='pdf')throw fail('此格式不支持 PDF 分段预览。',415);await validatePreview(info,await readExact(handle,0,Math.min(5,total)));}
|
|
const selected=byteRange(range,total),bytes=selected.status===416?Buffer.alloc(0):await readExact(handle,selected.start,selected.end-selected.start+1);
|
|
// Validate both the opened file and its path after reading. Ranges and PDF
|
|
// headers use this same handle, and no successful short/growing read escapes.
|
|
const after=await handle.stat({bigint:true});await this.resolve(relative);const current=await fs.lstat(file,{bigint:true});
|
|
if(current.isSymbolicLink()||!unchanged(stat,after)||!unchanged(stat,current))throw fail('文件正在更新,请稍后重试。',409);
|
|
return {filename,bytes,total,...selected};
|
|
}finally{await handle.close();}
|
|
}
|
|
async readPreview(relative,{range}={}){
|
|
if(range!==undefined&&path.extname(relative).toLowerCase()==='.pdf'){
|
|
const file=await this.readFile(relative,MAX_FILE,{range,previewPdf:true});return {...describePreview(file.filename,file.total),...file};
|
|
}
|
|
const info=await this.previewInfo(relative);if(!info.canPreview)throw fail(info.reason,info.kind==='unsupported'?415:413);
|
|
const file=await this.readFile(relative,info.limit),bytes=await validatePreview({...info,bytes:file.bytes.length,canPreview:file.bytes.length<=info.limit},file.bytes),selected=byteRange(range,bytes.length);
|
|
return {...info,total:bytes.length,...selected,bytes:selected.status===416?Buffer.alloc(0):bytes.subarray(selected.start,selected.end+1)};
|
|
}
|
|
async archive(source,filename,relative=''){
|
|
if(segments(filename).length!==1||path.extname(filename).toLowerCase()!=='.pdf')throw fail('归档文件名必须为 PDF 文件名。');
|
|
const bytes=await pdf(source),sha256=digest(bytes),directory=await this.resolve(relative,true);
|
|
const same=async target=>{try{return digest(await pdf(target))===sha256;}catch(e){if(e.code==='ENOENT')return false;if(e.status===400)return false;throw e;}};
|
|
const candidateNames=[filename,filename.slice(0,-4).slice(0,130)+'_'+sha256+'.pdf'];
|
|
for(const name of candidateNames){
|
|
const target=path.join(directory,name);const result={filename:name,relativePath:[...segments(relative),name].join('/'),bytes:bytes.length,sha256};
|
|
try{const stat=await fs.lstat(target);if(stat.isSymbolicLink())throw fail('目标文件为链接,不能归档。');if(await same(target))return result;continue;}catch(e){if(e.code!=='ENOENT')throw e;}
|
|
const temp=path.join(directory,'.order-upload-'+crypto.randomUUID());
|
|
try{
|
|
await fs.writeFile(temp,bytes,{flag:'wx'});if(!await same(temp))throw fail('上传后校验失败,请重试。',502);
|
|
try{await native.publishExclusive(temp,target);}catch(e){if(e.code!=='EEXIST')throw e;if(!await same(target))continue;}
|
|
if(!await same(target))throw fail('归档文件校验失败,请检查服务器。',502);return result;
|
|
}finally{await fs.unlink(temp).catch(e=>{if(e.code!=='ENOENT')throw e;});}
|
|
}
|
|
throw fail('存在同名文件且内容不同,请选择其他归档目录。',409);
|
|
}
|
|
}
|
|
class SmbClient{
|
|
constructor(options={}){this.options=options;}
|
|
execute(server,operation,args,options={}){return require('./smb-operation.cjs').execute(server,operation,args,{...this.options,...options});}
|
|
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,byteRange};
|