merge: preserve main lazy loading and scoped refresh with DSH

This commit is contained in:
abaishu0730 committed 2026-10-29 09:42:00 +08:00
commit fb7a195186
113 files changed
+2675 -212

No files matched your search

@@ -96,6 +96,10 @@ class NativeSchedules {
this.store.db.exec(
"CREATE TABLE IF NOT EXISTS assistant_schedule_tasks(id TEXT PRIMARY KEY,conversation_id TEXT NOT NULL,owner TEXT NOT NULL,payload BLOB NOT NULL,last_error TEXT NOT NULL DEFAULT '');CREATE TABLE IF NOT EXISTS assistant_schedule_inbox(id TEXT PRIMARY KEY,conversation_id TEXT NOT NULL,owner TEXT NOT NULL,task_id TEXT NOT NULL,status TEXT NOT NULL,turn_id TEXT,payload BLOB NOT NULL,created_at TEXT NOT NULL);CREATE INDEX IF NOT EXISTS schedule_inbox_owner ON assistant_schedule_inbox(owner,created_at);UPDATE assistant_schedule_inbox SET status='queued' WHERE status='running';",
);
require('../../shared/refresh-revisions.cjs').installRevisionTracking(this.store.db, [
['assistant_schedule_tasks', "'owner:' || $row.owner"],
['assistant_schedule_inbox', "'owner:' || $row.owner"],
]);
const schema = this.module.scheduleDomain.tables.tasks.valueSchema;
for (const row of this.store.db.prepare('SELECT * FROM assistant_schedule_tasks').all()) {
const value = schema.parse(this.store.decode('schedule-task:' + row.id, row.payload));
+9
View File
@@ -48,6 +48,15 @@ class AssistantStore {
.run(this.encode('config', { ...raw, apiKey: '' }));
}
});
require('../../shared/refresh-revisions.cjs').installRevisionTracking(this.db, [
'config',
['conversations', "'owner:' || $row.owner"],
['turns', "'owner:' || (SELECT owner FROM conversations WHERE id=$row.conversation_id)"],
['turns', "'usage:' || $row.day", 'OLD.day IS NOT NEW.day'],
['assistant_usage', "'usage:' || $row.day"],
['assistant_providers', "'config'"],
['assistant_provider_defaults', "'config'"],
]);
} catch (error) {
try {
this.db?.close();
+1
View File
@@ -14,6 +14,7 @@ class BpmScanStore{
UPDATE runs SET status='error',message='服务重启,扫描未完成。',finished_at=CURRENT_TIMESTAMP WHERE status='running';`);
if(!this.db.prepare('PRAGMA table_info(runs)').all().some(c=>c.name==='kind'))this.db.exec("ALTER TABLE runs ADD COLUMN kind TEXT NOT NULL DEFAULT 'inform'");
this.deliveries=new ScanDeliveries({db:this.db,dir});
require('../../shared/refresh-revisions.cjs').installRevisionTracking(this.db,['config','arrivals','runs','execution_deliveries']);
} catch(error) {
try { this.db?.close(); } catch {}
throw error;
+7 -3
View File
@@ -3,7 +3,7 @@ const {SessionStore,SESSION_MS}=require('./sessions.cjs');
const {isLoopback}=require('../../app/request.cjs');
const {validateChange}=require('./passwords.cjs');
function createAuth({store,workspace,bpmSessions,bpmMonitor,bpmLifecycle}){
const sessions=new SessionStore(path.dirname(store.file));const failures=new Map(),passwordFailures=new Map();
const sessions=new SessionStore(path.dirname(store.file));const failures=new Map(),passwordFailures=new Map(),pendingLogins=new Map();
const cleanup=require('./pending-cleanup.cjs').accessCleanup({store,workspace,bpmSessions,bpmMonitor,bpmLifecycle,sessions});
const sessionCookieName='order_session';
const sessionCookiePattern=new RegExp('(?:^|;\\s*)'+sessionCookieName+'=([a-f0-9]{64})(?:;|$)');
@@ -24,8 +24,12 @@ const handled=(...args)=>{reply(...args);return {handled: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((failures.get(address)?.count||0)+(pendingLogins.get(address)||0)>=10)fail(429,'登录失败次数过多,请 15 分钟后重试。');
const candidate=typeof body.username==='string'?store.users().find(member=>member.username.toLowerCase()===body.username.toLowerCase()):null;
const passwordVersion=candidate?store.passwordVersion(candidate.id):null;
pendingLogins.set(address,(pendingLogins.get(address)||0)+1);
let user;try{user=await store.authenticateAsync(body.username,body.password);}finally{const pending=(pendingLogins.get(address)||1)-1;if(pending)pendingLogins.set(address,pending);else pendingLogins.delete(address);}
if(user&&(!candidate||user.id!==candidate.id||store.passwordVersion(user.id)!==passwordVersion||store.user(user.id)?.enabled===false))user=null;
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)});
}
+15 -1
View File
@@ -1,5 +1,14 @@
'use strict';
const crypto=require('node:crypto');
const {promisify}=require('node:util');
const scrypt=promisify(crypto.scrypt),passwordQueue=[];let active=0;
function schedulePassword(work){
if(active>=4&&passwordQueue.length>=32)return Promise.reject(Object.assign(Error('登录验证繁忙,请稍后重试。'),{status:429}));
return new Promise((resolve,reject)=>{
const start=()=>{active++;Promise.resolve().then(work).then(resolve,reject).finally(()=>{active--;passwordQueue.shift()?.();});};
if(active<4)start();else passwordQueue.push(start);
});
}
const fail=message=>{throw Object.assign(new Error(message),{status:400});};
function validatePassword(password){if(typeof password!=='string'||password.length<12||password.length>128)fail('密码长度需为 12–128 位。');}
function hashPassword(password){validatePassword(password);const salt=crypto.randomBytes(16).toString('hex');return salt+':'+crypto.scryptSync(password,salt,32).toString('hex');}
@@ -9,10 +18,15 @@ function matchesPassword(password,encoded){
const actual=crypto.scryptSync(password,salt,32),expected=Buffer.from(hash||'','hex');
return expected.length===actual.length&&crypto.timingSafeEqual(actual,expected);
}
async function matchesPasswordAsync(password,encoded){
if(typeof password!=='string'||password.length>128)return false;
const [salt,hash]=(encoded||'00000000000000000000000000000000:'+ '0'.repeat(64)).split(':');
return schedulePassword(async()=>{const actual=await scrypt(password,salt,32),expected=Buffer.from(hash||'','hex');return expected.length===actual.length&&crypto.timingSafeEqual(actual,expected);});
}
function validateChange(body){
if(!body||Object.keys(body).some(key=>!['currentPassword','newPassword','confirmPassword'].includes(key)))fail('密码修改内容不正确。');
if(typeof body.currentPassword!=='string'||!body.currentPassword||body.currentPassword.length>128)fail('请填写当前密码。');
validatePassword(body.newPassword);
if(body.confirmPassword!==body.newPassword)fail('两次输入的新密码不一致。');
}
module.exports={validatePassword,hashPassword,matchesPassword,validateChange};
module.exports={validatePassword,hashPassword,matchesPassword,matchesPasswordAsync,validateChange};
+12 -1
View File
@@ -2,7 +2,7 @@ const fs=require('node:fs');
const path=require('node:path');
const crypto=require('node:crypto');
const {DatabaseSync}=require('node:sqlite');
const {validatePassword,hashPassword,matchesPassword}=require('./passwords.cjs');
const {validatePassword,hashPassword,matchesPassword,matchesPasswordAsync}=require('./passwords.cjs');
const {JobStore}=require('./job-store.cjs');
const copy=value=>structuredClone(value);
const safeUser=({id,username,role,createdAt,enabled=true,version=1})=>({id,username,role,createdAt,enabled,version});
@@ -43,6 +43,7 @@ class Store {
return JSON.parse(db.prepare('SELECT value FROM dashboard_state WHERE id=1').get().value);
});
this.jobStore=new JobStore(this);
this.database(db=>require('../../shared/refresh-revisions.cjs').installRevisionTracking(db,['pdf_jobs','dashboard_state']));
}
database(work){
const db=new DatabaseSync(this.file);
@@ -93,6 +94,16 @@ class Store {
return safeUser(user);
}
passwordVersion(id){return this.data.users.find(user=>user.id===id)?.passwordVersion||0;}
async authenticateAsync(username,password){
if(typeof username!=='string'||typeof password!=='string'||password.length>128)return null;
const prior=this.data.users.find(user=>user.username.toLowerCase()===username.toLowerCase());
const passwordHash=prior?.passwordHash,version=prior?.passwordVersion||0;
const matches=await matchesPasswordAsync(password,passwordHash);
// Password/role changes can commit while the worker pool verifies the hash.
const current=prior&&this.data.users.find(user=>user.id===prior.id);
if(!matches||!current||current.enabled===false||current.passwordHash!==passwordHash||(current.passwordVersion||0)!==version)return null;
return safeUser(current);
}
validateUserChange(id,input,actor){
if(actor?.role!=='admin')fail('仅管理员可以调整账号。',403);
const target=this.user(id);if(!target)fail('账号不存在。',404);
+1 -1
View File
@@ -60,7 +60,7 @@ class RuntimeHealth {
return {id:c.id,name:redact(c.name||'托管邮箱'),status,checkedAt,detail:redact(c.state?.message||'尚未检查 SMTP / IMAP。'),...this.remember('mail',c.id,{successAt:status==='healthy'?checkedAt:null,failureAt:status==='error'?checkedAt:null})};
}));
if(this.sources.execution)safe('execution','分类订单执行','#notification-execution',()=>{
const data=this.sources.execution.snapshot(),names={liveTodo:'真实待办',pdfExport:'PDF 导出',automaticArchive:'归档校验'};
const execution=this.sources.execution,data=typeof execution.healthSnapshot==='function'?execution.healthSnapshot():execution.snapshot(),names={liveTodo:'真实待办',pdfExport:'PDF 导出',automaticArchive:'归档校验'};
const items=Object.entries(names).map(([id,name])=>({id,name,global:true,status:data.capabilities?.[id]===true?'healthy':'pending',detail:data.capabilities?.[id]===true?'实际检查已通过;各类别仍需现场核验。':'尚未通过实际接入检查,请在订单通知管理的订单执行查看阻塞原因。'}));
for(const task of data.tasks||[]){const status=['blocked','failed'].includes(task.status)?'error':task.status==='unknown'?'unknown':['capturing','preparing','archiving','running','sending'].includes(task.status)?'running':['archived','sent','pending'].includes(task.status)?'healthy':'pending';
items.push({id:task.id,owner:connections.find(c=>c.id===task.connectionId)?.owner,name:redact(task.processName||'订单执行任务'),status,checkedAt:timestamp(task.updatedAt),detail:redact(task.error||task.reason||task.blockedReason||'任务进度已持久保存,请在订单通知管理查看。'),...this.remember('execution',task.id,{successAt:status==='healthy'?task.updatedAt:null,failureAt:status==='error'?task.updatedAt:null})});}
+7 -5
View File
@@ -25,11 +25,13 @@ async function readHistory(client,input={}){
try{
const uidValidity=String(client.mailbox.uidValidity);
if(input.action==='search'){
const found=await client.search(query,{uid:true}),uids=(found||[]).filter(Number.isSafeInteger).sort((a,b)=>b-a),messages=[];
for(const uid of uids.slice(0,limit)){
const info=await client.fetchOne(uid,{envelope:true,size:true},{uid:true});if(!info)continue;
messages.push({uid,subject:info.envelope?.subject||'',date:info.envelope?.date?.toISOString()||null,to:addresses(info.envelope?.to),cc:addresses(info.envelope?.cc),size:info.size});
}
const found=await client.search(query,{uid:true}),uids=(found||[]).filter(uid=>Number.isSafeInteger(uid)&&uid>0).sort((a,b)=>b-a),selected=uids.slice(0,limit),envelopes=new Map();
// FETCH emits mailbox sequence order; retain the selected UID order even when
// messages disappear between SEARCH and FETCH. An empty set must never mean '*'.
if(selected.length)for await(const info of client.fetch(selected.join(','),{uid:true,envelope:true,size:true},{uid:true}))if(selected.includes(info.uid))envelopes.set(info.uid,{...envelopes.get(info.uid),...info});
const messages=selected.flatMap(uid=>{
const info=envelopes.get(uid);return info?[{uid,subject:info.envelope?.subject||'',date:info.envelope?.date?.toISOString()||null,to:addresses(info.envelope?.to),cc:addresses(info.envelope?.cc),size:info.size}]:[];
});
return {folder:input.folder,uidValidity,messages,truncated:uids.length>limit};
}
if(!Number.isSafeInteger(input.uid)||input.uid<=0)fail('邮件标识无效。');
+1
View File
@@ -20,6 +20,7 @@ class MailStore{
if(columns!=='channel_id,scope,notification_mode')this.db.exec("DROP INDEX IF EXISTS active_template; CREATE UNIQUE INDEX active_template ON templates(channel_id,scope,notification_mode) WHERE status='active'");
});
for(const r of this.db.prepare("SELECT id,payload FROM templates WHERE summary='{}'").all()){const p=this.decode(r.id,r.payload);this.db.prepare('UPDATE templates SET summary=? WHERE id=?').run(this.summary(p),r.id);}
require('../../shared/refresh-revisions.cjs').installRevisionTracking(this.db,['channels','templates','receipts','sends','meta']);
} catch(error) {
try { this.db?.close(); } catch {}
try { this.vault?.destroy(); } catch {}
@@ -141,6 +141,17 @@ class OrderExecutionCoordinator{
try{this.connection(task.connectionId,principal);return true;}
catch{return false;}
}
healthSnapshot(){
// Health consumes persisted progress, never captured fields or discovery views.
const tasks=this.store.all('execution-tasks').map(task=>{
const order=task.orderId&&this.store.get('orders',task.orderId);
const activeStatus=['failed','unknown','blocked','capturing','archiving'].includes(task.status);
return {id:task.id,connectionId:task.connectionId,processName:task.row?.processName,
status:activeStatus?task.status:order?.status||task.status,updatedAt:task.updatedAt,
error:task.error||order?.error||null,reason:task.reason,blockedReason:task.blockedReason};
}).reverse();
return {tasks,capabilities:clone(this.store.capabilities)};
}
snapshot(principal,{includeFieldEvidence=false}={}){
const allowed=id=>!principal||require('../order-rules/access.cjs').canReadConnection(this.workspace,principal.user,id);
const fields=this.store.fields();
+4 -3
View File
@@ -1,6 +1,7 @@
'use strict';
const {fail,validateRule}=require('./validation.cjs');
const {checkTemplates}=require('./template-validation.cjs');
const {ruleReceipt,restrictedReceipt}=require('./configuration.cjs');
async function orderRuleApi({orderRules,mail,workspace,user,url,route,method,body,reply,response}){
if(route!=='/api/order-rules'&&!route.startsWith('/api/order-rules/'))return false;
if(!orderRules)fail('分类通知规则服务未启动。',503);
@@ -39,12 +40,12 @@ async function orderRuleApi({orderRules,mail,workspace,user,url,route,method,bod
else if(route==='/api/order-rules/import/commit')result=require('./import.cjs').commitImport(orderRules,body,actor,{mail,user});
else if(route==='/api/order-rules/restricted-test/apply'){
for(const item of Array.isArray(body?.rules)?body.rules:[]){const record=orderRules.get('rules',item?.id);if(record)checkTemplates(mail,record.draft);}
result=orderRules.applyRestrictedDrafts(body,user);
result=restrictedReceipt(orderRules,orderRules.applyRestrictedDrafts(body,user));
}
else if(route==='/api/order-rules/rules'){
const old=orderRules.get('rules',body?.id)?.draft;
if(old)checkTemplates(mail,validateRule(body,old));
result=orderRules.saveRule(body,actor);
result=ruleReceipt(orderRules,orderRules.saveRule(body,actor));
}
else if(route==='/api/order-rules/settings'){
if(body?.enabled){if(!mail)fail('发件邮箱服务未启动。',409);const channel=mail.store.publicChannel(body.channelId);if(!channel.state.smtp)fail('请先验证发件邮箱 SMTP。',409);}
@@ -60,7 +61,7 @@ async function orderRuleApi({orderRules,mail,workspace,user,url,route,method,bod
const recheck=/^\/api\/order-rules\/orders\/([\w-]+)\/recheck$/.exec(route);
if(rule){if(!body||Object.keys(body).some(k=>!['version','publishedVersion','activationVersion'].includes(k)))fail('请提供当前规则和启停版本。');const record=orderRules.get('rules',rule[1]);if(rule[2]==='publish'){if(!record?.trialSampleId||!orderRules.get('capture-samples',record.trialSampleId))fail('发布前必须选择服务端真实采集样本完成试运行。',409);}
if(rule[2]!=='pause'){const selected=rule[2]==='resume'?record?.published:record?.draft;checkTemplates(mail,selected);}
result=orderRules[rule[2]](rule[1],body,actor);}
result=ruleReceipt(orderRules,orderRules[rule[2]](rule[1],body,actor));}
else if(batch){if(!body||Object.keys(body).some(k=>!['version','idempotencyKey','resolution','note'].includes(k)))fail('核验内容无效。');result=orderRules.resolve(batch[1],body,actor,{controlled:true});}
else if(recheck){if(!body||Object.keys(body).some(k=>k!=='note'))fail('重新识别内容无效。');result=orderRules.recheck(recheck[1],body,actor);}
else fail('没有找到此规则操作。',404);
+10 -3
View File
@@ -11,7 +11,7 @@ function associated(store,order,mode){return store.all('batches').filter(b=>mode
function safeHistory(batches){return batches.every(b=>proof(b)&&(b.status==='failed'||b.status==='cancelled'&&b.resolution?.resolution==='carry_forward'));}
function qualified(store,order,{active=true}={}){
if(!order||order.removedAt||!order.categoryId||!order.sample||!receipt(order.archive)||!order.ruleSnapshot)return null;
const tasks=store.all('execution-tasks').filter(t=>t.orderId===order.id);if(tasks.length!==1)return null;const task=tasks[0];
const tasks=require('./read-context.cjs').byOrder(store,'execution-tasks',order.id);if(tasks.length!==1)return null;const task=tasks[0];
if(task.removedAt||task.supersededBy||task.revisionIgnored||task.conflict||task.blockedByBatchId||!['complete','missed_window'].includes(task.step))return null;
if(!identity.sameTask(task.row,order.sample)||['source','portalSource','taskId','instanceId','revision','processName','nodeName','receivedAt'].some(k=>String(task.row?.[k])!==String(order.sample[k])))return null;
const captured=store.get('capture-samples',task.sampleId||'');if(captured?.provenance!=='server-provider'||captured.taskId!==task.id||typeof captured.snapshot?.html!=='string'||!captured.snapshot.html.trim()||!captured.sample||identity.fingerprint(captured.sample)!==identity.fingerprint(order.sample))return null;
@@ -24,6 +24,11 @@ function qualified(store,order,{active=true}={}){
return {task,original};
}
function windowForOrder(store,value,mode='normal'){
const context=require('./read-context.cjs').state(store);
if(context&&value?.id){const key=JSON.stringify(['carry',value.id,mode]);if(!context.memo.has(key))context.memo.set(key,readWindow(store,value,mode));return context.memo.get(key);}
return readWindow(store,value,mode);
}
function readWindow(store,value,mode){
if(!['normal','huizhou'].includes(mode))return null;
// A Hui projection replaces event/order numbers. Always validate the persisted source.
const order=value?.id&&store.get('orders',value.id),stamp=order?.carryForward?.[mode];if(!stamp||stamp.basisHash!==basis(order)||!qualified(store,order,{active:false}))return null;
@@ -37,11 +42,13 @@ function knownMissed(store,value,original,stamp){
return ['start','end','collectionStart','collectionEnd','collectionLeadMinutes','policyVersion','startInclusive','endInclusive'].every(key=>value[key]===expected[key]);
}
function candidate(store,order,mode){
const q=qualified(store,order),state=delivery(order,mode);if(!q||!state||order.blockedByBatchId||state.blockedByBatchId||!['pending','blocked','archived'].includes(state.status))return null;
const state=delivery(order,mode);if(!state||order.blockedByBatchId||state.blockedByBatchId||!['pending','blocked','archived'].includes(state.status))return null;
if(mode==='huizhou'&&(order.ruleSnapshot?.huizhouEnabled!==true||!state.orderNos?.length||state.issues?.length||!['pending','blocked','archived','batched','sent','unknown'].includes(order.status)))return null;
const q=qualified(store,order);if(!q)return null;
const batches=associated(store,order,mode);if(!safeHistory(batches))return null;
const failed=batches.filter(b=>b.status==='failed');if(state.batchId&&!failed.some(b=>b.id===state.batchId))return null;
if(mode==='normal'&&['unknown','sending','sent','ignored','archiving','capturing','failed'].includes(q.task.status))return null;
if(mode==='huizhou'&&(order.ruleSnapshot.huizhouEnabled!==true||!state.orderNos?.length||state.issues?.length||!['pending','blocked','archived','batched','sent','unknown'].includes(order.status)||q.task.step!=='complete'&&q.task.step!=='missed_window'))return null;
if(mode==='huizhou'&&q.task.step!=='complete'&&q.task.step!=='missed_window')return null;
const stamp=order.carryForward?.[mode];if(stamp&&!windowForOrder(store,order,mode))return null;
if(!knownMissed(store,mode==='normal'?order.missedWindow:state.missedWindow,q.original,stamp)||mode==='normal'&&!knownMissed(store,q.task.missedWindow,q.original,stamp))return null;
return {...q,order,mode,state,stamp,failed,previous:stamp?.targetCutoff||q.original.end};
@@ -14,18 +14,19 @@ function contentFor(store,rule,cutoff,mode,template){
if(template?.attachments?.length)fail('业务通知模板禁止附件,批次编辑不能覆盖此限制。',409);
return {template:{...(template||{}),id:template?.id||rule.bodyTemplateId||id,version:template?.version||rule.version,notificationMode:mode,status:'active',attachments:[],subject:saved.subject,text:saved.text,html:saved.html},edit:{id,version:saved.version,updatedAt:saved.updatedAt,updatedBy:saved.updatedBy}};
}
function list(store,{cutoff}={}){
function list(store,options={}){return structuredClone(readList(require('./read-context.cjs').readStore(store),options));}
function readList(store,{cutoff}={}){
if(typeof store.clock!=='function'||typeof store.schedule!=='function'||typeof store.calendar!=='function')return [];
const window=cutoff?require('./window.cjs').windowForCutoff(cutoff,store.schedule(),store.calendar()):upcomingWindow(store.clock(),store.schedule(),store.calendar());if(!window)return [];
const groups=new Map(),frozen=store.all('batches');
const groups=new Map(),frozen=new Set(store.all('batches').filter(b=>b.cutoff===window.end).map(b=>JSON.stringify([b.categoryId,b.notificationMode||'normal'])));
for(const order of store.all('orders')){
const rule=order.ruleSnapshot;if(order.removedAt||!rule?.id||!rule.categoryId||!require('./scopes.cjs').matchesScope(rule,order.event||{}))continue;
if(order.blockedByBatchId||order.status==='ignored')continue;
for(const mode of ['normal','huizhou']){
const carried=require('./carry-forward.cjs').windowForOrder(store,order,mode);if(order.missedWindow&&!carried||!require('./restricted-test.cjs').orderInWindow(store,order,window,mode))continue;
const notice=delivery(order,mode);if(!notice||notice.batchId||!['identified','preparing','archived','pending','blocked','failed'].includes(notice.status))continue;
if(mode==='huizhou'&&rule.huizhouEnabled!==true)continue;
if(frozen.some(b=>b.categoryId===rule.categoryId&&(b.notificationMode||'normal')===mode&&b.cutoff===window.end))continue;
if(frozen.has(JSON.stringify([rule.categoryId,mode])))continue;
const carried=require('./carry-forward.cjs').windowForOrder(store,order,mode);if(order.missedWindow&&!carried||!require('./restricted-test.cjs').orderInWindow(store,order,window,mode))continue;
const id=idFor(rule,window.end,mode);if(!groups.has(id))groups.set(id,{id,status:'collecting',categoryId:rule.categoryId,notificationMode:mode,cutoff:window.end,window,windowStart:window.start,windowEnd:window.end,rule,orders:[],orderIds:[],attachments:[],createdAt:order.ingestedAt||order.createdAt,...(rule.testRunId?{testRunId:rule.testRunId}:{})});const group=groups.get(id);group.orders.push(order);group.orderIds.push(order.id);
}
}
+55
View File
@@ -0,0 +1,55 @@
'use strict';
const {fail}=require('./validation.cjs');
const {canReadConnection}=require('./access.cjs');
const pick=(value,keys)=>Object.fromEntries(keys.filter(key=>Object.hasOwn(value,key)).map(key=>[key,value[key]]));
const adapterKeys=['id','processName','processVersion','verified','reference','status','label','sampleId'];
const templateKeys=['id','channelId','scope','notificationMode','status','version','createdAt','subject','sender','attachmentCount'];
const serverKeys=['id','version','name','host','share','directory','username','enabled','state','hasPassword','createdAt','updatedAt','address','authMode','passwordless'];
const sampleKeys=['connectionId','source','processVersion','nodeName','serialNum','title','receivedAt'];
function configuration(orderRules,mail,storage){
const snapshot=orderRules.snapshot({includeRecords:false}),errors={};
const resource=(key,read)=>{try{return read();}catch{errors[key]={templates:'邮件模板暂不可读取,请稍后重试。',bindings:'类别模板关联暂不可读取,请稍后重试。',servers:'归档服务器暂不可读取,请稍后重试。'}[key];return null;}};
const bindings=resource('bindings',()=>mail.store.categoryBindings().map(value=>pick(value,['categoryId','templateId','version'])));
const bound=new Set([...(bindings||[]).map(value=>value.templateId),...snapshot.rules.flatMap(rule=>[rule.bodyTemplateId,rule.huizhouTemplateId])].filter(Boolean));
const templates=resource('templates',()=>mail.store.templates().filter(value=>value.status==='active'||bound.has(value.id)).map(value=>pick(value,templateKeys)));
const servers=resource('servers',()=>storage.store.servers().map(value=>pick(value,serverKeys)));
let scopeProcesses=[],scopeCatalog=[],scopeError=null;
try{const directory=require('./scope-catalog.cjs').directory(orderRules);scopeProcesses=directory.processes;scopeCatalog=directory.scopes;}
catch{scopeError='流程节点目录暂不可读取,请稍后重试。';}
return {rules:snapshot.rules.map(rule=>({huizhouEnabled:false,huizhouTemplateId:'',...rule})),adapters:snapshot.adapters.map(value=>pick(value,adapterKeys)),restrictedTest:snapshot.restrictedTest??null,settings:snapshot.settings,capabilities:snapshot.capabilities,window:snapshot.window,scopeProcesses,scopeCatalog,scopeError,resources:{templates,bindings,servers,errors}};
}
function samples(orderRules,workspace,user,params){
const processes=new Set();
for(const [key,value] of params){
if(key!=='process'||!value.trim()||value.length>250||/[\x00-\x1f\x7f-\x9f]/.test(value))fail('请选择有效的样本流程。');
processes.add(value.trim());
}
if(processes.size>100)fail('一次最多读取100个流程的样本。');
if(!processes.size)return {samples:[]};
return {samples:orderRules.all('capture-samples').filter(value=>value.provenance==='server-provider'&&!value.sample?.demo&&value.sample&&value.sample.source!=='history'&&processes.has(value.processName)&&canReadConnection(workspace,user,value.sample.connectionId)).map(value=>({...pick(value,['id','processName','provenance','capturedAt']),sample:pick(value.sample,sampleKeys)}))};
}
function ruleReceipt(orderRules,result){
const snapshot=orderRules.snapshot({includeRecords:false});
return {...result,...snapshot.rules.find(rule=>rule.id===result.id),restrictedTest:snapshot.restrictedTest??null};
}
function restrictedReceipt(orderRules,result){
const snapshot=orderRules.snapshot({includeRecords:false});
return {...result,rules:snapshot.rules,restrictedTest:snapshot.restrictedTest??null};
}
function templateUsage(rules){return rules.map(r=>({categoryId:r.published?.categoryId||r.draft?.categoryId,name:r.draft?.name,templateId:r.published?.bodyTemplateId||'',huizhouEnabled:r.published?.huizhouEnabled===true,huizhouTemplateId:r.published?.huizhouTemplateId||'',legacyBinding:!!r.published&&r.published.bodyTemplateId===undefined,publishedVersion:r.published?.version||null,status:r.published?.status||'draft'}));}
function orderRuleConfigurationApi({orderRules,mail,storage,workspace,user,url,route,method,reply}){
if(method!=='GET'||!['/api/order-rules/configuration','/api/order-rules/configuration/samples','/api/order-rules/status','/api/order-rules/catalog','/api/order-rules/notification-settings'].includes(route))return false;
if(!user)fail('请先登录。',401);
if(!orderRules)fail('分类通知规则服务未启动。',503);
if(route==='/api/order-rules/configuration')reply(200,configuration(orderRules,mail,storage));
else if(route==='/api/order-rules/status')reply(200,{settings:{enabled:orderRules.settings().enabled},capabilities:structuredClone(orderRules.capabilities)});
else if(route==='/api/order-rules/catalog'){const rules=orderRules.all('rules');reply(200,{rules:rules.map(r=>pick(r.draft,['categoryId','name'])),templateUsage:templateUsage(rules)});}
else if(route==='/api/order-rules/notification-settings')reply(200,{settings:orderRules.settings(),restrictedTest:orderRules.restrictedTest()});
else reply(200,samples(orderRules,workspace,user,url.searchParams));
return true;
}
module.exports={orderRuleConfigurationApi,ruleReceipt,restrictedReceipt,templateUsage};
+6 -4
View File
@@ -24,7 +24,9 @@ class OrderRuleDispatcher{
this.attachmentReader=attachmentReader;if(templateResolver)store.templateResolver=templateResolver;if(mail?.store?.signature)store.signatureResolver=id=>mail.store.signature(id);
}
ready(){
const config=this.store.settings(),cap=this.store.snapshot().capabilities;
// Real RuleStore exposes immutable capabilities directly; retain the small
// snapshot fallback for adapters and older test/runtime stores.
const config=this.store.settings(),cap=this.store.capabilities||this.store.snapshot?.().capabilities||{};
return !this.stopped&&config.enabled===true&&this.providersReady()===true&&cap?.liveTodo===true&&cap?.pdfExport===true&&cap?.automaticArchive===true;
}
tick(now=this.clock()){
@@ -35,7 +37,7 @@ class OrderRuleDispatcher{
}
async perform(now){
this.store.expireIntakes?.();
for(const batch of this.store.snapshot().batches||[])if(batch.status==='prepared'&&!batch.manual&&now-Date.parse(batch.cutoff)>1800000)this.store.finishSending(batch.id,'failed','冻结发送队列超过30分钟,请负责人核验后受控补发。',{outcome:'not_submitted',phase:'queue_expired',at:this.clock().toISOString()});
for(const batch of this.store.all('batches').reverse())if(batch.status==='prepared'&&!batch.manual&&now-Date.parse(batch.cutoff)>1800000)this.store.finishSending(batch.id,'failed','冻结发送队列超过30分钟,请负责人核验后受控补发。',{outcome:'not_submitted',phase:'queue_expired',at:this.clock().toISOString()});
if(!this.ready())return;
const config=freeze(structuredClone(this.store.settings())),schedule=this.settings()?.schedule,calendar=this.calendar();
if(!schedule?.times?.length)return;
@@ -43,13 +45,13 @@ class OrderRuleDispatcher{
if(!this.schedule||this.schedule.signature!==signature||now-Date.parse(this.schedule.next)>60000){const current=require('./window.cjs').upcomingWindow(now,schedule,calendar);this.schedule={signature,next:current?.available?current.end:nextSlots(schedule,now,1,calendar)[0]};}
const resumed=this.store.pendingIntakeCutoffs?.().filter(cutoff=>now-Date.parse(cutoff)>60000)||[];
const cutoff=resumed[0]||this.schedule.next,canPrepare=cutoff&&now-Date.parse(cutoff)>=0&&(now-Date.parse(cutoff)<=60000||resumed.includes(cutoff));
const queued=(this.store.snapshot().batches||[]).some(b=>b.status==='prepared'&&!b.manual&&now-Date.parse(b.cutoff)>=0&&now-Date.parse(b.cutoff)<=1800000);
const queued=this.store.all('batches').some(b=>b.status==='prepared'&&!b.manual&&now-Date.parse(b.cutoff)>=0&&now-Date.parse(b.cutoff)<=1800000);
if(!canPrepare&&!queued)return;
try{await this.mail.exclusive(config.channelId,async()=>{
if(!this.ready())return;
if(canPrepare&&!this.store.discoveryBlockers(cutoff).length){const window=windowForCutoff(cutoff,schedule,calendar);this.store.prepare(cutoff,'系统调度',window);}
// A frozen collection is immutable. Queue time is distinct from collection time.
const batches=(this.store.snapshot().batches||[]).filter(b=>b.status==='prepared'&&!b.manual&&now-Date.parse(b.cutoff)>=0&&now-Date.parse(b.cutoff)<=1800000);
const batches=this.store.all('batches').reverse().filter(b=>b.status==='prepared'&&!b.manual&&now-Date.parse(b.cutoff)>=0&&now-Date.parse(b.cutoff)<=1800000);
for(const batch of batches){if(!this.ready())break;
let expected;try{expected=windowForCutoff(batch.cutoff,schedule,calendar);}catch{continue;}
const legacyStart=new Date(Date.parse(batch.cutoff)+8*3600000).toISOString().slice(0,10)+'T00:00:00+08:00';
+9 -8
View File
@@ -3,15 +3,14 @@ const crypto=require('node:crypto');
const {canReadConnection,canReadOrder,canReadBatch}=require('./access.cjs');
const {fail}=require('./validation.cjs');
const {notifications,modeOf}=require('./delivery.cjs');
const cache=new WeakMap();
const {readStore,state:readState}=require('./read-context.cjs');
const orderStates=['candidate','identified','preparing','archived','pending','batched','blocked','unknown','sent','failed','capturing','archiving','queued','ignored'];
const batchStates=['collecting','prepared','sending','unknown','failed','sent','cancelled'];
function records(store){
const revision=store.queryRevision?.();
const saved=cache.get(store);
if(revision!==undefined&&saved?.revision===revision)return saved;
const memo=readState(store)?.memo,saved=memo?.get('records');if(saved)return saved;
const value={revision:revision??Date.now(),orders:store.all('orders'),batches:store.all('batches'),tasks:store.all('execution-tasks'),issues:store.all('business-issues')};
if(revision!==undefined)cache.set(store,value);
memo?.set('records',value);
return value;
}
function filters(input={},kind){
@@ -63,7 +62,8 @@ function visibleOrders(context,user,collectingGroups){
const rows=data.orders.filter(o=>classified(o,tasks.get(o.id))&&canReadOrder(context.workspace,user,o)).map(o=>orderRow(o,tasks.get(o.id)));
for(const task of data.tasks)if(!task.orderId&&!task.supersededBy&&classified(null,task)&&canReadConnection(context.workspace,user,task.connectionId))rows.push(orderRow(null,task));
const collecting=(collectingGroups||require('./collecting-batches.cjs').list(context.orderRules)).filter(b=>canReadBatch(context.workspace,user,b,context.orderRules));
for(const row of rows)row.collectingBatches=collecting.filter(b=>b.orderIds.includes(row.id)).map(b=>({id:b.id,subject:b.subject,cutoff:b.cutoff}));
const membership=new Map();for(const batch of collecting)for(const id of batch.orderIds){if(!membership.has(id))membership.set(id,[]);membership.get(id).push({id:batch.id,subject:batch.subject,cutoff:batch.cutoff});}
for(const row of rows)row.collectingBatches=membership.get(row.id)||[];
return rows;
}
function page(rows,input,revision){
@@ -112,14 +112,14 @@ function batchDetail(context,id,user){
return {...batchRow(context,batch),...pick(batch,['to','cc','text','html','window','sentAt','resolvedAt','resolution','manual','originalBatchId','template','signature','contentEdit','editor','edited','context','editable']),orders:(batch.orderIds||[]).map(id=>context.orderRules.get('orders',id)).filter(Boolean).map(o=>orderRow(o)),attachments:(batch.attachments||[]).map(a=>pick(a,['name','filename','size','sha256']))};
}
async function readOrderFile(context,id,index,user){
orderDetail(context,id,user);
orderDetail({...context,orderRules:readStore(context.orderRules)},id,user);
if(!Number.isSafeInteger(index)||index<0)fail('文件编号无效。');
const file=context.orderRules.get('orders',id)?.archive?.files?.[index];
if(!file||!Number.isSafeInteger(file.size)||!/^[a-f0-9]{64}$/i.test(file.sha256||''))fail('归档文件证据不完整。',409);
if(typeof context.execution?.archive?.read!=='function')fail('归档读取服务暂不可用。',503);
const bytes=await context.execution.archive.read(structuredClone(file));
// Ownership may change while storage performs an asynchronous read.
orderDetail(context,id,user);
orderDetail({...context,orderRules:readStore(context.orderRules)},id,user);
const current=context.orderRules.get('orders',id)?.archive?.files?.[index];
if(!current||current.sha256!==file.sha256||current.path!==file.path||current.size!==file.size)fail('归档证据已变化,请重新读取详情。',409);
if(!Buffer.isBuffer(bytes)||bytes.length!==file.size||bytes.subarray(0,5).toString()!=='%PDF-'||crypto.createHash('sha256').update(bytes).digest('hex')!==file.sha256)fail('归档文件读回校验失败。',409);
@@ -145,4 +145,5 @@ function summary(context,user){
result.revision=crypto.createHash('sha256').update(publicRevision(context,user)+JSON.stringify([result.window,result.issues])).digest('hex').slice(0,24);
return result;
}
module.exports={queryOrders,queryBatches,orderDetail,batchDetail,readOrderFile,summary};
const scoped=fn=>(context,...args)=>structuredClone(fn({...context,orderRules:readStore(context.orderRules)},...args));
module.exports={queryOrders:scoped(queryOrders),queryBatches:scoped(queryBatches),orderDetail:scoped(orderDetail),batchDetail:scoped(batchDetail),readOrderFile,summary:scoped(summary)};
+32
View File
@@ -0,0 +1,32 @@
'use strict';
const contextKey=Symbol('order-rules-read-context');
// This facade lives for one synchronous read only. Cached rows are internal,
// read-only values; public query boundaries copy their result before returning.
function readStore(store){
if(store[contextKey])return store;
const rows=new Map(),values=new Map(),indexes=new Map(),memo=new Map(),view=Object.create(store);
const state={memo,index(name,build){if(!indexes.has(name))indexes.set(name,build());return indexes.get(name);}};
Object.defineProperty(view,contextKey,{value:state});
view.all=function(kind){
if(!rows.has(kind)){
const result=store.all(kind);rows.set(kind,result);
let found=values.get(kind);if(!found)values.set(kind,found=new Map());for(const row of result)found.set(row.id,row);
}
// snapshot callers may reverse/sort the array, never the cached ordering.
return rows.get(kind).slice();
};
view.get=function(kind,id){
let found=values.get(kind);if(!found)values.set(kind,found=new Map());
if(!found.has(id))found.set(id,rows.has(kind)?null:store.get(kind,id));
return found.get(id);
};
for(const method of ['put','audit','transaction'])view[method]=()=>{throw new Error('Read context cannot write.');};
return view;
}
function state(store){return store?.[contextKey];}
function byOrder(store,kind,id){
const context=state(store);if(!context)return store.all(kind).filter(row=>row.orderId===id);
const index=context.index('order:'+kind,()=>{const map=new Map();for(const row of store.all(kind)){if(!map.has(row.orderId))map.set(row.orderId,[]);map.get(row.orderId).push(row);}return map;});
return index.get(id)||[];
}
module.exports={readStore,state,byOrder};
+12 -5
View File
@@ -17,6 +17,7 @@ const digest=value=>crypto.createHash('sha256').update(JSON.stringify(canonical(
const copy=value=>structuredClone(value);
const BASE_CAPABILITIES={liveTodo:false,pdfExport:false,automaticArchive:false};
function validDate(value){return typeof value==='string'&&/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/.test(value)&&Number.isFinite(Date.parse(value));}
function pendingCompanionState(order){const hui=delivery(order,'huizhou');return !!order?.archive&&order.ruleSnapshot?.huizhouEnabled===true&&['batched','sending','sent','unknown'].includes(order.status)&&!!hui&&['pending','blocked'].includes(hui.status)&&!hui.batchId&&!hui.missedWindow;}
class RuleStore{
constructor(dir,{clock=()=>new Date(),capabilities={},seedOverrides=[],schedule=()=>({times:['11:00','17:00'],weekends:false}),calendar=()=>[],desktopRoot=path.join(require('node:os').homedir(),'Desktop')}={}){
this.desktopRoot=desktopRoot;
@@ -45,6 +46,7 @@ class RuleStore{
}
}
});
require('../../shared/refresh-revisions.cjs').installRevisionTracking(this.db,[['records',"'records:' || $row.kind"]]);
}catch(error){try{this.db?.close();}catch{}this.vault?.destroy();throw error;}
}
now(){return this.clock().toISOString();}
@@ -113,13 +115,13 @@ class RuleStore{
if(issues.length)fail(issues.join(';'),409);
record.published={...copy(record.draft),status:'enabled',publishedAt:this.now()};record.mappingIssue=null;record.publicationSampleId=record.trialSampleId;record.publicationAdaptersHash=digest(record.published.adapterIds.map(id=>this.adapters().find(a=>a.id===id)));record.activationVersion=(record.activationVersion||0)+1;this.put('rules',record);
this.put('rule-history',{id:record.id+':'+record.draft.version,rule:copy(record.published),at:this.now(),actor});this.audit(actor,'发布规则',id+' v'+record.draft.version);
return this.snapshot().rules.find(r=>r.id===id);
return this.snapshot({includeRecords:false}).rules.find(r=>r.id===id);
});}
pause(id,input,actor){return this.transaction(()=>{
const record=this.get('rules',id);if(!record)fail('规则不存在。',404);
if(input?.version!==record.draft.version)fail('规则已变化,请刷新。',409);
if(input.activationVersion!==undefined&&input.activationVersion!==(record.activationVersion||0))fail('启停状态已变化,请刷新。',409);
if(record.published)record.published.status='paused';record.activationVersion=(record.activationVersion||0)+1;this.put('rules',record);this.audit(actor,'暂停规则',id);return this.snapshot().rules.find(r=>r.id===id);
if(record.published)record.published.status='paused';record.activationVersion=(record.activationVersion||0)+1;this.put('rules',record);this.audit(actor,'暂停规则',id);return this.snapshot({includeRecords:false}).rules.find(r=>r.id===id);
});}
resume(id,input,actor){return this.transaction(()=>{
const record=this.get('rules',id);if(!record?.published)fail('此分类尚未发布,请先保存并检查真实订单,再发布启用。',409);
@@ -132,7 +134,7 @@ class RuleStore{
const overlaps=this.all('rules').filter(r=>r.id!==id&&r.published?.status==='enabled'&&scopesOverlap(r.published,record.published));
if(overlaps.length)issues.push('与其他启用分类的流程节点冲突');
if(issues.length)fail(issues.join(';'),409);
record.published.status='enabled';record.activationVersion=(record.activationVersion||0)+1;this.put('rules',record);this.audit(actor,'启用已发布规则',id+' v'+record.published.version);return this.snapshot().rules.find(r=>r.id===id);
record.published.status='enabled';record.activationVersion=(record.activationVersion||0)+1;this.put('rules',record);this.audit(actor,'启用已发布规则',id+' v'+record.published.version);return this.snapshot({includeRecords:false}).rules.find(r=>r.id===id);
});}
matchingPublications(sample){
const rules=this.all('rules').map(r=>this.executionRule(r)).filter(Boolean);
@@ -158,12 +160,17 @@ class RuleStore{
return [...new Set(cutoffs.filter(cutoff=>cutoff&&now>=Date.parse(cutoff)&&now<=Date.parse(cutoff)+1800000))].sort();
}
pendingCompanion(order){
const hui=delivery(order,'huizhou'),normal=order?.batchId&&this.get('batches',order.batchId);
return !!order?.archive&&order.ruleSnapshot?.huizhouEnabled===true&&['batched','sending','sent','unknown'].includes(order.status)&&!!hui&&['pending','blocked'].includes(hui.status)&&!hui.batchId&&!hui.missedWindow&&normal?.huizhouPlanned===true&&modeOf(normal)==='normal'&&normal.orderIds?.includes(order.id)&&normal.cutoff===this.intakeWindow(order.sample||order.event,{includeExpired:true})?.end;
if(!pendingCompanionState(order))return false;
const normal=order.batchId&&this.get('batches',order.batchId);
return normal?.huizhouPlanned===true&&modeOf(normal)==='normal'&&normal.orderIds?.includes(order.id)&&normal.cutoff===this.intakeWindow(order.sample||order.event,{includeExpired:true})?.end;
}
expireIntakes(){return this.transaction(()=>{
const carry=require('./carry-forward.cjs');carry.advance(this);
for(const order of this.all('orders')){
// Only uncompleted normal work or an independent Hui companion can expire.
// Do this before intakeWindow's task lookup; keep carry advancement above
// and the persisted evidence checks below on the ordinary writable store.
if(!(['identified','preparing','archived','pending','blocked'].includes(order.status)&&!order.batchId&&!order.missedWindow)&&!pendingCompanionState(order))continue;
const window=this.intakeWindow(order.sample||order.event,{includeExpired:true});
if(!window||+this.clock()<=Date.parse(window.end)+1800000)continue;
if(this.pendingCompanion(order)&&!carry.hasCarry(this,order,'huizhou')){
+9 -1
View File
@@ -9,7 +9,15 @@ function taskIdentity(value){const item=identity(value);if(!item.source||!item.t
// A legacy row with no native portal source is ambiguous. Treat it as an
// overlapping namespace, never guess v4/v8 and create a second notification.
function sameTask(a,b){a=identity(a);b=identity(b);return !!a.source&&!!a.taskId&&a.source===b.source&&a.taskId===b.taskId&&(!a.portalSource||!b.portalSource||a.portalSource===b.portalSource);}
function records(store,kind,value){return store.all(kind).filter(row=>sameTask(row,value));}
function records(store,kind,value){
const context=require('./read-context.cjs').state(store);if(!context)return store.all(kind).filter(row=>sameTask(row,value));
const key=item=>JSON.stringify([item.source,item.taskId]),index=context.index('task:'+kind,()=>{
const groups=new Map();for(const row of store.all(kind)){const item=identity(row);if(!item.source||!item.taskId)continue;const k=key(item);if(!groups.has(k))groups.set(k,[]);groups.get(k).push(row);}return groups;
});
// Keep all portal variants: a legacy row without portalSource overlaps every
// native namespace, and lookup must still reject multiple matching records.
return (index.get(key(identity(value)))||[]).filter(row=>sameTask(row,value));
}
function lookup(store,kind,value){const rows=records(store,kind,value);if(rows.length>1)fail('同一通知任务存在多条旧记录,须人工核验,禁止新建或自动合并。',409);return rows[0]||null;}
function normalize(value){const row=structuredClone(value);for(const key of ['connectionId','source','portalSource','instanceId','taskId','revision'])if(row[key]!==undefined&&row[key]!==null)row[key]=text(row[key]);if(!text(row.revision))delete row.revision;return row;}
function fingerprint(value){const row=normalize(value);delete row.connectionId;return digest(row);}
+7 -7
View File
@@ -1,5 +1,6 @@
'use strict';
const {secureBpmTransport}=require('../bpm/api.cjs');
const {byteRange}=require('./files.cjs');
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
function payload(body,keys){if(!body||Object.keys(body).some(k=>!keys.includes(k)))fail('存储操作参数无效。');}
async function storageApi({storage,workspace,user,url,route,method,body,request,response,reply,trustedProxy}){
@@ -25,14 +26,13 @@ async function storageApi({storage,workspace,user,url,route,method,body,request,
if(action==='archive'&&method==='POST'){payload(body,['jobId','directory']);const result=await storage.archive(id,body.jobId,body.directory??'',user.username);audit('PDF 归档完成',result.relativePath);reply(200,result);return true;}
if(action==='preview-info'&&method==='GET'){reply(200,await storage.previewInfo(id,url.searchParams.get('path')||''));return true;}
if((action==='file'||action==='content')&&method==='GET'){
const preview=action==='content',file=await storage[preview?'readPreview':'readFile'](id,url.searchParams.get('path')||''),total=file.bytes.length;
const preview=action==='content',range=request.headers.range,file=await storage[preview?'readPreview':'readFile'](id,url.searchParams.get('path')||'',range===undefined?{}:{range}),total=file.total??file.bytes.length;
response.setHeader('Content-Type',preview?file.contentType:'application/octet-stream');response.setHeader('Content-Disposition',(preview?'inline':'attachment')+"; filename*=UTF-8''"+encodeURIComponent(file.filename));response.setHeader('Content-Security-Policy',"default-src 'none'; sandbox");response.setHeader('Cross-Origin-Resource-Policy','same-origin');response.setHeader('Accept-Ranges','bytes');
let start=0,end=total-1,status=200;
if(request.headers.range){const range=/^bytes=(\d*)-(\d*)$/.exec(request.headers.range);if(!range||(!range[1]&&!range[2])){response.setHeader('Content-Range','bytes */'+total);response.writeHead(416);response.end();return true;}
if(range[1]){start=Number(range[1]);if(range[2])end=Math.min(Number(range[2]),end);}else start=Math.max(0,total-Number(range[2]));
if(!Number.isSafeInteger(start)||!Number.isSafeInteger(end)||start>end||start>=total){response.setHeader('Content-Range','bytes */'+total);response.writeHead(416);response.end();return true;}status=206;response.setHeader('Content-Range',`bytes ${start}-${end}/${total}`);
}
const bytes=file.bytes.subarray(start,end+1);response.setHeader('Content-Length',bytes.length);response.writeHead(status);response.end(bytes);return true;
const {start,end,status}=byteRange(range,total);
if(file.total!==undefined&&(file.start!==start||file.end!==end||file.status!==status||file.bytes.length!==(status===416?0:end-start+1)))fail('存储分段响应无效。',502);
if(status===416){response.setHeader('Content-Range','bytes */'+total);response.writeHead(416);response.end();return true;}
if(status===206)response.setHeader('Content-Range',`bytes ${start}-${end}/${total}`);
const bytes=file.total===undefined?file.bytes.subarray(start,end+1):file.bytes;response.setHeader('Content-Length',bytes.length);response.writeHead(status);response.end(bytes);return true;
}
}
fail('没有找到此存储操作。',404);
+34 -8
View File
@@ -15,6 +15,22 @@ function segments(relative=''){
}
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('归档根目录超出共享目录。');}
@@ -45,16 +61,26 @@ class FileArea{
}
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){
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();if(!stat.isFile())throw fail('请选择要读取的文件。');if(stat.size>limit)throw fail('文件超过工作台读取上限。',413);
const buffer=Buffer.alloc(stat.size+1);let length=0;
while(length<buffer.length){const result=await handle.read(buffer,length,buffer.length-length,null);if(!result.bytesRead)break;length+=result.bytesRead;}
if(length>stat.size)throw fail('文件正在更新,请稍后重试。',409);
return {filename:path.basename(file),bytes:buffer.subarray(0,length)};
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){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);return {...info,bytes:await validatePreview({...info,bytes:file.bytes.length,canPreview:file.bytes.length<=info.limit},file.bytes)};}
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);
@@ -79,4 +105,4 @@ 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};
module.exports={FileArea,SmbClient,segments,inside,MAX_FILE,byteRange};
+3 -3
View File
@@ -1,6 +1,6 @@
'use strict';
const fs=require('node:fs/promises');const path=require('node:path');
const {SmbClient,segments,inside}=require('./files.cjs');
const {SmbClient,segments,inside,MAX_FILE}=require('./files.cjs');
const {orderFolder}=require('./order.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);
@@ -71,8 +71,8 @@ class StorageService{
mkdir(id,relative){return this.run(id,async (server,signal)=>this.operation(server,'mkdir',[relative],signal));}
readPdf(id,relative){return this.run(id,async (server,signal)=>this.operation(server,'readPdf',[relative],signal));}
previewInfo(id,relative){return this.run(id,async (server,signal)=>this.operation(server,'previewInfo',[relative],signal));}
readPreview(id,relative){return this.run(id,async (server,signal)=>this.operation(server,'readPreview',[relative],signal));}
readFile(id,relative){return this.run(id,async (server,signal)=>this.operation(server,'readFile',[relative],signal));}
readPreview(id,relative,options={}){return this.run(id,async (server,signal)=>this.operation(server,'readPreview',[relative,options],signal));}
readFile(id,relative,options={}){return this.run(id,async (server,signal)=>this.operation(server,'readFile',[relative,MAX_FILE,options],signal));}
archive(id,jobId,directory='',actor='自动归档'){
return this.run(id,async (server,signal)=>{
segments(directory);if(typeof jobId!=='string'||!jobId||jobId.length>200)throw fail('请选择已完成的 PDF 导出任务。');
+7
View File
@@ -17,6 +17,13 @@ function validate(operation,value){
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);
+1
View File
@@ -18,6 +18,7 @@ class StorageStore{
INSERT OR IGNORE INTO settings VALUES(1,'{"serverId":"","enabled":false,"since":null}');
CREATE TABLE IF NOT EXISTS archives(id TEXT PRIMARY KEY,server_id TEXT NOT NULL,job_id TEXT NOT NULL,status TEXT NOT NULL,value TEXT NOT NULL,UNIQUE(server_id,job_id));
UPDATE archives SET status='interrupted' WHERE status='running';`);
require('../../shared/refresh-revisions.cjs').installRevisionTracking(this.db,['servers','settings','archives']);
} catch(error) {
try { this.db?.close(); } catch {}
try { this.vault?.destroy(); } catch {}
+87
View File
@@ -0,0 +1,87 @@
'use strict';
const REPOSITORY_URL='https://git.simgreek.com/Skyworth_Digital_Hardware/order-notification-automation';
const RELEASES_API_URL='https://git.simgreek.com/api/v1/repos/Skyworth_Digital_Hardware/order-notification-automation/releases/latest';
const VERSION_PATTERN=/^[vV]?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
const MAX_RESPONSE_BYTES=256*1024;
function versionParts(value){
const match=typeof value==='string'&&value.length<=200&&VERSION_PATTERN.exec(value.trim());
if(!match)return null;
const pre=match[4]?match[4].split('.'):[];
if(pre.some(part=>/^0\d+$/.test(part)))return null;
return {major:BigInt(match[1]),minor:BigInt(match[2]),patch:BigInt(match[3]),pre};
}
function compareIdentifiers(a,b){
const an=/^\d+$/.test(a),bn=/^\d+$/.test(b);
if(an&&bn)return BigInt(a)>BigInt(b)?1:BigInt(a)<BigInt(b)?-1:0;
if(an!==bn)return an?-1:1;
return a>b?1:a<b?-1:0;
}
function compareVersions(left,right){
const a=versionParts(left),b=versionParts(right);
if(!a||!b)throw new Error('版本必须是 x.y.z 格式。');
for(const key of ['major','minor','patch'])if(a[key]!==b[key])return a[key]>b[key]?1:-1;
if(!a.pre.length&&!b.pre.length)return 0;
if(!a.pre.length)return 1;
if(!b.pre.length)return -1;
for(let i=0;i<Math.max(a.pre.length,b.pre.length);i++){
if(i>=a.pre.length)return -1;
if(i>=b.pre.length)return 1;
const result=compareIdentifiers(a.pre[i],b.pre[i]);
if(result)return result>0?1:-1;
}
return 0;
}
function safeReleaseUrl(value,repositoryUrl=REPOSITORY_URL){
try{
const url=new URL(value),base=new URL(repositoryUrl);
if(url.username||url.password||url.origin!==base.origin||!url.pathname.startsWith(base.pathname+'/releases/'))return '';
return url.href;
}catch{return '';}
}
function parseRelease(release,currentVersion,{repositoryUrl=REPOSITORY_URL}={}){
const base={currentVersion,latest:null};
if(!release||typeof release!=='object'||Array.isArray(release)||typeof release.tag_name!=='string')return {...base,status:'unavailable'};
const version=release.tag_name.trim().replace(/^v/i,''),parts=versionParts(version);
if(!parts)return {...base,status:'unavailable'};
if(release.draft===true||release.prerelease===true||parts.pre.length)return {...base,status:'none'};
if(compareVersions(version,currentVersion)<=0)return {...base,status:'current'};
const publishedAt=release.published_at?new Date(release.published_at):null;
return {status:'update-available',currentVersion,latest:{version,name:String(release.name||release.tag_name||version).slice(0,200),notes:String(release.body||'').slice(0,20000),url:safeReleaseUrl(release.html_url,repositoryUrl),publishedAt:publishedAt&&!Number.isNaN(publishedAt.getTime())?publishedAt.toISOString():null}};
}
async function readRelease(response){
const reader=response.body?.getReader();
if(!reader)throw Error('发行版本响应为空。');
const chunks=[];let bytes=0;
try{
while(true){
const {value,done}=await reader.read();if(done)break;
bytes+=value.byteLength;if(bytes>MAX_RESPONSE_BYTES)throw Error('发行版本响应过大。');
chunks.push(Buffer.from(value));
}
return JSON.parse(Buffer.concat(chunks,bytes).toString('utf8'));
}catch(error){await reader.cancel().catch(()=>{});throw error;}
finally{reader.releaseLock();}
}
function createUpdateChecker({currentVersion,fetchImpl=globalThis.fetch,apiUrl=RELEASES_API_URL,repositoryUrl=REPOSITORY_URL,timeoutMs=5000}={}){
if(!versionParts(currentVersion))throw new Error('当前版本必须是 x.y.z 格式。');
let inFlight=null;
async function readUpdate(){
const base={currentVersion,latest:null};
if(typeof fetchImpl!=='function')return {...base,status:'unavailable'};
const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),timeoutMs);
try{
const response=await fetchImpl(apiUrl,{headers:{Accept:'application/json'},redirect:'error',credentials:'omit',signal:controller.signal});
if(!response.ok){await response.body?.cancel();return {...base,status:response.status===404?'none':'unavailable'};}
return parseRelease(await readRelease(response),currentVersion,{repositoryUrl});
}catch{return {...base,status:'unavailable'};}
finally{clearTimeout(timer);}
}
return async function checkForUpdate(){
// Share only work still in progress; a later manual check always revalidates.
if(!inFlight)inFlight=readUpdate().finally(()=>{inFlight=null;});
return structuredClone(await inFlight);
};
}
module.exports={REPOSITORY_URL,RELEASES_API_URL,compareVersions,parseRelease,createUpdateChecker};
+1
View File
@@ -24,6 +24,7 @@ class WorkspaceStore {
delete item.detailUrl;if(item.checks)delete item.checks.detail;if(item.status==='partial')item.status='unchecked';
this.db.prepare('UPDATE connections SET value=? WHERE id=?').run(JSON.stringify(item),row.id);
}});
require('../../shared/refresh-revisions.cjs').installRevisionTracking(this.db,['connections','connection_archives','exceptions',['metadata',"'metadata:' || $row.key"]]);
} catch(error) {
try { this.db?.close(); } catch {}
throw error;