refactor(app): split HTTP responsibilities and own state before recovery
This commit is contained in:
1 parent
098fec1007
commit
54e5bafd86
13 files changed
+430
-264
No files matched your search
@@ -0,0 +1,37 @@
|
||||
const fs=require('node:fs');const path=require('node:path');
|
||||
const {nextSlots}=require('../../shared/schedule.cjs');
|
||||
const publicJob=({path:ignored,...job})=>({...job,downloadable:job.status==='success'});
|
||||
async function dashboardApi({store,outputDir,workspace,mail,scanner,storage,user,route,request,response,body,reply,fail}){
|
||||
const handled=(...args)=>{reply(...args);return true;};
|
||||
if(route==='/api/overview' && request.method==='GET') {
|
||||
const jobs=store.jobs();const settings=store.settings();const mailChannels=mail?.store.channels()||[];const mailTemplates=mail?.store.templates()||[];
|
||||
const today=new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date());
|
||||
const todayJobs=jobs.filter(job=>new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date(job.updatedAt))===today);
|
||||
const scan=scanner?.store.status();
|
||||
return handled(200,{stats:{total:jobs.length,today:todayJobs.length,completed:jobs.filter(job=>job.status==='success').length,failed:jobs.filter(job=>['error','interrupted'].includes(job.status)).length,running:jobs.filter(job=>job.status==='running').length},scan,automation:{enabled:false,reason:'待核实并接入 BPM 业务规则,完整订单自动处理尚未启用。'},connections:[{name:'PDF 导出',ready:true,detail:'浏览器扩展导出与任务记录已接入'},{name:'订单规则表',ready:false,detail:'等待提供表格,随后配置列映射与筛选'},{name:'BPM 自动扫描',ready:!!scan?.runs.some(r=>r.status==='success'),detail:scan?`${scan.config.enabled?'已开启':'已暂停'},每 ${scan.config.intervalMinutes} 分钟扫描 · 已收录 ${scan.total} 条流程`:'扫描服务未启动'},{name:'存储服务器',ready:!!storage?.store.servers().some(s=>s.enabled&&s.state.readable&&s.state.writable),detail:storage?`已配置 ${storage.store.servers().length} 个 SMB 存储服务器`:'存储服务未启动'},{name:'邮件渠道',ready:mailChannels.some(c=>c.state.smtp&&c.state.imap),detail:`已配置 ${mailChannels.length} 个邮箱`},{name:'邮件模板',ready:mailTemplates.some(t=>t.status==='active'),detail:`${mailTemplates.filter(t=>t.status==='active').length} 个已生效,${mailTemplates.filter(t=>t.status==='pending').length} 个待确认`},{name:'产品线群组',ready:settings.groups.length>0,detail:`已配置 ${settings.groups.length} 个产品线`}],nextSlots:nextSlots(settings.schedule,new Date(),2,workspace?workspace.snapshot(store.users()).calendar.overrides:[]),schedule:settings.schedule,jobs:jobs.slice(0,6).map(publicJob),audit:store.audit().slice(0,5)});
|
||||
}
|
||||
if(route==='/api/settings') {
|
||||
if(request.method==='GET')return handled(200,store.settings());
|
||||
if(request.method==='POST'){if(user.role!=='admin')fail(403,'仅管理员可以修改配置。');return handled(200,store.saveSettings(body,body.version,user.username));}
|
||||
}
|
||||
if(route==='/api/jobs' && request.method==='GET')return handled(200,{jobs:store.jobs().map(publicJob)});
|
||||
if(route==='/api/audit' && request.method==='GET')return handled(200,{audit:store.audit()});
|
||||
if(route==='/api/users') {
|
||||
if(user.role!=='admin')fail(403,'仅管理员可以管理账号。');
|
||||
if(request.method==='GET')return handled(200,{users:store.users()});
|
||||
if(request.method==='POST')return handled(201,{user:store.addUser(body,user.username)});
|
||||
}
|
||||
const download=/^\/api\/jobs\/([\w-]+)\/file$/.exec(route);
|
||||
if(download && request.method==='GET') {
|
||||
const job=store.jobs().find(job=>job.jobId===download[1]);
|
||||
if(!job || job.status!=='success' || !job.path)fail(404,'文件不可用。');
|
||||
let realRoot,realFile;
|
||||
try{[realRoot,realFile]=await Promise.all([fs.promises.realpath(outputDir),fs.promises.realpath(job.path)]);}catch{fail(404,'文件不存在。');}
|
||||
const relative=path.relative(realRoot,realFile);
|
||||
if(!relative || relative.startsWith('..'+path.sep) || relative==='..' || path.isAbsolute(relative) || path.extname(realFile).toLowerCase()!=='.pdf')fail(404,'文件不可用。');
|
||||
const bytes=await fs.promises.readFile(realFile);
|
||||
response.writeHead(200,{'Content-Type':'application/pdf','Content-Disposition':`attachment; filename*=UTF-8''${encodeURIComponent(path.basename(realFile))}`});response.end(bytes);return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
module.exports={dashboardApi};
|
||||
@@ -0,0 +1,46 @@
|
||||
const path=require('node:path');
|
||||
const {SessionStore,SESSION_MS}=require('./sessions.cjs');
|
||||
const {isLoopback}=require('../../app/request.cjs');
|
||||
function createAuth({store,previewUserId,bpmSessions}){
|
||||
const sessions=new SessionStore(path.dirname(store.file));const failures=new Map();
|
||||
const sessionCookieName=previewUserId?'order_preview_session':'order_session';
|
||||
const sessionCookiePattern=new RegExp('(?:^|;\\s*)'+sessionCookieName+'=([a-f0-9]{64})(?:;|$)');
|
||||
async function authenticate({request,response,route,body,reply,fail,encryptedTransport}){
|
||||
const handled=(...args)=>{reply(...args);return {handled:true};};
|
||||
const host=(request.headers.host || '').split(':')[0];
|
||||
const canSetup=isLoopback(request.socket.remoteAddress) && ['localhost','127.0.0.1'].includes(host);
|
||||
const preview=Boolean(previewUserId && canSetup && store.user(previewUserId));
|
||||
if(route==='/api/bootstrap/status' && request.method==='GET')return handled(200,{required:store.users().length===0,canSetup,preview});
|
||||
function signIn(user) {
|
||||
const {token}=sessions.issue(user.id);
|
||||
response.setHeader('Set-Cookie',`${sessionCookieName}=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${SESSION_MS/1000}${encryptedTransport?'; Secure':''}`);
|
||||
return user;
|
||||
}
|
||||
if(route==='/api/bootstrap' && request.method==='POST') {
|
||||
if(!canSetup)fail(403,'请在部署机访问 http://127.0.0.1:18766 创建管理员。');
|
||||
return handled(201,{user:signIn(store.bootstrap(body.username,body.password))});
|
||||
}
|
||||
if(route==='/api/preview-login' && request.method==='POST') {
|
||||
if(!previewUserId)fail(404,'没有找到此页面或操作。');
|
||||
if(!preview)fail(403,'演示登录仅允许在部署机本地访问。');
|
||||
return handled(200,{user:signIn(store.user(previewUserId)),preview:true});
|
||||
}
|
||||
if(route==='/api/login' && request.method==='POST') {
|
||||
const address=request.socket.remoteAddress;const now=Date.now();
|
||||
for(const [key,value] of failures)if(now-value.since>900000)failures.delete(key);
|
||||
if(failures.get(address)?.count>=10)fail(429,'登录失败次数过多,请 15 分钟后重试。');
|
||||
const user=store.authenticate(body.username,body.password);
|
||||
if(!user){if(failures.size>1000)failures.clear();const previous=failures.get(address);failures.set(address,{since:previous?.since || now,count:(previous?.count || 0)+1});fail(401,'账号或密码不正确。');}
|
||||
failures.delete(address);return handled(200,{user:signIn(user)});
|
||||
}
|
||||
const token=sessionCookiePattern.exec(request.headers.cookie || '')?.[1];
|
||||
const session=sessions.lookup(token);const user=session?store.user(session.userId):null;
|
||||
if(!user)fail(401,'请先登录。');
|
||||
if(session.renewed)response.setHeader('Set-Cookie',`${sessionCookieName}=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${SESSION_MS/1000}${encryptedTransport?'; Secure':''}`);
|
||||
if(route==='/api/me' && request.method==='GET')return handled(200,{user,preview});
|
||||
if(route==='/api/logout' && request.method==='POST'){sessions.revoke(token);response.setHeader('Set-Cookie',`${sessionCookieName}=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0${encryptedTransport?'; Secure':''}`);if(bpmSessions)try{await bpmSessions.releaseSession(token);}catch{fail(502,'登录窗口关闭失败,请稍后重试。');}return handled(200,{ok:true});}
|
||||
return {user,token,preview};
|
||||
}
|
||||
return {authenticate,close:()=>sessions.close()};
|
||||
}
|
||||
module.exports={createAuth};
|
||||
Reference in new issue
Block a user