Initial team BPM workspace with managed connections, scanning and mail templates

This commit is contained in:
abaishu0730 committed 2026-10-16 22:34:11 +08:00
commit 34770ed338
101 files changed
+6499

No files matched your search

+73
View File
@@ -0,0 +1,73 @@
const fail=(status,message)=>{throw Object.assign(new Error(message),{status});};
const isLoopback=address=>['127.0.0.1','::1','::ffff:127.0.0.1'].includes(address);
function secureBpmTransport(request,trustedProxy=false){
if(request.socket.encrypted)return true;
if(!isLoopback(request.socket.remoteAddress))return false;
if(trustedProxy && request.headers['x-forwarded-proto']==='https')return true;
try{const host=new URL('http://'+request.headers.host);return ['localhost','127.0.0.1','[::1]'].includes(host.hostname) && !host.username && !host.password && host.pathname==='/' && !host.search && !host.hash;}catch{return false;}
}
function authorizeConnection(connection,user){
if(user?.role!=='admin' && !(user?.role==='operator' && connection.owner===user.username))fail(403,'仅连接负责人或管理员可以操作此连接。');
}
function emptyBody(body){if(!body || Object.keys(body).length)fail(400,'此操作不接受额外数据。');}
async function managerCall(work){
try{return await work();}catch(error){
if(error?.status===409&&error.code==='BPM_ACCOUNT_DUPLICATE')fail(409,'该 BPM 账号已开启自动续登,请使用已有连接或先解除原账号托管。');
const messages={400:'登录操作数据不正确。',403:'没有操作此登录会话的权限。',404:'登录会话不存在,请重新打开。',409:'登录会话正被使用或不可操作,请刷新后重试。',410:'登录会话已过期,请重新打开。',429:'登录窗口已达到上限,请稍后重试。',503:'BPM 登录服务暂不可用,请稍后重试。'};
const status=messages[error?.status]?error.status:502;fail(status,messages[status] || 'BPM 暂时无法连接,请稍后重试。');
}
}
async function bpmApi({workspace,bpmSessions,user,sessionId,route,method,body,request,response,reply,trustedProxy=false}){
const match=/^\/api\/connections\/([\w-]+)\/(?:login\/(open|frame|input|navigate|save|close|fill-account)|(check|disable|delete)|(account)(\/(?:clear|check))?)$/.exec(route);
if(!match || !workspace)return false;
const [,id,login,other,account,suffix]=match;const action=login || other || (suffix==='/clear'?'clear-account':suffix==='/check'?'check-account':account);
if(action==='account'?!['GET','POST'].includes(method):method!==(action==='frame'?'GET':'POST'))fail(405,'此操作不支持当前请求方式。');
const connection=workspace.getConnection(id);authorizeConnection(connection,user);
if(action==='delete'){
if(user.role!=='admin')fail(403,'仅管理员可以删除连接。');emptyBody(body);
if(connection.status!=='disabled')fail(409,'请先停用连接再删除。');
if(!bpmSessions)fail(503,'BPM 登录服务暂不可用,请稍后重试。');
await managerCall(()=>bpmSessions.disable(id));reply(200,workspace.deleteConnection(id,user));return true;
}
if(action==='disable'){
if(user.role!=='admin')fail(403,'仅管理员可以停用连接。');emptyBody(body);
if(bpmSessions)await managerCall(()=>bpmSessions.disable(id));reply(200,workspace.disableConnection(id,user));return true;
}
if(connection.status==='disabled')fail(409,'此连接已停用。');
if(!secureBpmTransport(request,trustedProxy))fail(403,'请在部署机本地或 HTTPS 页面中登录 BPM。');
if(!bpmSessions)fail(503,'BPM 登录服务暂不可用。');
const principal={user,sessionId};
if(action==='check-account'){
const value=await managerCall(()=>bpmSessions.checkAccount(connection,principal,body));reply(200,{available:value.available===true});return true;
}
if(!['frame','input','navigate','account'].includes(action))emptyBody(body);
if(action==='account' || action==='clear-account'){
const saving=action==='account' && method==='POST';
const previous=saving?await managerCall(()=>bpmSessions.account(connection,principal)):null;
const value=await managerCall(()=>bpmSessions[action==='clear-account'?'clearAccount':saving?'saveAccount':'account'](connection,principal,body));
let checked;
if(saving && previous.configured && previous.username!==value.username)workspace.resetConnectionSession(id,user);
if(saving || action==='clear-account')workspace.record(user,saving?'bpm.account.save':'bpm.account.clear',connection.name);
if(saving){
try{const result=await managerCall(()=>bpmSessions.ensure(workspace.getConnection(id),principal));checked=workspace.updateConnectionSession(id,result,user);}
catch(error){if(error.status!==409)throw error;checked=workspace.getConnection(id);}
}
reply(200,{configured:value.configured===true,username:typeof value.username==='string'?value.username:'',updatedAt:typeof value.updatedAt==='string'?value.updatedAt:null,...(saving?{connection:checked}:{})});return true;
}
if(action==='fill-account'){
const value=await managerCall(()=>bpmSessions.fillAccount(connection,principal));reply(200,{filled:value.filled===true,message:typeof value.message==='string'?value.message:''});return true;
}
if(action==='frame'){
const bytes=await managerCall(()=>bpmSessions.frame(id,principal));
if(!Buffer.isBuffer(bytes))fail(502,'登录画面暂不可用。');
response.writeHead(200,{'Content-Type':'image/jpeg'});response.end(bytes);return true;
}
if(action==='save' || action==='check'){
const result=await managerCall(()=>bpmSessions[action](connection,principal));reply(200,workspace.updateConnectionSession(id,result,user));return true;
}
const value=await managerCall(()=>bpmSessions[action](action==='open'?connection:id,principal,body));
if(action==='open')reply(200,{active:value.active===true,viewport:{width:value.viewport?.width,height:value.viewport?.height},expiresAt:value.expiresAt,host:value.host});
else reply(200,{ok:true});
return true;
}
module.exports={bpmApi,secureBpmTransport};
+34
View File
@@ -0,0 +1,34 @@
const crypto=require('node:crypto');
class BpmCustodian {
constructor({workspace,manager,intervalMs=5*60*1000}){
this.workspace=workspace;this.manager=manager;this.intervalMs=intervalMs;this.stopped=false;this.running=null;
this.principal={user:{id:'bpm-custodian',username:'系统托管',role:'admin'},sessionId:'custodian:'+crypto.randomBytes(24).toString('hex')};
}
start(){if(this.timer || this.stopped)return;this.timer=setInterval(()=>{this.tick().catch(()=>{});},this.intervalMs);this.timer.unref?.();this.tick().catch(()=>{});}
tick(){
if(this.stopped || this.running)return Promise.resolve();
this.running=this.checkAll().finally(()=>{this.running=null;});return this.running;
}
async checkAll(){
const connections=this.workspace.snapshot().connections;
for(const candidate of connections){
if(this.stopped)break;
if(candidate.status==='disabled')continue;
try{
const connection=this.workspace.getConnection(candidate.id);
if(connection.status==='disabled')continue;
const account=await this.manager.account(connection,this.principal);
if(!account.configured && !connection.lastConnectedAt && !['connected','unchecked','login_required'].includes(connection.status))continue;
const result=await this.manager.ensure(connection,this.principal);
// The connection can be disabled while its remote check is in flight.
if(this.workspace.getConnection(connection.id).status!=='disabled')this.workspace.updateConnectionSession(connection.id,result,this.principal.user);
}catch(cause){
// Interactive leases and transient browser failures are retried on the next cycle.
// The manager returns checked upstream failures as structured results.
if(![403,404,409,429].includes(cause.status))this.lastErrorAt=new Date().toISOString();
}
}
}
async stop(){this.stopped=true;clearInterval(this.timer);this.timer=null;await this.running;}
}
module.exports={BpmCustodian};
+57
View File
@@ -0,0 +1,57 @@
'use strict';
const sanitize=require('sanitize-html');
const {loadPlaywright}=require('./runtime.cjs');
const fail=(message,status=502)=>Object.assign(new Error(message),{status});
const SOURCES=[['portal-v8','bpm/worklist/informlist'],['portal-v4','skyworth/todo/v2/workflow/get_process_of_inform_v4']];
function plain(value,max=8000){
const text=sanitize(String(value??''),{allowedTags:[],allowedAttributes:{}}).replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi,(m,key)=>{
if(key[0]==='#'){const n=key[1].toLowerCase()==='x'?parseInt(key.slice(2),16):+key.slice(1);return n>0&&n<=0x10ffff?String.fromCodePoint(n):'';}
return {amp:'&',lt:'<',gt:'>',quot:'"',apos:"'",nbsp:' '}[key.toLowerCase()];
});return text.replace(/\s+/g,' ').trim().slice(0,max);
}
function normalizeArrival(row,source){
if(!row||typeof row!=='object'||!['string','number'].includes(typeof row.taskId)||!String(row.taskId)||String(row.taskId).length>200)throw fail('BPM 列表缺少有效的任务标识。');
const raw=row.startTime;
if(typeof raw!=='string'||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})?$/.test(raw))throw fail('BPM 列表缺少有效的流程到达时间。');
const day=raw.slice(0,10),valid=new Date(day+'T00:00:00Z');
if(Number.isNaN(+valid)||valid.toISOString().slice(0,10)!==day)throw fail('BPM 流程到达日期无效。');
const date=new Date(/(?:Z|[+-]\d{2}:\d{2})$/.test(raw)?raw:raw+'+08:00');
if(Number.isNaN(+date))throw fail('BPM 流程到达时间无效。');
const arrivedAt=date.toISOString(),arrivalDay=new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(date);
return {source,taskId:String(row.taskId),serialNum:plain(row.serialNum,250),processName:plain(row.processName,250),activityName:plain(row.activityName,250),subject:plain(row.processInstanceSubject),initiator:plain(row.processInstanceInitiatorShortName||row.processInstanceInitiator,250),arrivedAt,arrivalDay};
}
class BpmListClient{
constructor({baseURL='https://bpmn.skyworthdigital.com/',pageSize=100,allowLocal=false}={}){
const u=new URL(baseURL);if(u.href!=='https://bpmn.skyworthdigital.com/'&&!(allowLocal&&['127.0.0.1','localhost','[::1]'].includes(u.hostname)&&['http:','https:'].includes(u.protocol)&&u.pathname==='/'&&!u.username&&!u.password&&!u.search&&!u.hash))throw fail('BPM 地址不受支持。',400);
this.baseURL=u.href;this.pageSize=pageSize;
}
async scan(storageState){
if(!storageState)throw fail('BPM 会话需要续登。',401);
const request=await loadPlaywright().request.newContext({baseURL:this.baseURL,storageState,timeout:20000});
const get=async(route,options={})=>{
let response;try{response=await request.get(route,{...options,maxRedirects:0});}catch{throw fail('BPM 查询连接失败,请稍后重试。');}
const status=response.status();if(status>=300&&status<400)throw fail('BPM 查询发生登录跳转,需要续登。',401);
if([401,403].includes(status))throw fail('BPM 会话需要续登。',401);
if(status!==200)throw fail('BPM 查询失败,请稍后重试。');
const body=await response.body();if(body.length>10*1024*1024)throw fail('BPM 查询响应过大。');return body.toString('utf8');
};
try{
const html=await get('/'),token=/Yiez\.clientId\s*=\s*['"]([^'"\s<>]{1,16000})['"]/.exec(html)?.[1];
if(!token)throw fail('BPM 会话需要续登。',401);
const rows=[];
for(const [source,route]of SOURCES){
let total=null;const seen=new Set();
for(let page=1;page<=100;page++){
let data;try{data=JSON.parse(await get(route,{params:{page,start:(page-1)*this.pageSize,limit:this.pageSize},headers:{Authorization:'Bearer '+token}}));}catch(cause){if(cause.status)throw cause;throw fail('BPM 列表数据格式不正确。');}
if(!Array.isArray(data.children)||!Number.isSafeInteger(data.total)||data.total<0||data.total>10000||data.success===false)throw fail('BPM 列表分页数据不完整。');
if(total!==null&&total!==data.total)throw fail('BPM 列表正在变化,请重新扫描。');total=data.total;
for(const raw of data.children){const row=normalizeArrival(raw,source);if(seen.has(row.taskId))throw fail('BPM 列表分页重复,请重新扫描。');seen.add(row.taskId);rows.push(row);}
if(seen.size===total)break;
if(!data.children.length||data.children.length>this.pageSize||seen.size>total||page===100)throw fail('BPM 列表分页不完整,请重新扫描。');
}
}
return rows;
}finally{await request.dispose();}
}
}
module.exports={BpmListClient,normalizeArrival};
+23
View File
@@ -0,0 +1,23 @@
'use strict';
async function bpmScanApi({scanner,workspace,user,sessionId,url,route,method,body,reply}){
if(!route.startsWith('/api/bpm-scan')&&route!=='/api/arrivals')return false;
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
if(!scanner)fail('BPM 扫描暂不可用。',503);
if(route==='/api/arrivals'&&method==='GET'){
const filters={connectionId:url.searchParams.get('connectionId')||'',q:url.searchParams.get('q')||'',before:url.searchParams.get('before')||'',days:Number(url.searchParams.get('days')||7)};
reply(200,scanner.store.list(filters));return true;
}
if(route==='/api/bpm-scan'&&method==='GET'){reply(200,{...scanner.store.status(),connections:workspace.snapshot().connections.map(({id,name,status,owner})=>({id,name,status,owner}))});return true;}
if(route==='/api/bpm-scan/config'&&method==='POST'){
if(user.role!=='admin')fail('仅管理员可以配置自动扫描。',403);
const config=scanner.store.saveConfig(body);workspace.record(user,'保存自动扫描',`${config.enabled?'开启':'暂停'},间隔 ${config.intervalMinutes} 分钟`);reply(200,config);return true;
}
if(route==='/api/bpm-scan/run'&&method==='POST'){
if(!body||Object.keys(body).some(k=>k!=='connectionId')||typeof body.connectionId!=='string')fail('请选择 BPM 连接。');
// A scan may span many pages. The UI polls the durable run instead of holding a request open.
const {promise,runId}=scanner.startScan(body.connectionId,{user,sessionId});
promise.catch(()=>{});reply(202,{runId});return true;
}
return false;
}
module.exports={bpmScanApi};
+36
View File
@@ -0,0 +1,36 @@
'use strict';
const fs=require('node:fs');const path=require('node:path');const crypto=require('node:crypto');const {DatabaseSync}=require('node:sqlite');
const invalid=message=>Object.assign(new Error(message),{status:400});
class BpmScanStore{
constructor(dir){fs.mkdirSync(dir,{recursive:true});this.db=new DatabaseSync(path.join(dir,'scan.sqlite'));this.db.exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL;
CREATE TABLE IF NOT EXISTS config(id INTEGER PRIMARY KEY CHECK(id=1),value TEXT NOT NULL);
INSERT OR IGNORE INTO config VALUES(1,'{"enabled":true,"intervalMinutes":5}');
CREATE TABLE IF NOT EXISTS arrivals(connection_id TEXT NOT NULL,source TEXT NOT NULL,task_id TEXT NOT NULL,day TEXT NOT NULL,value TEXT NOT NULL,first_seen TEXT NOT NULL,last_seen TEXT NOT NULL,PRIMARY KEY(connection_id,source,task_id));
CREATE INDEX IF NOT EXISTS arrivals_day ON arrivals(day DESC);
CREATE TABLE IF NOT EXISTS runs(id TEXT PRIMARY KEY,connection_id TEXT NOT NULL,actor TEXT NOT NULL,started_at TEXT NOT NULL,finished_at TEXT,status TEXT NOT NULL,seen INTEGER,added INTEGER,message TEXT);
UPDATE runs SET status='error',message='服务重启,扫描未完成。',finished_at=CURRENT_TIMESTAMP WHERE status='running';`);}
transaction(fn){this.db.exec('BEGIN IMMEDIATE');try{const r=fn();this.db.exec('COMMIT');return r;}catch(e){this.db.exec('ROLLBACK');throw e;}}
config(){return JSON.parse(this.db.prepare('SELECT value FROM config WHERE id=1').get().value);}
saveConfig(input){if(!input||Object.keys(input).some(k=>!['enabled','intervalMinutes'].includes(k))||typeof input.enabled!=='boolean'||!Number.isInteger(input.intervalMinutes)||input.intervalMinutes<1||input.intervalMinutes>1440)throw invalid('扫描间隔需为 1–1440 分钟。');this.db.prepare('UPDATE config SET value=? WHERE id=1').run(JSON.stringify(input));return this.config();}
begin(connectionId,actor){const id=crypto.randomUUID();this.db.prepare('INSERT INTO runs(id,connection_id,actor,started_at,status) VALUES(?,?,?,?,?)').run(id,connectionId,actor,new Date().toISOString(),'running');return id;}
complete(id,connectionId,rows){return this.transaction(()=>{
let added=0;const now=new Date().toISOString();
const insert=this.db.prepare('INSERT OR IGNORE INTO arrivals VALUES(?,?,?,?,?,?,?)');const update=this.db.prepare('UPDATE arrivals SET day=?,value=?,last_seen=? WHERE connection_id=? AND source=? AND task_id=?');
for(const row of rows){if(!row.arrivalDay||!row.taskId||!row.source)throw invalid('流程记录无效。');const value=JSON.stringify(row);added+=Number(insert.run(connectionId,row.source,row.taskId,row.arrivalDay,value,now,now).changes);update.run(row.arrivalDay,value,now,connectionId,row.source,row.taskId);}
this.db.prepare('UPDATE runs SET status=?,finished_at=?,seen=?,added=?,message=? WHERE id=? AND status=?').run('success',now,rows.length,added,'',id,'running');this.prune();return {seen:rows.length,added};
});}
fail(id,message){this.db.prepare('UPDATE runs SET status=?,finished_at=?,message=? WHERE id=?').run('error',new Date().toISOString(),message,id);this.prune();}
prune(){this.db.exec("DELETE FROM runs WHERE status!='running' AND id NOT IN(SELECT id FROM runs ORDER BY started_at DESC,rowid DESC LIMIT 200)");}
status(){return {config:this.config(),total:this.db.prepare('SELECT COUNT(*) n FROM arrivals').get().n,runs:this.db.prepare('SELECT id,connection_id AS connectionId,actor,started_at AS startedAt,finished_at AS finishedAt,status,seen,added,message FROM runs ORDER BY started_at DESC,rowid DESC LIMIT 30').all()};}
list({connectionId='',q='',before='',days=7}={}){
if(typeof q!=='string'||q.length>200||typeof connectionId!=='string'||connectionId.length>200||typeof before!=='string'||(before&&!/^\d{4}-\d{2}-\d{2}$/.test(before))||!Number.isInteger(days)||days<1||days>31)throw invalid('查询条件无效。');
const conditions=[],args=[];if(connectionId){conditions.push('connection_id=?');args.push(connectionId);}if(q){conditions.push("value LIKE ? ESCAPE '\\'");args.push('%'+q.replace(/[\\%_]/g,'\\$&')+'%');}
const where=conditions.length?' WHERE '+conditions.join(' AND '):'';const total=this.db.prepare('SELECT COUNT(*) n FROM arrivals'+where).get(...args).n;
if(before){conditions.push('day<?');args.push(before);}const filtered=conditions.length?' WHERE '+conditions.join(' AND '):'';
const dates=this.db.prepare('SELECT DISTINCT day FROM arrivals'+filtered+' ORDER BY day DESC LIMIT ?').all(...args,days+1).map(r=>r.day);const shown=dates.slice(0,days);
const groups=shown.map(day=>({day,items:this.db.prepare('SELECT connection_id AS connectionId,value,first_seen AS firstSeenAt,last_seen AS lastSeenAt FROM arrivals'+(filtered?filtered+' AND ':' WHERE ')+'day=? ORDER BY json_extract(value,\'$.arrivedAt\') DESC,task_id').all(...args,day).map(({value,...rest})=>({...JSON.parse(value),...rest}))}));
return {total,groups,nextBefore:dates.length>days?shown.at(-1):null};
}
close(){this.db.close();}
}
module.exports={BpmScanStore};
+28
View File
@@ -0,0 +1,28 @@
'use strict';
const crypto=require('node:crypto');const {dayPolicy}=require('./schedule.cjs');
const fail=(message,status)=>Object.assign(new Error(message),{status});
class BpmScanner{
constructor({store,workspace,manager,settings,clock=()=>new Date()}){Object.assign(this,{store,workspace,manager,settings,clock});this.pending=new Map();this.stopped=false;this.lastTick=0;this.principal={user:{username:'系统扫描',role:'admin'},sessionId:'scan:'+crypto.randomUUID()};}
start(){if(this.timer||this.stopped)return;this.timer=setInterval(()=>this.tick().catch(()=>{}),15000);this.timer.unref?.();this.tick().catch(()=>{});}
async scan(id,principal){return this.startScan(id,principal).promise;}
startScan(id,principal){
if(this.stopped)throw fail('扫描服务正在关闭。',503);const connection=this.workspace.getConnection(id);
if(!principal?.sessionId||!['admin','operator'].includes(principal.user?.role)||(principal.user.role!=='admin'&&connection.owner!==principal.user.username))throw fail('只有连接负责人或管理员可以扫描。',403);
if(connection.status==='disabled')throw fail('此 BPM 连接已停用。',409);
if(this.pending.has(id))throw fail('此连接正在扫描,请稍后查看结果。',409);
const runId=this.store.begin(id,principal.user.username);
const operation=Promise.resolve().then(async()=>{
try{const rows=await this.manager.scanArrivals(connection,principal);if(this.workspace.getConnection(id).status==='disabled')throw fail('此 BPM 连接已停用。',409);return {...this.store.complete(runId,id,rows),runId};}
catch(cause){this.store.fail(runId,cause.status?cause.message:'BPM 扫描失败,请稍后重试。');throw cause;}
}).finally(()=>this.pending.delete(id));this.pending.set(id,operation);return {promise:operation,runId};
}
tick(){if(this.stopped||this.ticking)return Promise.resolve();this.ticking=this.checkAll().finally(()=>{this.ticking=null;});return this.ticking;}
async checkAll(){
const config=this.store.config(),now=this.clock();if(!config.enabled||+now-this.lastTick<config.intervalMinutes*60000)return;
const snapshot=this.workspace.snapshot();if(!dayPolicy(now,this.settings().schedule,snapshot.calendar.overrides).scan)return;
this.lastTick=+now;
for(const connection of snapshot.connections){if(this.stopped)break;if(connection.status==='disabled'||(!connection.lastConnectedAt&&connection.status!=='connected')||this.pending.has(connection.id))continue;try{await this.scan(connection.id,this.principal);}catch{}}
}
async stop(){this.stopped=true;clearInterval(this.timer);await this.ticking;await Promise.allSettled([...this.pending.values()]);}
}
module.exports={BpmScanner};
+417
View File
@@ -0,0 +1,417 @@
'use strict';
const fs = require('node:fs');
const path = require('node:path');
const { BpmVault } = require('./bpm-vault.cjs');
const { loadPlaywright, browserOptions } = require('./runtime.cjs');
const { BpmListClient } = require('./bpm-list-client.cjs');
const DEFAULT_URLS = { main: 'https://bpmn.skyworthdigital.com/' };
const LOGIN_FORMS = {
'https://sso.skyworthdigital.com': { username:'#username', password:'#password', submit:'#kc-form-login button[type="submit"]', form:'#kc-form-login', actionPath:'/realms/skyworthdigital/login-actions/authenticate' }
};
const TTL = 10 * 60 * 1000;
const KEYS = new Set(['Tab','Enter','Backspace','Delete','ArrowUp','ArrowDown','ArrowLeft','ArrowRight','Home','End','Escape','Control+A']);
const error = (message, status = 400) => Object.assign(new Error(message), { status });
const safe = cause => cause?.status ? cause : error('BPM 浏览器暂不可用,请重试。', 503);
const object = (value, fields) => value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).every(key => fields.includes(key));
class BpmSessionManager {
constructor({ stateDir, browserFactory, urls, allowedOrigins, probe, loginForms } = {}) {
this.stateDir = path.resolve(stateDir); fs.mkdirSync(this.stateDir, { recursive: true });
if (urls!==undefined && !object(urls,['main'])) throw error('BPM 地址配置无效。');
this.urls = { ...DEFAULT_URLS, ...urls };
this.allowedOrigins = new Set(Object.values(DEFAULT_URLS).map(url => new URL(url).origin));
this.allowedOrigins.add('https://sso.skyworthdigital.com');
if (allowedOrigins) {
// Injection exists only for local integration fixtures; it cannot widen production's external allowlist.
for (const origin of allowedOrigins) {
const parsed = new URL(origin);
if (!['localhost','127.0.0.1','[::1]'].includes(parsed.hostname) || !['http:','https:'].includes(parsed.protocol) || parsed.origin !== origin) throw error('测试域名必须为本机地址。');
this.allowedOrigins.add(origin);
}
}
for (const target of Object.values(this.urls)) if (!this.allowed(target)) throw error('BPM 地址不在允许范围内。',403);
this.loginForms = { ...LOGIN_FORMS };
// Only local fixtures may register additional forms; callers cannot replace company forms.
for (const [origin,form] of Object.entries(loginForms || {})) {
const parsed = new URL(origin);
if (!['localhost','127.0.0.1','[::1]'].includes(parsed.hostname) || !this.allowedOrigins.has(origin) || parsed.origin!==origin || !object(form,['username','password','submit']) || !['username','password'].every(key=>typeof form[key]==='string' && /^#[a-zA-Z_][\w-]*$/.test(form[key])) || (form.submit!==undefined && !/^#[a-zA-Z_][\w-]*$/.test(form.submit))) throw error('测试登录表单无效。');
this.loginForms[origin] = { ...form };
}
this.browserFactory = browserFactory || (() => loadPlaywright().chromium.launch(browserOptions()));
this.probe = probe || this.defaultProbe.bind(this);
this.sessions = new Map(); this.operations = new Map(); this.disabled = new Set(); this.stopped = false;
}
allowed(url) { try { const parsed = new URL(url); return !parsed.username && !parsed.password && this.allowedOrigins.has(parsed.origin); } catch { return false; } }
vault() { return this._vault ||= new BpmVault({ stateDir: this.stateDir }); }
accountMetadata(stored) { return stored ? {configured:true,username:stored.username,updatedAt:stored.updatedAt} : {configured:false,username:'',updatedAt:null}; }
async migrateAccounts(connections) { await this.vault().migrateAccounts(connections.map(connection=>connection.id)); }
async checkAccount(connection,principal,input) {
return this.run(connection?.id,async()=>{this.authorize(connection,principal);if(!object(input,['username'])||typeof input.username!=='string'||!input.username.trim()||input.username.length>150)throw error('请输入有效的 BPM 账号。');return this.vault().accountAvailability(connection.id,input.username);});
}
async account(connection,principal) {
return this.run(connection?.id,async()=>{ this.authorize(connection,principal); return this.accountMetadata(await this.vault().read('account:'+connection.id)); });
}
async saveAccount(connection,principal,credentials) {
return this.run(connection?.id,async()=>{
this.authorize(connection,principal);
if (!object(credentials,['username','password']) || typeof credentials.username!=='string' || !credentials.username.trim() || credentials.username.length>150 || typeof credentials.password!=='string' || !credentials.password || credentials.password.length>256) throw error('请输入有效的 BPM 账号和密码。');
const lease=this.sessions.get(connection.id);
if (lease && lease.sessionId!==principal.sessionId) throw error('此连接正在另一登录窗口中使用。',409);
const stored={username:credentials.username.trim(),password:credentials.password,updatedAt:new Date().toISOString()};
const previous=await this.vault().read('account:'+connection.id);
// A password rotation retains valid cookies. Only an actual account change revokes
// authentication; first custody can reuse a user's already saved manual login.
await this.vault().write('account:'+connection.id,stored);
if (previous && previous.username.trim().toLowerCase()!==stored.username.toLowerCase()) {
try{await this.vault().remove(connection.id);await this.closeLease(connection.id);}
catch(cause){await this.vault().write('account:'+connection.id,previous);throw cause;}
}
return this.accountMetadata(stored);
});
}
async clearAccount(connection,principal) {
return this.run(connection?.id,async()=>{ this.authorize(connection,principal); await this.vault().remove('account:'+connection.id); return this.accountMetadata(null); });
}
async fillSavedAccount(lease) {
const stored=await this.vault().read('account:'+lease.id);
if (!stored) return {filled:false,message:'请先保存托管账号。'};
const origin=new URL(lease.page.url()).origin, form=this.loginForms[origin];
if (!form || lease.blocked) return {filled:false,message:'请打开支持的 BPM 登录页面。'};
try {
await Promise.all([lease.page.locator(form.username).waitFor({state:'visible',timeout:1500}),lease.page.locator(form.password).waitFor({state:'visible',timeout:1500})]);
// Validate and set both values in one browser task: a navigation or DOM replacement
// between separate locator.fill calls must never redirect a secret to another field.
const filled=await lease.page.evaluate(({origin,form,username,password})=>{
if (location.origin!==origin || window!==window.top) return false;
const user=document.querySelector(form.username), secret=document.querySelector(form.password);
const usable=(node,type)=>node instanceof HTMLInputElement && node.type===type && !node.disabled && !node.readOnly && node.getClientRects().length>0 && getComputedStyle(node).visibility==='visible' && getComputedStyle(node).display!=='none';
if (!usable(user,'text') || !usable(secret,'password') || user===secret) return false;
const set=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set;
set.call(user,username);set.call(secret,password);
for (const node of [user,secret]) { node.dispatchEvent(new Event('input',{bubbles:true})); node.dispatchEvent(new Event('change',{bubbles:true})); }
return true;
},{origin,form,username:stored.username,password:stored.password});
return {filled,message:filled?'已填入托管账号,请完成登录。':'请打开支持的 BPM 登录表单。'};
} catch { return {filled:false,message:'请等待登录表单显示后重试。'}; }
}
async fillAccount(connection,principal) {
return this.run(connection?.id,async()=>{ this.authorize(connection,principal); const lease=await this.getLease(connection.id,principal,true); await this.settleNavigation(lease); return this.fillSavedAccount(lease); });
}
async automaticSubmit(lease,stored,submit=false) {
const origin=new URL(lease.page.url()).origin, form=this.loginForms[origin];
if (!form?.submit || lease.blocked) return false;
return lease.page.evaluate(({origin,form,stored,submit})=>{
if (location.origin!==origin || window!==window.top) return false;
const visible=node=>!!node && node.getClientRects().length>0 && getComputedStyle(node).visibility==='visible' && getComputedStyle(node).display!=='none';
const user=document.querySelector(form.username),secret=document.querySelector(form.password),button=document.querySelector(form.submit);
if (!(user instanceof HTMLInputElement) || user.type!=='text' || !visible(user) || user.disabled || user.readOnly || !(secret instanceof HTMLInputElement) || secret.type!=='password' || !visible(secret) || secret.disabled || secret.readOnly || !visible(button) || button.disabled || button.type!=='submit') return false;
const login=user.form;
if (!login || secret.form!==login || button.form!==login || login.method.toLowerCase()!=='post' || (form.form && !login.matches(form.form))) return false;
if ((button.getAttribute('formmethod') || login.method).toLowerCase()!=='post' || !['','_self'].includes(button.getAttribute('formtarget') || login.target)) return false;
const action=new URL(button.getAttribute('formaction') || login.action,location.href);
if (action.origin!==origin || (form.actionPath && action.pathname!==form.actionPath)) return false;
// Any additional visible field or challenge requires the user's intervention.
const challenge=/captcha|recaptcha|hcaptcha|turnstile|otp|one.?time|totp|verification|verify.?code/i;
if (Array.from(document.querySelectorAll('input,iframe,img,[id],[class]')).some(node=>visible(node) && challenge.test([node.id,node.className,node.getAttribute('name'),node.getAttribute('autocomplete'),node.getAttribute('src'),node.getAttribute('title')].join(' ')))) return false;
if (Array.from(login.elements).some(node=>visible(node) && node!==user && node!==secret && !['submit','button','hidden','reset'].includes(node.type))) return false;
if (submit) {
const set=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set;
set.call(user,stored.username);set.call(secret,stored.password);
button.click();
}
return true;
},{origin,form,stored:{username:stored.username,password:stored.password},submit}).catch(()=>false);
}
async persistLease(lease) {
await this.captureSessions(lease);
const storageState=await lease.context.storageState({indexedDB:true});
await this.vault().write(lease.id,{storageState,sessionStorage:lease.sessionStorage});
}
canPersistVerified(result) {
return result.status==='connected' && result.checks.portal.ok;
}
async ensure(connection,principal) {
return this.run(connection?.id,async()=>{
this.authorize(connection,principal);
if (this.sessions.has(connection.id)) throw error('此连接正在登录窗口中使用。',409);
const lease=await this.create(connection,principal);
try {
let result=await this.verify(lease);
this.authorize(connection,principal);
if (this.canPersistVerified(result)) await this.persistLease(lease);
if (result.status==='connected') return result;
// Network failures and a healthy portal never justify submitting credentials again.
if (result.status!=='login_required' || result.checks.portal.message!=='请在此入口完成登录。' || lease.blocked) return result;
const stored=await this.vault().read('account:'+connection.id);
if (!stored) return result;
const manual=message=>{ if (!result.checks.portal.ok) result.checks.portal.message=message; return result; };
if (Date.parse(stored.nextAttemptAt)>Date.now()) return manual('自动登录暂缓,请稍后重试或更新托管账号。');
await this.readOnlyGoto(lease,this.urls.main);
if (lease.blocked || !this.allowed(lease.page.url())) return manual('请人工检查 BPM 登录页面。');
if (!await this.automaticSubmit(lease,stored)) return manual('需要人工完成验证码或登录验证。');
// Persist before a request to avoid repeated retries after a crash or failed password.
await this.vault().write('account:'+connection.id,{...stored,nextAttemptAt:new Date(Date.now()+15*60*1000).toISOString()});
if (!await this.automaticSubmit(lease,stored,true)) return manual('需要人工完成登录验证。');
await this.settleNavigation(lease);
result=await this.verify(lease);this.authorize(connection,principal);
if (this.canPersistVerified(result)) {
await this.persistLease(lease);delete stored.nextAttemptAt;await this.vault().write('account:'+connection.id,stored);
} else if (!result.checks.portal.ok) result.checks.portal.message='自动登录未完成,请检查托管账号或人工完成验证;稍后重试。';
return result;
} finally { await this.closeLease(connection.id); }
});
}
async scanArrivals(connection,principal) {
const query=()=>this.run(connection?.id,async()=>{
this.authorize(connection,principal);
if(this.sessions.has(connection.id))throw error('此连接正在登录窗口中使用,请关闭后扫描。',409);
const saved=await this.vault().read(connection.id);
const rows=await (this.listClient ||= new BpmListClient()).scan(saved?.storageState);
this.authorize(connection,principal);return rows;
});
try{return await query();}catch(cause){if(cause.status!==401)throw cause;}
// Renewal takes the same per-connection lock, so it must run after query releases it.
const renewed=await this.ensure(connection,principal);
if(renewed.status!=='connected')throw error(renewed.checks?.portal?.message||'请在 BPM 连接中完成登录。',401);
return query();
}
authorize(connection, principal) {
if (!connection || typeof connection.id !== 'string' || !connection.id || connection.id.length > 200) throw error('连接标识无效。');
if (!principal?.sessionId || !principal.user || !['admin','operator'].includes(principal.user.role) || (principal.user.role !== 'admin' && connection.owner !== principal.user.username)) throw error('只有连接负责人或管理员可以操作。',403);
if (this.stopped) throw error('BPM 服务正在关闭。',503);
if (connection.status === 'disabled' || this.disabled.has(connection.id)) throw error('此 BPM 连接已停用。',409);
}
run(id, work) {
const before = this.operations.get(id) || Promise.resolve();
const operation = before.catch(()=>{}).then(work).catch(cause=>{ throw safe(cause); });
this.operations.set(id, operation);
operation.finally(()=>{ if (this.operations.get(id) === operation) this.operations.delete(id); }).catch(()=>{});
return operation;
}
touch(lease) {
lease.expiresAt = Date.now() + TTL; clearTimeout(lease.timer);
lease.timer = setTimeout(()=>this.run(lease.id, async()=>{ if (lease.expiresAt <= Date.now()) await this.closeLease(lease.id); }).catch(()=>{}), TTL + 10);
lease.timer.unref?.();
}
async getLease(id, principal, touch = false, closing = false) {
const lease = this.sessions.get(id);
if (!lease) throw error('登录窗口已关闭,请重新打开。',410);
this.authorize(lease.connection,principal);
if (lease.sessionId !== principal.sessionId) throw error('此连接正在另一登录窗口中使用。',409);
if (lease.expiresAt <= Date.now()) { await this.closeLease(id); throw error('登录窗口已过期,请重新打开。',410); }
if (!closing && (lease.blocked || !this.allowed(lease.page.url()))) throw error('已阻止离开允许的 BPM 域名,请重新打开登录窗口。',403);
if (touch) this.touch(lease);
return lease;
}
async browser() {
if (this.stopped) throw error('BPM 服务正在关闭。',503);
if (!this.browserPromise) this.browserPromise = Promise.resolve().then(()=>this.browserFactory()).catch(cause=>{ this.browserPromise=null; throw cause; });
return this.browserPromise;
}
async create(connection, principal) {
this.authorize(connection,principal);
if (this.sessions.size >= 3) throw error('同时登录窗口已达上限,请先关闭其他窗口。',429);
const lease = { id:connection.id, connection:{...connection}, sessionId:principal.sessionId, context:null, page:null, blocked:false, sessionStorage:{} };
this.sessions.set(connection.id,lease); this.touch(lease);
try {
const stored = await this.vault().read(connection.id);
lease.sessionStorage = stored?.sessionStorage || {};
const browser = await this.browser();
this.authorize(connection,principal);
lease.context = await browser.newContext({ viewport:{width:1280,height:800}, acceptDownloads:false, serviceWorkers:'block', permissions:[], storageState:stored?.storageState });
await lease.context.route('**/*', async route => {
try {
// A popup is never a remote-control surface. Block its first navigation,
// before even an allowed host can redirect it elsewhere.
if (route.request().isNavigationRequest() && route.request().frame().page()!==lease.page) return route.abort('blockedbyclient');
if (this.allowed(route.request().url())) {
// route.continue follows redirects without re-entering the route handler.
// Inspect each redirect before Chromium receives it, including resource redirects.
const response=await route.fetch({maxRedirects:0,timeout:25000});
const location=response.headers().location;
if (location && response.status()>=300 && response.status()<400 && !this.allowed(new URL(location,route.request().url()).href)) {
if (route.request().isNavigationRequest() && !route.request().frame().parentFrame()) lease.blocked=true;
return route.abort('blockedbyclient');
}
if (/attachment/i.test(response.headers()['content-disposition']||'')) return route.abort('blockedbyclient');
return route.fulfill({response});
}
if (route.request().isNavigationRequest() && !route.request().frame().parentFrame()) lease.blocked = true;
await route.abort('blockedbyclient');
} catch { await route.abort('failed').catch(()=>{}); }
});
if (lease.context.routeWebSocket) await lease.context.routeWebSocket(/.*/, socket => {
const url=socket.url().replace(/^ws:/,'http:').replace(/^wss:/,'https:');
if (this.allowed(url)) socket.connectToServer(); else socket.close();
});
await lease.context.addInitScript(({ sessions }) => {
try { if (sessionStorage.length===0) for (const [key,value] of Object.entries(sessions[location.origin] || {})) sessionStorage.setItem(key,value); } catch {}
// Native file pickers are not part of remote login and must never reach the service desktop.
const disable = () => document.querySelectorAll('input[type=file]').forEach(input=>{ input.disabled=true; });
new MutationObserver(disable).observe(document,{childList:true,subtree:true});
document.addEventListener('click', event => { if (event.target.closest?.('input[type=file],a[download]')) { event.preventDefault(); event.stopImmediatePropagation(); } },true);
}, { sessions:lease.sessionStorage });
lease.page = await lease.context.newPage();
// Playwright routes omit redirected requests. A private Chromium request-stage
// guard sees every hop before any network access, including redirect chains.
lease.network = await lease.context.newCDPSession(lease.page);
lease.mainFrameId=(await lease.network.send('Page.getFrameTree')).frameTree.frame.id;
// Raw mouse/keyboard input returns before a form-triggered navigation commits.
// Track main-frame navigation independently so verification never races it.
const started=event=>{
if (event.frameId!==lease.mainFrameId || lease.pendingNavigation) return;
lease.pendingNavigation=new Promise(resolve=>{lease.finishNavigation=resolve;});
};
lease.network.on('Page.frameRequestedNavigation',started);
lease.network.on('Page.frameStartedLoading',started);
lease.network.on('Page.frameStoppedLoading',event=>{
if (event.frameId!==lease.mainFrameId) return;
lease.finishNavigation?.(); lease.pendingNavigation=null; lease.finishNavigation=null;
});
await lease.network.send('Page.enable');
lease.network.on('Fetch.requestPaused', async event => {
try {
if (this.allowed(event.request.url)) await lease.network.send('Fetch.continueRequest',{requestId:event.requestId});
else {
if (event.resourceType==='Document' && event.frameId===lease.mainFrameId) lease.blocked=true;
await lease.network.send('Fetch.failRequest',{requestId:event.requestId,errorReason:'BlockedByClient'});
}
} catch {}
});
await lease.network.send('Fetch.enable',{patterns:[{urlPattern:'*',requestStage:'Request'}]});
lease.context.on('page', page=>{ if (page !== lease.page) page.close().catch(()=>{}); });
lease.page.on('download', download=>download.cancel().catch(()=>{}));
lease.page.on('dialog', dialog=>dialog.dismiss().catch(()=>{}));
await lease.page.goto(this.urls.main,{waitUntil:'domcontentloaded',timeout:30000});
this.authorize(connection,principal);
if (lease.blocked || !this.allowed(lease.page.url())) throw error('已阻止离开允许的 BPM 域名。',403);
await this.fillSavedAccount(lease);
return lease;
} catch (cause) { await this.closeLease(connection.id); throw safe(cause); }
}
async open(connection, principal) {
return this.run(connection?.id,async()=>{
this.authorize(connection,principal);
const lease=this.sessions.has(connection.id) ? await this.getLease(connection.id,principal,true) : await this.create(connection,principal);
return { active:true,viewport:{width:1280,height:800},expiresAt:new Date(lease.expiresAt).toISOString(),host:new URL(lease.page.url()).host };
});
}
async frame(id,principal) { return this.run(id,async()=>{ const lease=await this.getLease(id,principal); return lease.page.screenshot({type:'jpeg',quality:75,caret:'initial',timeout:10000}); }); }
async input(id,principal,action) {
return this.run(id,async()=>{
if (!object(action,['type','x','y','text','key','deltaX','deltaY'])) throw error('输入操作无效。');
const type=action.type;
if (type==='click') { if (!Number.isFinite(action.x)||!Number.isFinite(action.y)||action.x<0||action.x>=1280||action.y<0||action.y>=800) throw error('点击位置无效。'); }
else if (type==='text') { if (typeof action.text!=='string'||action.text.length>2000) throw error('输入文字过长或无效。'); }
else if (type==='key') { if (!KEYS.has(action.key)) throw error('不支持此按键。'); }
else if (type==='scroll') { if (![action.deltaX,action.deltaY].every(value=>Number.isFinite(value)&&Math.abs(value)<=10000)) throw error('滚动距离无效。'); }
else throw error('输入操作无效。');
const lease=await this.getLease(id,principal,true);
if (type==='click') await lease.page.mouse.click(action.x,action.y);
if (type==='text') await lease.page.keyboard.insertText(action.text);
if (type==='key') await lease.page.keyboard.press(action.key);
if (type==='scroll') await lease.page.mouse.wheel(action.deltaX,action.deltaY);
return {ok:true};
});
}
async navigate(id,principal,action) {
return this.run(id,async()=>{
if (!object(action,['target']) || !['main','reload','back'].includes(action.target)) throw error('导航目标无效。');
const lease=await this.getLease(id,principal,true), options={waitUntil:'domcontentloaded',timeout:30000};
if (action.target==='reload') await lease.page.reload(options);
else if (action.target==='back') await lease.page.goBack(options);
else await lease.page.goto(this.urls[action.target],options);
if (lease.blocked || !this.allowed(lease.page.url())) throw error('已阻止离开允许的 BPM 域名。',403);
await this.fillSavedAccount(lease);
return {ok:true,host:new URL(lease.page.url()).host};
});
}
async defaultProbe(page) {
const marker=page.locator('a.yz-btn-signinuser .x-btn-inner').first();
await marker.waitFor({state:'visible',timeout:4000}).catch(()=>{});
if (!await marker.isVisible().catch(()=>false)) return {ok:false};
const identity=(await marker.innerText()).trim();
return {ok:!!identity && !/^(登录|请登录|未登录|sign\s*in|login)$/i.test(identity),identity};
}
async captureSessions(lease) {
for (const frame of lease.page.frames()) {
if (!this.allowed(frame.url())) continue;
const item=await frame.evaluate(()=>({origin:location.origin,values:Object.fromEntries(Object.entries(sessionStorage))})).catch(()=>null);
if (item) lease.sessionStorage[item.origin]=item.values;
}
}
async settleNavigation(lease) {
// A protocol round trip lets an input-triggered navigation notification arrive;
// the wait itself follows lifecycle events, with a deadline rather than a sleep.
await lease.network.send('Page.getFrameTree');
const pending=lease.pendingNavigation;
if (pending) {
let timeout;
try { await Promise.race([pending,new Promise((_,reject)=>{timeout=setTimeout(()=>reject(error('BPM 页面仍在加载,请稍后重试。',503)),15000);})]); }
finally { clearTimeout(timeout); }
}
await lease.page.waitForLoadState('domcontentloaded',{timeout:15000});
}
async readOnlyGoto(lease,url) {
await this.settleNavigation(lease);
for (let attempt=0;attempt<2;attempt++) {
try { return await lease.page.goto(url,{waitUntil:'domcontentloaded',timeout:25000}); }
catch (cause) {
// Retry only our read-only verification GET, never the user's login action.
if (attempt || lease.blocked || !/interrupted by another navigation|ERR_ABORTED/i.test(cause.message||'')) throw cause;
await this.settleNavigation(lease);
}
}
}
async verify(lease) {
const checkedAt=new Date().toISOString();
try {
await this.settleNavigation(lease);await this.captureSessions(lease);
lease.blocked=false;
const response=await this.readOnlyGoto(lease,this.urls.main);
if (lease.blocked || !this.allowed(lease.page.url())) throw error('域名被阻止。',403);
if (response && response.status()>=400) throw error('BPM 暂时无法连接。',503);
const result=await this.probe(lease.page,'portal');
const ok=result?.ok===true && typeof result.identity==='string' && !!result.identity.trim();
await this.captureSessions(lease);
return {status:ok?'connected':'login_required',identity:ok?result.identity.trim().slice(0,150):'',checkedAt,checks:{portal:{ok,message:ok?'已验证登录账号。':'请在此入口完成登录。'}}};
} catch {
return {status:'error',identity:'',checkedAt,checks:{portal:{ok:false,message:lease.blocked?'已阻止离开允许的 BPM 域名。':'暂时无法验证此入口。'}}};
}
}
async save(connection,principal) {
return this.run(connection?.id,async()=>{
this.authorize(connection,principal); const lease=await this.getLease(connection.id,principal,true);
const result=await this.verify(lease);
this.authorize(connection,principal);
// Failed verification never replaces a previously working credential snapshot.
if (this.canPersistVerified(result)) await this.persistLease(lease);
return result;
});
}
async check(connection,principal) {
return this.run(connection?.id,async()=>{
this.authorize(connection,principal);
const transient=!this.sessions.has(connection.id);
const lease=transient ? await this.create(connection,principal) : await this.getLease(connection.id,principal,true);
try { const result=await this.verify(lease); this.authorize(connection,principal); if(this.canPersistVerified(result))await this.persistLease(lease); return result; }
finally { if (transient) await this.closeLease(connection.id); }
});
}
async closeLease(id) {
const lease=this.sessions.get(id); if (!lease) return;
clearTimeout(lease.timer); this.sessions.delete(id);
await lease.context?.close().catch(()=>{});
}
async close(id,principal) { return this.run(id,async()=>{ if (!this.sessions.has(id)) return {active:false}; await this.getLease(id,principal,false,true); await this.closeLease(id); return {active:false}; }); }
async releaseSession(sessionId) { await Promise.all([...this.sessions.values()].filter(lease=>lease.sessionId===sessionId).map(lease=>this.run(lease.id,()=>this.closeLease(lease.id)))); }
async disable(id) { this.disabled.add(id); await this.run(id,async()=>{ await this.closeLease(id); await this.vault().remove(id); await this.vault().remove('account:'+id); }); }
async shutdown() {
this.stopped=true;
await Promise.allSettled([...this.operations.values()]);
await Promise.all([...this.sessions.keys()].map(id=>this.closeLease(id)));
if (this.browserPromise) await (await this.browserPromise.catch(()=>null))?.close().catch(()=>{});
this._vault?.destroy();
}
}
module.exports={BpmSessionManager};
+123
View File
@@ -0,0 +1,123 @@
'use strict';
const fs = require('node:fs');
const fsp = require('node:fs/promises');
const path = require('node:path');
const crypto = require('node:crypto');
const { execFileSync } = require('node:child_process');
const { DatabaseSync } = require('node:sqlite');
const fail = () => Object.assign(new Error('BPM 会话存储不可用,请重新登录或联系管理员。'), { status: 503 });
const duplicate = () => Object.assign(new Error('该 BPM 账号已开启自动续登,请使用已有连接或先解除原账号托管。'), { status: 409, code: 'BPM_ACCOUNT_DUPLICATE' });
const digest = value => crypto.createHash('sha256').update(value).digest('hex');
function powershell(script, input) {
return execFileSync('powershell.exe', ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', script], {
input, encoding: 'utf8', windowsHide: true, timeout: 15000, stdio: ['pipe', 'pipe', 'pipe']
}).trim();
}
function secureDirectory(dir) {
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
if (process.platform === 'win32') {
powershell('$ErrorActionPreference="Stop"; $p=[Console]::In.ReadToEnd(); $s=[System.Security.Principal.WindowsIdentity]::GetCurrent().User; $a=New-Object System.Security.AccessControl.DirectorySecurity; $a.SetAccessRuleProtection($true,$false); $a.SetOwner($s); $r=New-Object System.Security.AccessControl.FileSystemAccessRule($s,"FullControl","ContainerInherit,ObjectInherit","None","Allow"); $a.AddAccessRule($r); [System.IO.Directory]::SetAccessControl($p,$a)', dir);
} else fs.chmodSync(dir, 0o700);
}
function dpapi(value, decrypt = false) {
const operation = decrypt ? 'Unprotect' : 'Protect';
return Buffer.from(powershell(`$ErrorActionPreference="Stop"; Add-Type -AssemblyName System.Security; $b=[Convert]::FromBase64String([Console]::In.ReadToEnd()); $r=[System.Security.Cryptography.ProtectedData]::${operation}($b,$null,[System.Security.Cryptography.DataProtectionScope]::CurrentUser); [Console]::Out.Write([Convert]::ToBase64String($r))`, value.toString('base64')), 'base64');
}
class BpmVault {
constructor({ stateDir }) {
try {
this.stateDir = path.resolve(stateDir);
secureDirectory(this.stateDir);
} catch { throw fail(); }
}
ensureKey() {
if (this.key) return this.key;
try {
// The key always stays on the service user's local disk, even when project code is on a shared drive.
const keyDir = process.platform === 'win32'
? path.join(process.env.LOCALAPPDATA, 'OrderNotificationAutomation', 'bpm-keys')
: path.join(this.stateDir, '.keys');
secureDirectory(keyDir);
const keyFile = path.join(keyDir, digest(this.stateDir.toLowerCase()) + '.key');
if (!fs.existsSync(keyFile)) {
const raw = crypto.randomBytes(32);
const protectedKey = process.platform === 'win32' ? dpapi(raw) : raw;
try { fs.writeFileSync(keyFile, protectedKey, { flag: 'wx', mode: 0o600 }); }
catch (error) { if (error.code !== 'EEXIST') throw error; }
finally { raw.fill(0); }
}
const protectedKey = fs.readFileSync(keyFile);
this.key = process.platform === 'win32' ? dpapi(protectedKey, true) : protectedKey;
if (this.key.length !== 32) throw fail();
return this.key;
} catch { throw fail(); }
}
filename(id) {
if (typeof id !== 'string' || !id || id.length > 200) throw Object.assign(new Error('连接标识无效。'), { status: 400 });
return path.join(this.stateDir, digest(id) + '.enc');
}
accounts() {
if(this.db)return this.db;
const db=new DatabaseSync(path.join(this.stateDir,'accounts.sqlite'));
try{db.exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA secure_delete=ON;
CREATE TABLE IF NOT EXISTS accounts(connection_id TEXT PRIMARY KEY,username_key TEXT NOT NULL UNIQUE,payload BLOB NOT NULL);`);this.db=db;return db;}
catch{db.close();throw fail();}
}
accountKey(username) {
if(typeof username!=='string'||!username.trim()||username.length>150)throw Object.assign(new Error('请输入有效的 BPM 账号。'),{status:400});
return crypto.createHmac('sha256',this.ensureKey()).update(username.trim().toLowerCase()).digest('hex');
}
encode(id,state) {
const iv=crypto.randomBytes(12),cipher=crypto.createCipheriv('aes-256-gcm',this.ensureKey(),iv);cipher.setAAD(Buffer.from(id));
const encrypted=Buffer.concat([cipher.update(JSON.stringify(state),'utf8'),cipher.final()]);
return Buffer.concat([Buffer.from('BPM1'),iv,cipher.getAuthTag(),encrypted]);
}
decode(id,bytes) {
const data=Buffer.from(bytes);
if(data.length<33||data.subarray(0,4).toString()!=='BPM1')throw fail();
const decipher=crypto.createDecipheriv('aes-256-gcm',this.ensureKey(),data.subarray(4,16));
decipher.setAAD(Buffer.from(id));decipher.setAuthTag(data.subarray(16,32));
return JSON.parse(Buffer.concat([decipher.update(data.subarray(32)),decipher.final()]).toString('utf8'));
}
putAccount(id,state) {
try{this.accounts().prepare('INSERT INTO accounts(connection_id,username_key,payload) VALUES(?,?,?) ON CONFLICT(connection_id) DO UPDATE SET username_key=excluded.username_key,payload=excluded.payload').run(id.slice(8),this.accountKey(state.username),this.encode(id,state));}
catch(cause){if(cause.errcode===2067)throw duplicate();if(cause.status)throw cause;throw fail();}
}
async accountAvailability(connectionId,username) {
try{const row=this.accounts().prepare('SELECT connection_id FROM accounts WHERE username_key=?').get(this.accountKey(username));return {available:!row||row.connection_id===connectionId};}
catch(cause){if(cause.status)throw cause;throw fail();}
}
async migrateAccounts(connectionIds) {
const db=this.accounts(),legacy=[];
try{
for(const connectionId of connectionIds){const id='account:'+connectionId;if(db.prepare('SELECT 1 FROM accounts WHERE connection_id=?').get(connectionId))continue;try{const payload=await fsp.readFile(this.filename(id));legacy.push({id,state:this.decode(id,payload)});}catch(cause){if(cause.code!=='ENOENT')throw cause;}}
db.exec('BEGIN IMMEDIATE');
try{for(const item of legacy)this.putAccount(item.id,item.state);db.exec('COMMIT');}catch(cause){db.exec('ROLLBACK');throw cause;}
// Committed database rows become authoritative before legacy ciphertext is removed.
for(const item of legacy)await fsp.rm(this.filename(item.id),{force:true});
}catch(cause){if(cause.status)throw cause;throw fail();}
}
async read(id) {
const filename = this.filename(id);
try {
if(id.startsWith('account:')){const row=this.accounts().prepare('SELECT payload FROM accounts WHERE connection_id=?').get(id.slice(8));if(row)return this.decode(id,row.payload);}
const state=this.decode(id,await fsp.readFile(filename));
if(id.startsWith('account:')){this.putAccount(id,state);await fsp.rm(filename,{force:true});}
return state;
} catch (error) { if (error.code === 'ENOENT') return null;if(error.code==='BPM_ACCOUNT_DUPLICATE')throw error;throw fail(); }
}
async write(id, state) {
const filename = this.filename(id), temp = filename + '.' + crypto.randomUUID() + '.tmp';
if(id.startsWith('account:')){this.putAccount(id,state);await fsp.rm(filename,{force:true}).catch(()=>{});return;}
try {
await fsp.writeFile(temp, this.encode(id,state), { flag: 'wx', mode: 0o600 });
await fsp.rename(temp, filename);
} catch { throw fail(); }
finally { await fsp.rm(temp, { force: true }).catch(() => {}); }
}
async remove(id) { try { await fsp.rm(this.filename(id), { force: true });if(id.startsWith('account:'))this.accounts().prepare('DELETE FROM accounts WHERE connection_id=?').run(id.slice(8)); } catch { throw fail(); } }
destroy() { this.db?.close();this.db=null;this.key?.fill(0);this.key=null; }
}
module.exports = { BpmVault };
+32
View File
@@ -0,0 +1,32 @@
const fs=require('node:fs');
const path=require('node:path');
const crypto=require('node:crypto');
const {DatabaseSync}=require('node:sqlite');
const DAY=86400000;
const SESSION_MS=30*DAY;
const digest=token=>crypto.createHash('sha256').update(token).digest('hex');
class SessionStore {
constructor(dir){
fs.mkdirSync(dir,{recursive:true});this.db=new DatabaseSync(path.join(dir,'auth.sqlite'));
this.db.exec('PRAGMA busy_timeout=5000; CREATE TABLE IF NOT EXISTS sessions(hash TEXT PRIMARY KEY,userId TEXT NOT NULL,expires INTEGER NOT NULL,renewedAt INTEGER NOT NULL);');
}
issue(userId,now=Date.now()){
this.db.prepare('DELETE FROM sessions WHERE expires<=?').run(now);
this.db.exec('DELETE FROM sessions WHERE hash IN (SELECT hash FROM sessions ORDER BY renewedAt DESC LIMIT -1 OFFSET 999)');
const token=crypto.randomBytes(32).toString('hex'),expires=now+SESSION_MS;
this.db.prepare('INSERT INTO sessions(hash,userId,expires,renewedAt) VALUES(?,?,?,?)').run(digest(token),userId,expires,now);
return {token,expires};
}
lookup(token,now=Date.now()){
if(typeof token!=='string' || !/^[a-f0-9]{64}$/.test(token))return null;
const hash=digest(token),row=this.db.prepare('SELECT userId,expires,renewedAt FROM sessions WHERE hash=?').get(hash);
if(!row)return null;
if(row.expires<=now){this.db.prepare('DELETE FROM sessions WHERE hash=?').run(hash);return null;}
const renewed=now-row.renewedAt>=DAY;
if(renewed){row.expires=now+SESSION_MS;this.db.prepare('UPDATE sessions SET expires=?,renewedAt=? WHERE hash=?').run(row.expires,now,hash);}
return {userId:row.userId,expires:row.expires,renewed};
}
revoke(token){if(typeof token==='string' && /^[a-f0-9]{64}$/.test(token))this.db.prepare('DELETE FROM sessions WHERE hash=?').run(digest(token));}
close(){if(this.db){this.db.close();this.db=null;}}
}
module.exports={SessionStore,SESSION_MS};
+99
View File
@@ -0,0 +1,99 @@
const fs=require('node:fs');
const path=require('node:path');
const crypto=require('node:crypto');
const copy=value=>structuredClone(value);
const safeUser=({id,username,role,createdAt})=>({id,username,role,createdAt});
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
function validateSettings(settings) {
const schedule=settings.schedule;
if(!schedule || !Array.isArray(schedule.times) || schedule.times.length!==2 || new Set(schedule.times).size!==2)fail('请设置两个不同的发送时间。');
if(schedule.times.some(time=>typeof time!=='string' || !/^(?:[01]\d|2[0-3]):[0-5]\d$/.test(time)))fail('时间必须为有效的 HH:MM。');
if(typeof schedule.weekends!=='boolean' || !['product_line','order'].includes(schedule.mode) || !['next_window','skip'].includes(schedule.missed))fail('发送计划选项不正确。');
if(schedule.timezone!=='Asia/Shanghai')fail('时区必须为 Asia/Shanghai。');
if(!settings.templates || typeof settings.templates.subject!=='string' || typeof settings.templates.body!=='string' || settings.templates.subject.length>300 || settings.templates.body.length>20000)fail('模板标题最多 300 字,正文最多 20000 字。');
if(!Array.isArray(settings.groups) || settings.groups.length>100)fail('收件群组格式不正确。');
const names=new Set();
for(const group of settings.groups) {
if(!group || typeof group.productLine!=='string' || !group.productLine.trim() || group.productLine.length>100 || names.has(group.productLine.trim()))fail('产品线名称不能为空或重复。');
names.add(group.productLine.trim());
for(const field of ['to','cc']) {
if(!Array.isArray(group[field]) || group[field].length>50 || group[field].some(email=>typeof email!=='string' || email.length>254 || !/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(email)))fail('请填写有效的收件邮箱,使用逗号分隔。');
}
if(group.to.length===0)fail('每个产品线至少需要一个收件人。');
}
}
class Store {
constructor(dir) {
fs.mkdirSync(dir,{recursive:true});this.file=path.join(dir,'state.json');
try {this.data=JSON.parse(fs.readFileSync(this.file,'utf8'));if(this.data.schema!==1)fail('状态文件版本不支持。',500);}
catch(error) {if(error.code!=='ENOENT')throw error;this.data={schema:1,users:[],settings:{version:1,schedule:{times:['09:00','17:00'],timezone:'Asia/Shanghai',weekends:false,mode:'product_line',missed:'next_window'},templates:{subject:'',body:''},groups:[]},jobs:[],audit:[]};}
}
commit(mutator) {
const draft=copy(this.data);const result=mutator(draft);
const temp=this.file+'.'+crypto.randomBytes(6).toString('hex')+'.tmp';
try {fs.writeFileSync(temp,JSON.stringify(draft,null,2),{mode:0o600});fs.renameSync(temp,this.file);}
catch(error){try{fs.unlinkSync(temp);}catch{}throw error;}
this.data=draft;return copy(result);
}
addAudit(draft,actor,action,detail='') {draft.audit.unshift({id:crypto.randomUUID(),at:new Date().toISOString(),actor,action,detail});draft.audit=draft.audit.slice(0,2000);}
settings(){return copy(this.data.settings);}
saveSettings(patch,version,actor) {
return this.commit(draft=>{
if(version!==draft.settings.version)fail('配置已被其他人更新,请刷新后重试。',409);
const updated={...draft.settings};
for(const key of ['schedule','templates','groups'])if(Object.hasOwn(patch,key))updated[key]=copy(patch[key]);
validateSettings(updated);
updated.schedule={times:[...updated.schedule.times].sort(),timezone:'Asia/Shanghai',weekends:updated.schedule.weekends,mode:updated.schedule.mode,missed:updated.schedule.missed};
updated.templates={subject:updated.templates.subject,body:updated.templates.body};
updated.groups=updated.groups.map(group=>({productLine:group.productLine.trim(),to:group.to,cc:group.cc}));
updated.version++;draft.settings=updated;
this.addAudit(draft,actor,'保存配置','发送计划 / 模板 / 产品线群组');return updated;
});
}
users(){return this.data.users.map(safeUser);}
user(id){const user=this.data.users.find(user=>user.id===id);return user?safeUser(user):null;}
makeUser(username,password,role) {
if(typeof username!=='string' || !/^[a-zA-Z0-9_.-]{3,40}$/.test(username))fail('账号需为 3–40 位英文、数字、点、下划线或短横线。');
if(typeof password!=='string' || password.length<12 || password.length>128)fail('密码长度需为 12–128 位。');
if(!['admin','operator','viewer'].includes(role))fail('账号角色不正确。');
if(this.data.users.some(user=>user.username.toLowerCase()===username.toLowerCase()))fail('账号已存在。',409);
const salt=crypto.randomBytes(16).toString('hex');
return {id:crypto.randomUUID(),username,role,createdAt:new Date().toISOString(),passwordHash:salt+':'+crypto.scryptSync(password,salt,32).toString('hex')};
}
bootstrap(username,password) {
if(this.data.users.length)fail('管理员已经创建,请登录。',409);
const user=this.makeUser(username,password,'admin');
return this.commit(draft=>{draft.users.push(user);this.addAudit(draft,username,'创建管理员');return safeUser(user);});
}
addUser(input,actor) {
const user=this.makeUser(input.username,input.password,input.role);
return this.commit(draft=>{draft.users.push(user);this.addAudit(draft,actor,'创建账号',user.username+' / '+user.role);return safeUser(user);});
}
authenticate(username,password) {
if(typeof username!=='string' || typeof password!=='string' || password.length>128)return null;
const user=this.data.users.find(user=>user.username.toLowerCase()===username.toLowerCase());
const [salt,hash]=(user?.passwordHash || '00000000000000000000000000000000:'+ '0'.repeat(64)).split(':');
const actual=crypto.scryptSync(password,salt,32);
if(!crypto.timingSafeEqual(actual,Buffer.from(hash,'hex')) || !user)return null;
return safeUser(user);
}
recordJob(record) {
return this.commit(draft=>{
const index=draft.jobs.findIndex(job=>job.jobId===record.jobId);
const prior=index>=0?draft.jobs[index]:{createdAt:new Date().toISOString()};
const saved={...prior,...copy(record),updatedAt:new Date().toISOString()};
if(index>=0)draft.jobs.splice(index,1);draft.jobs.unshift(saved);draft.jobs=draft.jobs.slice(0,5000);
if(record.status!=='running')this.addAudit(draft,'浏览器导出',record.status==='success'?'PDF 导出完成':'PDF 导出失败',record.filename || record.error || '');
return saved;
});
}
jobs(){return copy(this.data.jobs);}
audit(){return copy(this.data.audit);}
recoverJobs() {
if(!this.data.jobs.some(job=>job.status==='running'))return;
this.commit(draft=>{for(const job of draft.jobs)if(job.status==='running'){job.status='interrupted';job.error='服务重启,请核对输出文件后重新导出。';}return null;});
}
}
module.exports={Store};
+121
View File
@@ -0,0 +1,121 @@
const http=require('node:http');const fs=require('node:fs');const path=require('node:path');
const {nextSlots}=require('./schedule.cjs');
const {workspaceApi}=require('./workspace-api.cjs');
const {bpmApi}=require('./bpm-api.cjs');
const {mailApi}=require('./mail-api.cjs');
const {bpmScanApi}=require('./bpm-scan-api.cjs');
const {SessionStore,SESSION_MS}=require('./dashboard-sessions.cjs');
const isLoopback=address=>['127.0.0.1','::1','::ffff:127.0.0.1'].includes(address);
const publicJob=({path:ignored,...job})=>({...job,downloadable:job.status==='success'});
function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,mail,scanner,trustedProxy=false}) {
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})(?:;|$)');
const webRoot=path.resolve(__dirname,'../web');
const assets={
'/':{path:path.join(webRoot,'index.html'),type:'text/html'},
'/app.js':{path:path.join(webRoot,'app.js'),type:'text/javascript'},
'/workspace.js':{path:path.join(webRoot,'workspace.js'),type:'text/javascript'},
'/bpm.js':{path:path.join(webRoot,'bpm.js'),type:'text/javascript'},
'/mail.js':{path:path.join(webRoot,'mail.js'),type:'text/javascript'},
'/orders.js':{path:path.join(webRoot,'orders.js'),type:'text/javascript'},
'/app.css':{path:path.join(webRoot,'app.css'),type:'text/css'},
'/vendor/tabler.css':{path:require.resolve('@tabler/core/dist/css/tabler.min.css'),type:'text/css'},
'/vendor/tabler.js':{path:require.resolve('@tabler/core/dist/js/tabler.min.js'),type:'text/javascript'}
};
const server=http.createServer(async(request,response)=>{
const encryptedTransport=Boolean(request.socket.encrypted || (trustedProxy && isLoopback(request.socket.remoteAddress) && request.headers['x-forwarded-proto']==='https'));
response.setHeader('X-Content-Type-Options','nosniff');response.setHeader('Referrer-Policy','same-origin');
response.setHeader('Content-Security-Policy',"default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'");
response.setHeader('Cache-Control','no-store');
const reply=(status,body)=>{response.writeHead(status,{'Content-Type':'application/json; charset=utf-8'});response.end(JSON.stringify(body));};
const fail=(status,message)=>{throw Object.assign(new Error(message),{status});};
try {
const url=new URL(request.url,'http://localhost');const route=url.pathname;
const asset=assets[route];
if(request.method==='GET' && asset) {
const bytes=await fs.promises.readFile(asset.path);response.writeHead(200,{'Content-Type':asset.type+'; charset=utf-8'});response.end(bytes);return;
}
const sameOrigin=request.headers.origin===`http://${request.headers.host}` || request.headers.origin===`https://${request.headers.host}`;
if(!['GET','HEAD'].includes(request.method) && !sameOrigin)fail(403,'请在看板页面中执行操作。');
let body;
if(request.method==='POST') {
if(!/^application\/json(?:;|$)/i.test(request.headers['content-type'] || ''))fail(415,'需要 JSON 数据。');
if(Number(request.headers['content-length'] || 0)>128*1024){request.resume();fail(413,'提交内容过大。');}
const chunks=[];let size=0;
for await(const chunk of request){size+=chunk.length;if(size>128*1024)fail(413,'提交内容过大。');chunks.push(chunk);}
try{body=JSON.parse(Buffer.concat(chunks).toString('utf8'));if(!body || Array.isArray(body) || typeof body!=='object')throw new Error();}catch{fail(400,'数据格式不正确。');}
}
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 reply(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 reply(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 reply(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 reply(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 reply(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 reply(200,{ok:true});}
if(await bpmApi({workspace,bpmSessions,user,sessionId:token,route,method:request.method,body,request,response,reply,trustedProxy}))return;
if(await mailApi({mail,workspace,user,route,method:request.method,body,request,response,reply,trustedProxy}))return;
if(await bpmScanApi({scanner,workspace,user,sessionId:token,url,route,method:request.method,body,reply}))return;
if(workspaceApi({workspace,store,user,route,method:request.method,body,reply,bpmSessions}))return;
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 reply(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:'待接入订单规则表和归档目录,业务自动处理尚未启用。'},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:'210 服务器',ready:false,detail:'等待完整地址、协议和归档目录'},{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 reply(200,store.settings());
if(request.method==='POST'){if(user.role!=='admin')fail(403,'仅管理员可以修改配置。');return reply(200,store.saveSettings(body,body.version,user.username));}
}
if(route==='/api/jobs' && request.method==='GET')return reply(200,{jobs:store.jobs().map(publicJob)});
if(route==='/api/audit' && request.method==='GET')return reply(200,{audit:store.audit()});
if(route==='/api/users') {
if(user.role!=='admin')fail(403,'仅管理员可以管理账号。');
if(request.method==='GET')return reply(200,{users:store.users()});
if(request.method==='POST')return reply(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;
}
fail(404,'没有找到此页面或操作。');
}catch(error){if(!response.headersSent){if(!error.status)console.error('看板处理失败:',error.message);reply(error.status || 500,{error:error.status?error.message:'处理失败,请检查服务日志。'});}else response.end();}
});
server.once('close',()=>sessions.close());server.once('error',()=>{if(!server.listening)sessions.close();});
return server;
}
module.exports={createDashboard};
+90
View File
@@ -0,0 +1,90 @@
const fs = require('node:fs/promises');
const path = require('node:path');
const { loadPlaywright, browserOptions } = require('./runtime.cjs');
const fields = { order: '订单号', project: '项目编号', model: '产品型号', serial: '通知书编号' };
function buildFilename(metadata = {}) {
const parts = Object.entries(fields).map(([key, label]) => {
if (typeof metadata[key] !== 'string' || !metadata[key].trim()) throw new Error(`缺少${label},请在订单页检查。`);
const value = metadata[key].trim().replace(/[<>:"/\\|?*\x00-\x1f\x7f]/g, '_').replace(/[. ]+$/g, '').slice(0, 45);
if (!value || !/[^._ ]/.test(value)) throw new Error(`${label}不能用于文件名。`);
return value;
});
return parts.join('_') + '.pdf';
}
function validateSnapshot(snapshot) {
if (!snapshot || typeof snapshot.html !== 'string' || !snapshot.html.trim() || snapshot.html.length > 12_000_000) throw new Error('页面内容为空或超过大小限制。');
buildFilename(snapshot.metadata);
if (snapshot.styles !== undefined && (!Array.isArray(snapshot.styles) || snapshot.styles.some(s => typeof s !== 'string'))) throw new Error('页面样式格式不正确。');
if (snapshot.images !== undefined && (!Array.isArray(snapshot.images) || snapshot.images.length > 200)) throw new Error('页面图片格式不正确。');
}
async function reserveFile(outputDir, filename) {
await fs.mkdir(outputDir, { recursive: true });
for (let index = 1; index <= 9999; index++) {
const suffix = index === 1 ? '' : ` (${index})`;
const target = path.join(outputDir, filename.slice(0, -4) + suffix + '.pdf');
try { const handle = await fs.open(target, 'wx'); return { target, handle }; }
catch (error) { if (error.code !== 'EEXIST') throw error; }
}
throw new Error('同名文件过多,请更换输出目录。');
}
async function renderSnapshot(snapshot, options = {}) {
validateSnapshot(snapshot);
const filename = buildFilename(snapshot.metadata);
const outputDir = path.resolve(options.outputDir || path.join(__dirname, '../output/pdf'));
const scale = options.scale ?? 0.59;
if (typeof scale !== 'number' || scale < 0.1 || scale > 2) throw new Error('scale 必须在 0.1 到 2 之间。');
const browser = await loadPlaywright().chromium.launch(browserOptions());
let reservation;
try {
const context = await browser.newContext({ javaScriptEnabled: false, serviceWorkers: 'block', viewport: { width: 1280, height: 1000 } });
await context.route('**/*', route => route.abort());
const page = await context.newPage();
await page.goto('about:blank');
// Only static markup enters the document. Network and page scripts stay disabled.
const content = await page.evaluate(({ html, styles, images, width }) => {
const doc = new DOMParser().parseFromString(html, 'text/html');
doc.querySelectorAll('script,iframe,object,embed,link,base,meta,input,button,textarea,select,[printout="false"],#taskCommentForm').forEach(el => el.remove());
doc.querySelectorAll('*').forEach(el => {
for (const attribute of [...el.attributes]) {
if (/^on/i.test(attribute.name) || ['action','srcdoc','srcset','formaction','href','poster','background'].includes(attribute.name.toLowerCase())) el.removeAttribute(attribute.name);
}
if (el.hidden || /display\s*:\s*none/i.test(el.getAttribute('style') || '')) el.remove();
});
const supplied = new Map((images || []).filter(image => image && typeof image.url === 'string' && /^data:image\/(png|jpeg|gif|webp);base64,[a-z0-9+/=\r\n]+$/i.test(image.data || '')).map(image => [image.url, image.data]));
doc.querySelectorAll('img').forEach(el => {
const value = supplied.get(el.getAttribute('src')) || el.getAttribute('src') || '';
if (/^data:image\/(png|jpeg|gif|webp);base64,[a-z0-9+/=\r\n]+$/i.test(value)) el.setAttribute('src', value); else el.remove();
});
const cleanCSS = css => css.replace(/@import\s+[^;]+;/gi, '').replace(/url\([^)]*\)/gi, 'none').replace(/<\/style/gi, '');
const css = (styles || []).map(cleanCSS).join('\n');
doc.querySelectorAll('style').forEach(el => el.remove());
const style = doc.createElement('style');
const pageWidth = Math.min(1264, Math.max(800, Number(width) || 1264));
style.textContent = css + `\nhtml,body{margin:0;padding:0;background:white}body,form{width:${pageWidth}px;font-family:Arial,"Microsoft YaHei",sans-serif}table{max-width:100%}tr{break-inside:avoid;page-break-inside:avoid}td{overflow-wrap:anywhere}a{color:inherit;text-decoration:none}span.TextBox,span.TextBoxPink{height:auto!important;min-height:16px}@media print{html,body{-webkit-print-color-adjust:exact;print-color-adjust:exact}}`;
doc.head.append(style);
doc.querySelectorAll('.yz-inp-cnt').forEach(el => {
const match = (el.getAttribute('style') || '').match(/width\s*:\s*([\d.]+)px/);
const text = el.textContent.trim();
if (match && Number(match[1]) <= 50 && text) el.style.width = Math.max(50, Math.min(120, text.length * 8)) + 'px';
});
return '<!doctype html>' + doc.documentElement.outerHTML;
}, snapshot);
await page.setContent(content, { waitUntil: 'load', timeout: 30000 });
await page.evaluate(() => document.fonts.ready);
const pdf = await page.pdf({ format: 'A4', scale, printBackground: true, displayHeaderFooter: false, margin: { top: '8mm', right: '6mm', bottom: '8mm', left: '6mm' } });
if (pdf.subarray(0, 5).toString() !== '%PDF-') throw new Error('PDF 生成失败。');
reservation = await reserveFile(outputDir, filename);
await reservation.handle.writeFile(pdf);
await reservation.handle.close();
return { path: reservation.target, filename: path.basename(reservation.target), bytes: pdf.length, warnings: snapshot.warnings || [] };
} catch (error) {
if (reservation) { await reservation.handle.close().catch(() => {}); await fs.unlink(reservation.target).catch(() => {}); }
throw error;
} finally { await browser.close(); }
}
module.exports = { buildFilename, validateSnapshot, renderSnapshot };
+32
View File
@@ -0,0 +1,32 @@
'use strict';
const {secureBpmTransport}=require('./bpm-api.cjs');const {escape}=require('./mail-parser.cjs');
const fail=(message,status)=>{throw Object.assign(new Error(message),{status});};
async function mailApi({mail,workspace,user,route,method,body,request,response,reply,trustedProxy}){
if(!route.startsWith('/api/mail'))return false;if(!mail)fail('邮件服务暂不可用。',503);const store=mail.store;
if(method==='POST'&&user.role!=='admin')fail('仅管理员可以维护邮箱和确认模板。',403);
if(route==='/api/mail'&&method==='GET'){reply(200,{channels:store.channels(),templates:store.templates(),receipts:store.receipts(),sends:store.sends()});return true;}
const audit=(action,detail)=>workspace?.record(user,action,detail);
if(route==='/api/mail/channels'&&method==='POST'){
if(!secureBpmTransport(request,trustedProxy))fail('请在部署机本地或 HTTPS 页面维护邮箱账号。',403);
if(body?.id&&mail.busy(body.id))fail('此邮箱正在执行操作,请稍后保存。',409);const saved=store.saveChannel(body);audit('mail.channel.save',saved.name);reply(body.id?200:201,saved);return true;
}
let match=/^\/api\/mail\/channels\/([\w-]+)\/(verify|poll|test)$/.exec(route);
if(match&&method==='POST'){const [,id,action]=match;let result;if(action==='test'){if(typeof body.templateId!=='string')fail('请选择已生效模板。',400);result=await mail.sendTest(id,body.templateId);}else result=await mail[action](id);audit('mail.'+action,store.publicChannel(id).name);reply(200,result);return true;}
match=/^\/api\/mail\/templates\/([\w-]+)(?:\/(confirm|reject|preview|source|attachments\/([0-9]+)))?$/.exec(route);
if(match){const [,id,action,index]=match;const template=store.template(id);
if(method==='GET'&&!action){const {raw,attachments,...detail}=template;reply(200,{...detail,attachments:attachments.map(({content,...a})=>a)});return true;}
if(method==='GET'&&action==='preview'){
response.setHeader('Content-Security-Policy',"default-src 'none'; img-src data:; style-src 'unsafe-inline'; sandbox; base-uri 'none'; form-action 'none'");
response.writeHead(200,{'Content-Type':'text/html; charset=utf-8'});response.end('<!doctype html><html lang="zh-CN"><meta charset="utf-8"><style>body{font:14px/1.7 system-ui,sans-serif;padding:16px;color:#182433;overflow-wrap:anywhere}img{max-width:100%;height:auto}table{border-collapse:collapse;max-width:100%}td,th{padding:6px;border:1px solid #ddd}pre{white-space:pre-wrap}</style><body>'+(template.html||'<pre>'+escape(template.text)+'</pre>')+'</body></html>');return true;
}
if(method==='GET'&&(action==='source'||action?.startsWith('attachments/'))){
if(user.role!=='admin')fail('仅管理员可以下载原邮件和附件。',403);let bytes,name;
if(action==='source'){bytes=store.source(id);name='template.eml';}else{const a=template.attachments[Number(index)];if(!a)fail('附件不存在。',404);bytes=Buffer.from(a.content,'base64');name=a.filename;}
response.writeHead(200,{'Content-Type':'application/octet-stream','Content-Disposition':"attachment; filename*=UTF-8''"+encodeURIComponent(name)});response.end(bytes);return true;
}
if(method==='POST'&&action==='confirm'){const saved=store.confirm(id,body,user.username);audit('mail.template.confirm',saved.subject);reply(200,{id:saved.id,status:saved.status,version:saved.version});return true;}
if(method==='POST'&&action==='reject'){store.reject(id,body.version);audit('mail.template.reject',template.subject);reply(200,{ok:true});return true;}
}
fail('没有找到此邮件操作。',404);
}
module.exports={mailApi};
+37
View File
@@ -0,0 +1,37 @@
'use strict';
const {simpleParser}=require('mailparser');const sanitize=require('sanitize-html');
const MAX_MAIL=10*1024*1024;
const fail=message=>{throw Object.assign(new Error(message),{status:400});};
const escape=value=>String(value??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const VARIABLES=['产品线','订单号','日期','订单列表'];
function validateVariables(...parts){for(const part of parts)for(const token of String(part||'').matchAll(/{{([\s\S]*?)}}/g))if(!VARIABLES.includes(token[1].trim()))fail('模板含有不支持的变量,请使用:'+VARIABLES.map(x=>'{{'+x+'}}').join('、'));}
function cleanHtml(html,attachments=[]){
let expandedBytes=Buffer.byteLength(html||'');
const inline=new Map(attachments.filter(a=>a.cid && /^image\/(png|jpeg|gif|webp)$/.test(a.contentType)).map(a=>[a.cid,'data:'+a.contentType+';base64,'+a.content]));
return sanitize(html||'',{allowedTags:['p','br','div','span','b','strong','i','em','u','s','ul','ol','li','blockquote','pre','code','h1','h2','h3','h4','table','thead','tbody','tfoot','tr','th','td','hr','img'],allowedAttributes:{'*':['style'],td:['colspan','rowspan','style'],th:['colspan','rowspan','style'],img:['src','alt','width','height']},allowedStyles:{'*':{'color':[/^#[0-9a-f]{3,8}$/i,/^[a-z]+$/i],'background-color':[/^#[0-9a-f]{3,8}$/i,/^[a-z]+$/i],'text-align':[/^(left|right|center)$/],'font-weight':[/^(bold|normal|[1-9]00)$/],'font-size':[/^\d{1,2}(px|pt)$/],'border':[/^\dpx solid #[0-9a-f]{3,6}$/i],'padding':[/^\d{1,2}px$/]}},allowedSchemes:['data'],allowedSchemesByTag:{img:['data']},transformTags:{img:(tag,attrs)=>{const src=attrs.src?.startsWith('cid:')?(inline.get(attrs.src.slice(4))||''):attrs.src||'';expandedBytes+=src.length;if(expandedBytes>12*1024*1024)fail('内嵌图片展开超过 12 MB,请减少重复图片后重新发送。');return {tagName:'img',attribs:{...attrs,src}};}},exclusiveFilter:frame=>frame.tag==='img'&&!/^data:image\/(png|jpeg|gif|webp);base64,[A-Za-z0-9+/=]+$/.test(frame.attribs.src||'')});
}
async function parseTemplate(raw,channel){
if(!Buffer.isBuffer(raw)||raw.length>MAX_MAIL)fail('邮件超过 10 MB 限制。');
const mail=await simpleParser(raw,{skipImageLinks:true,skipTextToHtml:true,maxHtmlLengthToParse:1024*1024,maxInlinedImagesSize:MAX_MAIL});
const sourceSubject=(mail.subject||'').trim();if(!sourceSubject.startsWith('[模板]'))return null;
let title=sourceSubject.slice(4).trim(),scope='';
if(title.startsWith('[')){const scoped=/^\[([^\[\]\r\n]{1,80})\]\s*(.+)$/u.exec(title);if(!scoped||!scoped[1].trim())fail('模板主题范围或标题不完整。');scope=scoped[1].trim();title=scoped[2].trim();}
if(!title)fail('模板主题缺少发信标题。');
if(mail.inReplyTo || mail.references?.length)fail('回复邮件不作为模板,请新建邮件发送。');
const senders=mail.from?.value||[];const sender=senders[0]?.address?.toLowerCase();
if(senders.length!==1||!(channel.senders||[]).map(x=>x.toLowerCase()).includes(sender))fail('模板发件人不在允许名单中。');
const recipients=[...(mail.to?.value||[]),...(mail.cc?.value||[])].map(x=>x.address?.toLowerCase());if(!recipients.includes(channel.email.toLowerCase()))fail('模板邮件收件人不包含此托管邮箱。');
const subject=title;if(subject.length>300||!subject)fail('发信标题应为 1–300 字。');
if((mail.html||'').length>1024*1024||(mail.text||'').length>200000)fail('模板正文过大。');
const attachments=mail.attachments.map(a=>({filename:(a.filename||'附件').replace(/[\\/\x00-\x1f]/g,'_').slice(0,150),contentType:a.contentType,content:a.content.toString('base64'),cid:a.contentId?.replace(/^<|>$/g,''),size:a.content.length,inline:a.contentDisposition==='inline'}));
const text=mail.text||'',html=cleanHtml(mail.html||'',attachments);if(!text.trim()&&!html.trim())fail('模板正文为空。');validateVariables(subject,text,html);
return {subject,scope,text,html,sender,sourceSubject:mail.subject,messageId:mail.messageId||'',date:mail.date?.toISOString()||'',attachments,notes:[...(html?'': ['纯文本邮件']),...(/(^|\n)\s*(On .+wrote:|发件人[::]|-----Original Message-----|在.+写道[::])/im.test(text)?['正文包含引用内容,请核对后确认。']:[])]};
}
function renderTemplate(template,values){
validateVariables(template.subject,template.text,template.html);
const replace=(input,html)=>String(input||'').replace(/{{\s*(产品线|订单号|日期|订单列表)\s*}}/g,(_,key)=>{if(values[key]===undefined)fail('缺少模板变量:'+key);return html?escape(values[key]).replace(/\r?\n/g,'<br>'):String(values[key]);});
let html=template.html?replace(template.html,true):undefined;
for(const a of template.attachments||[])if(html&&a.cid&&/^[A-Za-z0-9._@+-]{1,200}$/.test(a.cid))html=html.replaceAll('src="data:'+a.contentType+';base64,'+a.content+'"','src="cid:'+a.cid+'"');
return {subject:replace(template.subject,false).replace(/[\r\n]/g,' '),text:replace(template.text,false),html};
}
module.exports={parseTemplate,renderTemplate,cleanHtml,validateVariables,escape,MAX_MAIL};
+29
View File
@@ -0,0 +1,29 @@
'use strict';
const {ImapFlow}=require('imapflow');const nodemailer=require('nodemailer');const {parseTemplate,renderTemplate,MAX_MAIL}=require('./mail-parser.cjs');
const fail=(message,status=502)=>{throw Object.assign(new Error(message),{status});};
const safeError=(error,kind)=>error?.code==='EAUTH'||error?.authenticationFailed?`${kind} 登录失败,请检查账号和授权密码。`:/CERT|TLS|SSL|SELF_SIGNED/.test(error?.code||'')?`${kind} 加密连接失败,请检查服务器地址和证书。`:`${kind} 连接失败,请检查服务器、端口和网络后重试。`;
class MailService{
constructor({store,imapFactory,smtpFactory,interval=60000}){this.store=store;this.imapFactory=imapFactory||((c)=>new ImapFlow({host:c.host,port:c.port,secure:c.security==='tls',doSTARTTLS:c.security==='starttls',auth:{user:c.user,pass:c.password},logger:false,disableAutoIdle:true,connectionTimeout:15000,greetingTimeout:15000,socketTimeout:30000,maxLiteralSize:MAX_MAIL,tls:{rejectUnauthorized:true,minVersion:'TLSv1.2'}}));this.smtpFactory=smtpFactory||((c)=>nodemailer.createTransport({host:c.host,port:c.port,secure:c.security==='tls',requireTLS:c.security==='starttls',auth:{user:c.user,pass:c.password},logger:false,debug:false,connectionTimeout:15000,greetingTimeout:15000,socketTimeout:30000,disableFileAccess:true,disableUrlAccess:true,tls:{rejectUnauthorized:true,minVersion:'TLSv1.2'}}));this.interval=interval;this.running=new Map();this.clients=new Set();this.stopped=false;}
busy(id){return this.running.has(id);}
async exclusive(id,work){if(this.stopped)fail('邮件服务正在停止。',503);if(this.busy(id))fail('此邮箱正在执行操作,请稍后重试。',409);const promise=Promise.resolve().then(work);this.running.set(id,promise);return promise.finally(()=>this.running.delete(id));}
async withImap(config,work){const client=this.imapFactory(config);client.on?.('error',()=>{});this.clients.add(client);try{await client.connect();return await work(client);}finally{try{await client.logout();}catch{}client.close?.();this.clients.delete(client);}}
verify(id){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);let smtp=false,imap=false,message='SMTP 与 IMAP 连接正常';const transport=this.smtpFactory(c.smtp);this.clients.add(transport);try{try{await transport.verify();smtp=true;}catch(e){message=safeError(e,'SMTP');}try{await this.withImap(c.imap,async client=>{const lock=await client.getMailboxLock('INBOX',{readOnly:true});lock.release();});imap=true;}catch(e){message+=(smtp?'':';')+(smtp?'': ' ');message=smtp?safeError(e,'IMAP'):message+safeError(e,'IMAP');}this.store.setState(id,c.version,{checkedAt:new Date().toISOString(),smtp,imap,message});return this.store.publicChannel(id);}finally{transport.close?.();this.clients.delete(transport);}});}
poll(id){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);if(!c.enabled)fail('请先启用此邮箱的模板收信。',409);let imported=0,rejected=0;try{
await this.withImap(c.imap,async client=>{const lock=await client.getMailboxLock('INBOX',{readOnly:true});try{const epoch=String(client.mailbox.uidValidity),cursor=this.store.cursor(id);const sameEpoch=cursor.epoch===epoch;const last=sameEpoch?(cursor.uid||0):0;const query={since:new Date(sameEpoch&&cursor.since?cursor.since:Date.now()-7*86400000),...(last?{uid:(last+1)+':*'}:{})};const found=await client.search(query,{uid:true});const uids=(found||[]).filter(uid=>uid>last).sort((a,b)=>a-b).slice(0,50);
for(const uid of uids){if(this.stopped)break;this.store.guard(id,c.version);const info=await client.fetchOne(uid,{envelope:true,size:true},{uid:true});if(!info){this.store.skip(id,epoch,uid,'skipped','邮件已移除',c.version);continue;}
if(!/^\[模板\]/.test((info.envelope?.subject||'').trim())){this.store.transaction(()=>{this.store.guard(id,c.version);this.store.advance(id,epoch,uid);});continue;}
if(!Number.isFinite(info.size)||info.size>MAX_MAIL){this.store.skip(id,epoch,uid,'rejected','邮件超过 10 MB 限制',c.version);rejected++;continue;}
const source=await client.fetchOne(uid,{source:true},{uid:true});if(!source){this.store.skip(id,epoch,uid,'skipped','邮件已移除',c.version);continue;}
let parsed;try{parsed=await parseTemplate(source.source,c);}catch(e){this.store.skip(id,epoch,uid,'rejected',e.status===400?e.message:'邮件格式无法解析,请重新发送模板。',c.version);rejected++;continue;}
if(parsed){const result=this.store.ingest(id,epoch,uid,parsed,source.source,c.version);if(result.created)imported++;}else this.store.skip(id,epoch,uid,'skipped','未包含模板指令',c.version);
}
// Persist an empty mailbox epoch too, without skipping future messages.
if(!uids.length&&!sameEpoch)this.store.transaction(()=>{this.store.guard(id,c.version);this.store.advance(id,epoch,0);});
}finally{lock.release();}});
this.store.setState(id,c.version,{imap:true,pollAt:new Date().toISOString(),message:`收信完成:新增 ${imported} 个模板,${rejected} 封未导入`});return {imported,rejected};
}catch(error){if(error.status===409)throw error;const message=safeError(error,'IMAP');try{this.store.setState(id,c.version,{imap:false,pollAt:new Date().toISOString(),message});}catch{}fail(message);}});}
sendTest(id,templateId){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id),t=this.store.template(templateId);if(t.channelId!==id||t.status!=='active')fail('请选择此邮箱已确认生效的模板。',409);const values={'产品线':t.scope||'默认','订单号':'TEST','日期':new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date()),'订单列表':'测试订单 TEST'};const rendered=renderTemplate(t,values);const transport=this.smtpFactory(c.smtp);this.clients.add(transport);let sendId;try{await transport.verify();this.store.guard(id,c.version);sendId=this.store.beginSend(id,t.id);const result=await transport.sendMail({from:{address:c.email,name:c.name},to:{address:c.email},subject:'[测试] '+rendered.subject,text:rendered.text,html:rendered.html,messageId:`<${sendId}@${c.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true,attachments:t.attachments.map(a=>({filename:a.filename,content:Buffer.from(a.content,'base64'),contentType:a.contentType,...(a.cid?{cid:a.cid}:{}),contentDisposition:a.inline?'inline':'attachment'}))});if(!result.accepted?.length)throw new Error('Recipient rejected');this.store.finishSend(sendId,'sent');return {id:sendId,status:'sent',to:c.email};}catch(e){if(sendId)this.store.finishSend(sendId,'unknown');if(e.status===409)throw e;fail(sendId?'发信结果待核对,请检查本邮箱后再决定是否重试。':safeError(e,'SMTP'));}finally{transport.close?.();this.clients.delete(transport);}});}
start(){this.stopped=false;const tick=()=>{for(const c of this.store.channels())if(c.enabled&&!this.busy(c.id))this.poll(c.id).catch(()=>{});};this.timer=setInterval(tick,this.interval);this.timer.unref?.();this.startTimer=setTimeout(tick,2000);this.startTimer.unref?.();}
async stop(){this.stopped=true;clearInterval(this.timer);clearTimeout(this.startTimer);for(const client of this.clients)try{client.close?.();}catch{}await Promise.allSettled([...this.running.values()]);}
}
module.exports={MailService};
+66
View File
@@ -0,0 +1,66 @@
'use strict';
const path=require('node:path');const crypto=require('node:crypto');const {DatabaseSync}=require('node:sqlite');const {BpmVault}=require('./bpm-vault.cjs');const {validateVariables}=require('./mail-parser.cjs');
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
const email=value=>{if(typeof value!=='string'||value.length>254||!/^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?\.[A-Za-z]{2,63}$/.test(value.trim()))fail('请输入有效的邮箱地址。');return value.trim().toLowerCase();};
const text=(v,label,max=200)=>{if(typeof v!=='string'||!v.trim()||v.length>max||/[\x00-\x1f]/.test(v))fail(label+'格式不正确。');return v.trim();};
const at=()=>new Date().toISOString();const hash=raw=>crypto.createHash('sha256').update(raw).digest('hex');
class MailStore{
constructor(dir){this.vault=new BpmVault({stateDir:path.join(dir,'secrets')});this.db=new DatabaseSync(path.join(dir,'mail.sqlite'));this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
CREATE TABLE IF NOT EXISTS channels(id TEXT PRIMARY KEY,email TEXT NOT NULL UNIQUE,version INTEGER NOT NULL,payload BLOB NOT NULL,state TEXT NOT NULL,cursor TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS templates(id TEXT PRIMARY KEY,channel_id TEXT NOT NULL,source_key TEXT NOT NULL,scope TEXT NOT NULL,status TEXT NOT NULL,version INTEGER NOT NULL,base_id TEXT,payload BLOB NOT NULL,created_at TEXT NOT NULL,UNIQUE(channel_id,source_key));
CREATE UNIQUE INDEX IF NOT EXISTS active_template ON templates(channel_id,scope) WHERE status='active';
CREATE TABLE IF NOT EXISTS receipts(id INTEGER PRIMARY KEY,channel_id TEXT NOT NULL,epoch TEXT NOT NULL,uid INTEGER NOT NULL,status TEXT NOT NULL,detail TEXT NOT NULL,at TEXT NOT NULL,UNIQUE(channel_id,epoch,uid));
CREATE TABLE IF NOT EXISTS sends(id TEXT PRIMARY KEY,channel_id TEXT NOT NULL,template_id TEXT NOT NULL,status TEXT NOT NULL,at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY,value TEXT NOT NULL);`);
if(!this.db.prepare('PRAGMA table_info(templates)').all().some(c=>c.name==='summary'))this.db.exec("ALTER TABLE templates ADD COLUMN summary TEXT NOT NULL DEFAULT '{}'");
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);}
}
summary(p){return JSON.stringify({subject:p.subject,sender:p.sender,attachmentCount:p.attachments.length});}
recoverSends(){this.db.prepare("UPDATE sends SET status='unknown' WHERE status='sending'").run();}
transaction(work){this.db.exec('BEGIN IMMEDIATE');try{const result=work();this.db.exec('COMMIT');return result;}catch(e){this.db.exec('ROLLBACK');throw e;}}
encode(id,value){try{return this.vault.encode(id,value);}catch{fail('邮件加密存储不可用,请联系管理员。',503);}}
decode(id,value){try{return this.vault.decode(id,value);}catch{fail('邮件加密存储不可用,请联系管理员。',503);}}
row(id){const row=this.db.prepare('SELECT * FROM channels WHERE id=?').get(id);if(!row)fail('邮箱不存在。',404);return row;}
channelSecret(id){const row=this.row(id);return {...this.decode(id,row.payload),id,version:row.version};}
publicChannel(id){const c=this.channelSecret(id),state=JSON.parse(this.row(id).state);return {...c,smtp:{...c.smtp,password:undefined,hasPassword:!!c.smtp.password},imap:{...c.imap,password:undefined,hasPassword:!!c.imap.password},state};}
channels(){return this.db.prepare('SELECT id FROM channels ORDER BY rowid').all().map(r=>this.publicChannel(r.id));}
saveChannel(input){return this.transaction(()=>{
if(!input||typeof input!=='object')fail('邮箱配置无效。');const old=input.id?this.channelSecret(input.id):null;if(old&&old.version!==input.version)fail('邮箱已被修改,请刷新后重试。',409);
const id=old?.id||crypto.randomUUID(),address=email(input.email);const existing=this.db.prepare('SELECT id FROM channels WHERE email=?').get(address);if(existing&&existing.id!==id)fail('此邮箱已托管,请使用已有邮箱。',409);
if(typeof input.enabled!=='boolean'||!Array.isArray(input.senders)||!input.senders.length||input.senders.length>100)fail('请填写模板发件人名单,并选择是否启用收信。');
const endpoint=kind=>{const v=input[kind];if(!v||!['tls','starttls'].includes(v.security)||!Number.isInteger(v.port)||v.port<1||v.port>65535)fail(kind.toUpperCase()+' 端口或加密方式无效。');const host=text(v.host,'服务器地址',253);if(!/^[a-zA-Z0-9.:-]+$/.test(host)||host.startsWith('-'))fail('服务器地址只填写主机名或 IP。');const password=v.password===''&&old?old[kind].password:v.password;if(typeof password!=='string'||!password||password.length>2048)fail('请输入 '+kind.toUpperCase()+' 密码或授权码。');const user=text(v.user,'登录账号',254);if(old&&v.password===''&&(old.email!==address||old[kind].user!==user||old[kind].host!==host))fail('更换邮箱、服务器或登录账号时,请重新填写密码。');return {host,port:v.port,security:v.security,user,password};};
const saved={name:text(input.name,'邮箱名称',80),email:address,smtp:endpoint('smtp'),imap:endpoint('imap'),senders:[...new Set(input.senders.map(email))],enabled:input.enabled,createdAt:old?.createdAt||at(),updatedAt:at()};
const reset=!old||old.email!==address||JSON.stringify(old.imap)!==JSON.stringify(saved.imap);const oldrow=old?this.row(id):null;
const changed=reset||JSON.stringify(old?.smtp)!==JSON.stringify(saved.smtp);const state=changed?{checkedAt:null,smtp:false,imap:false,pollAt:null,message:'待检查连接'}:JSON.parse(oldrow.state);
this.db.prepare('INSERT INTO channels VALUES(?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET email=excluded.email,version=excluded.version,payload=excluded.payload,state=excluded.state,cursor=excluded.cursor').run(id,address,(old?.version||0)+1,this.encode(id,saved),JSON.stringify(state),reset?'{}':oldrow.cursor);return this.publicChannel(id);
});}
guard(id,version){if(this.row(id).version!==version)fail('邮箱配置已变化,请重试。',409);}
setState(id,version,patch){this.guard(id,version);this.db.prepare('UPDATE channels SET state=? WHERE id=?').run(JSON.stringify({...JSON.parse(this.row(id).state),...patch}),id);}
cursor(id){return JSON.parse(this.row(id).cursor);}
advance(id,epoch,uid){const prior=this.cursor(id);this.db.prepare('UPDATE channels SET cursor=? WHERE id=?').run(JSON.stringify({epoch:String(epoch),uid,since:prior.epoch===String(epoch)&&prior.since?prior.since:new Date(Date.now()-7*86400000).toISOString()}),id);}
receipt(id,epoch,uid,status,detail){this.db.prepare('INSERT OR IGNORE INTO receipts(channel_id,epoch,uid,status,detail,at) VALUES(?,?,?,?,?,?)').run(id,String(epoch),uid,status,detail,at());this.db.prepare('DELETE FROM receipts WHERE channel_id=? AND id NOT IN (SELECT id FROM receipts WHERE channel_id=? ORDER BY id DESC LIMIT 500)').run(id,id);}
skip(id,epoch,uid,status,detail,version){return this.transaction(()=>{this.guard(id,version);this.receipt(id,epoch,uid,status,detail);this.advance(id,epoch,uid);});}
receipts(){return this.db.prepare('SELECT * FROM receipts ORDER BY id DESC LIMIT 100').all();}
ingest(channelId,epoch,uid,parsed,raw,configVersion){return this.transaction(()=>{
this.guard(channelId,configVersion);const key=parsed.messageId?hash(parsed.messageId+'\0'+hash(raw)):hash(raw);const old=this.db.prepare('SELECT id FROM templates WHERE channel_id=? AND source_key=?').get(channelId,key);
let id=old?.id;if(!id){id=crypto.randomUUID();const payload={...parsed,raw:raw.toString('base64')};const base=this.activeId(channelId,parsed.scope);this.db.prepare('INSERT INTO templates VALUES(?,?,?,?,?,?,?,?,?,?)').run(id,channelId,key,parsed.scope,'pending',1,base,this.encode(id,payload),at(),this.summary(parsed));}
this.receipt(channelId,epoch,uid,old?'duplicate':'pending',old?'已识别,未重复导入':'待确认模板');this.advance(channelId,epoch,uid);return {...this.template(id),created:!old};
});}
template(id){const r=this.db.prepare('SELECT * FROM templates WHERE id=?').get(id);if(!r)fail('模板不存在。',404);return {...this.decode(id,r.payload),id:r.id,channelId:r.channel_id,scope:r.scope,status:r.status,version:r.version,baseId:r.base_id,createdAt:r.created_at};}
templates(){return ['pending','active','archived','rejected'].flatMap(status=>this.db.prepare('SELECT id,channel_id,scope,status,version,created_at,summary FROM templates WHERE status=? ORDER BY created_at DESC,rowid DESC LIMIT 200').all(status).map(r=>({...JSON.parse(r.summary),id:r.id,channelId:r.channel_id,scope:r.scope,status:r.status,version:r.version,createdAt:r.created_at})));}
stats(){return Object.fromEntries(this.db.prepare('SELECT status,COUNT(*) AS count FROM templates GROUP BY status').all().map(r=>[r.status,r.count]));}
activeId(channelId,scope){return this.db.prepare("SELECT id FROM templates WHERE channel_id=? AND scope=? AND status='active'").get(channelId,scope)?.id||null;}
active(channelId,scope){const r=this.db.prepare("SELECT id FROM templates WHERE channel_id=? AND scope=? AND status='active'").get(channelId,scope);return r?this.template(r.id):null;}
confirm(id,input,actor){return this.transaction(()=>{const t=this.template(id);if(t.status!=='pending'||input.version!==t.version)fail('模板状态已变化,请刷新。',409);if(t.channelId==='legacy'){this.row(input.channelId);t.channelId=input.channelId;}const subject=text(input.subject,'邮件标题',300);if(typeof input.scope!=='string'||input.scope.length>80||/[\[\]\x00-\x1f]/.test(input.scope))fail('产品线格式无效。');const scope=input.scope.trim(),current=this.activeId(t.channelId,scope);if(current!==(scope===t.scope?t.baseId:null))fail('该范围已有更新的模板,请重新导入后确认。',409);
if(typeof input.useText!=='boolean')fail('正文模式无效。');if(input.useText){if(typeof input.text!=='string'||!input.text.trim()||input.text.length>200000)fail('正文应为 1–200000 字。');t.text=input.text;t.html='';}
validateVariables(subject,t.text,t.html);const payload={...t,subject,scope,confirmedBy:actor,confirmedAt:at()};delete payload.id;this.db.prepare("UPDATE templates SET status='archived',version=version+1 WHERE channel_id=? AND scope=? AND status='active'").run(t.channelId,scope);this.db.prepare("UPDATE templates SET channel_id=?,scope=?,status='active',version=version+1,payload=?,summary=? WHERE id=?").run(t.channelId,scope,this.encode(id,payload),this.summary(payload),id);return this.template(id);
});}
reject(id,version){const t=this.template(id);if(t.status!=='pending'||t.version!==version)fail('模板状态已变化。',409);this.db.prepare("UPDATE templates SET status='rejected',version=version+1 WHERE id=?").run(id);}
source(id){return Buffer.from(this.template(id).raw||'','base64');}
migrateLegacy(legacy){if(this.db.prepare("SELECT 1 FROM meta WHERE key='legacy'").get())return;this.transaction(()=>{if(legacy?.subject?.trim()&&legacy?.body?.trim()){const id=crypto.randomUUID(),payload={subject:legacy.subject,text:legacy.body,html:'',sender:'工作台旧草稿',sourceSubject:legacy.subject,attachments:[],notes:['从原模板草稿迁入,请选择托管邮箱后确认。']};this.db.prepare('INSERT INTO templates VALUES(?,?,?,?,?,?,?,?,?,?)').run(id,'legacy','legacy','','pending',1,null,this.encode(id,payload),at(),this.summary(payload));}this.db.prepare("INSERT INTO meta VALUES('legacy','1')").run();});}
beginSend(channelId,templateId){const id=crypto.randomUUID();this.db.prepare('INSERT INTO sends VALUES(?,?,?,?,?)').run(id,channelId,templateId,'sending',at());return id;}
finishSend(id,status){this.db.prepare('UPDATE sends SET status=? WHERE id=?').run(status,id);}
sends(){return this.db.prepare('SELECT * FROM sends ORDER BY at DESC LIMIT 50').all();}
close(){if(this.db){this.db.close();this.db=null;}this.vault.destroy();}
}
module.exports={MailStore,email};
+24
View File
@@ -0,0 +1,24 @@
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
function loadPlaywright() {
const candidates = [
'playwright-core',
process.env.ORDER_PLAYWRIGHT_MODULE,
path.join(os.homedir(), '.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright-core')
].filter(Boolean);
for (const candidate of candidates) {
try { return require(candidate); } catch (error) { if (error.code !== 'MODULE_NOT_FOUND') throw error; }
}
throw new Error('缺少 playwright-core,请先运行 npm install。');
}
function browserOptions() {
const candidates = [process.env.ORDER_CHROME_PATH,
process.env.PROGRAMFILES && path.join(process.env.PROGRAMFILES, 'Google/Chrome/Application/chrome.exe'),
process.env['PROGRAMFILES(X86)'] && path.join(process.env['PROGRAMFILES(X86)'], 'Google/Chrome/Application/chrome.exe'),
process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, 'Google/Chrome/Application/chrome.exe')].filter(Boolean);
const executablePath = candidates.find(candidate => fs.existsSync(candidate));
return executablePath ? { executablePath, headless: true } : { channel: 'chrome', headless: true };
}
module.exports = { loadPlaywright, browserOptions };
+25
View File
@@ -0,0 +1,25 @@
// Plan calculation only. A mail connector must exist before execution is enabled.
function dayPolicy(date,schedule,overrides=[]) {
const key=typeof date==='string'?date:new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(date);
const override=overrides.find(item=>item.date===key);
if(override)return {scan:override.kind==='pause'?false:override.scan,send:override.kind==='pause'?false:override.send,kind:override.kind,note:override.note || ''};
const working=schedule.weekends || ![0,6].includes(new Date(key+'T00:00:00Z').getUTCDay());
return {scan:working,send:working,kind:working?'workday':'restday',note:''};
}
function nextSlots(schedule, from=new Date(), count=2, overrides=[]) {
const shifted=new Date(from.getTime()+8*3600000);
const midnight=Date.UTC(shifted.getUTCFullYear(),shifted.getUTCMonth(),shifted.getUTCDate());
const slots=[];
for(let day=0;day<370 && slots.length<count;day++) {
const date=new Date(midnight+day*86400000);
if(!dayPolicy(date.toISOString().slice(0,10),schedule,overrides).send)continue;
for(const time of [...schedule.times].sort()) {
const [hour,minute]=time.split(':').map(Number);
const utc=date.getTime()+hour*3600000+minute*60000-8*3600000;
if(utc>from.getTime())slots.push(new Date(utc).toISOString());
if(slots.length>=count)break;
}
}
return slots;
}
module.exports={nextSlots,dayPolicy};
+140
View File
@@ -0,0 +1,140 @@
const http = require('node:http');
const crypto = require('node:crypto');
const fs = require('node:fs/promises');
const path = require('node:path');
const os = require('node:os');
const { renderSnapshot, validateSnapshot } = require('./exporter.cjs');
const { Store } = require('./dashboard-store.cjs');
const { createDashboard } = require('./dashboard.cjs');
const { WorkspaceStore } = require('./workspace-store.cjs');
const { BpmSessionManager } = require('./bpm-session-manager.cjs');
const { BpmCustodian } = require('./bpm-custodian.cjs');
const { MailStore } = require('./mail-store.cjs');
const { MailService } = require('./mail-service.cjs');
const { BpmScanStore } = require('./bpm-scan-store.cjs');
const { BpmScanner } = require('./bpm-scanner.cjs');
function createServer(options) {
let busy = false;
const jobs = new Map();
const maxBytes = options.maxBodyBytes || 20 * 1024 * 1024;
return http.createServer(async (request, response) => {
const reply = (status, body) => { response.writeHead(status, { 'Content-Type':'application/json; charset=utf-8', 'Cache-Control':'no-store' }); response.end(JSON.stringify(body)); };
const origin = request.headers.origin || '';
if (!/^chrome-extension:\/\/[a-p]{32}$/.test(origin)) return reply(403, {error:'仅接受已配对的浏览器扩展。'});
response.setHeader('Access-Control-Allow-Origin', origin);
response.setHeader('Vary', 'Origin');
if (request.method === 'OPTIONS') {
response.setHeader('Access-Control-Allow-Methods','GET, POST, OPTIONS');
response.setHeader('Access-Control-Allow-Headers','Content-Type, X-Order-Token');
response.setHeader('Access-Control-Allow-Private-Network','true');
response.writeHead(204); response.end(); return;
}
const supplied = Buffer.from(String(request.headers['x-order-token'] || ''));
const expected = Buffer.from(options.token);
if (supplied.length !== expected.length || !crypto.timingSafeEqual(supplied, expected)) return reply(401, {error:'配对失效,请重新加载扩展。'});
if (request.method === 'GET' && request.url === '/health') return reply(200, {ok:true,version:'0.1.0',busy});
const jobRoute = /^\/jobs\/([a-f0-9]{32})$/.exec(request.url);
if (request.method === 'GET' && jobRoute) return jobs.has(jobRoute[1]) ? reply(200,jobs.get(jobRoute[1])) : reply(404,{error:'任务已过期,请检查输出目录后重试。'});
if (request.method !== 'POST' || request.url !== '/export') return reply(404, {error:'未知操作。'});
if (!/^application\/json(?:;|$)/i.test(request.headers['content-type'] || '')) return reply(415, {error:'需要 JSON 数据。'});
if (Number(request.headers['content-length'] || 0) > maxBytes) { request.resume(); return reply(413, {error:'页面超过 20 MB 限制。'}); }
if (busy) return reply(409, {error:'正在导出其他订单,请稍后重试。'});
try {
const raw = await new Promise((resolve, reject) => {
const chunks = []; let total = 0; let overflow = false;
request.on('data', chunk => { total += chunk.length; if (total > maxBytes) { if (!overflow) { overflow=true; reject(Object.assign(new Error('页面过大。'),{status:413})); } } else if (!overflow) chunks.push(chunk); });
request.on('end', () => { if (!overflow) resolve(Buffer.concat(chunks).toString('utf8')); });
request.on('error', reject);
});
let snapshot;
try { snapshot = JSON.parse(raw); validateSnapshot(snapshot); } catch(error) { return reply(400, {error:error instanceof SyntaxError ? '页面数据不是有效 JSON。' : error.message}); }
if (busy) return reply(409,{error:'正在导出其他订单,请稍后重试。'});
busy = true;
const jobId = crypto.randomBytes(16).toString('hex');
if (jobs.size >= 20) jobs.delete(jobs.keys().next().value);
jobs.set(jobId,{status:'running',jobId});
try { options.store?.recordJob({jobId,status:'running',metadata:snapshot.metadata}); }
catch(error) {busy=false;jobs.delete(jobId);throw error;}
reply(202,{status:'running',jobId});
renderSnapshot(snapshot, options).then(result => {
options.store?.recordJob({status:'success',jobId,...result});
jobs.set(jobId,{status:'success',jobId,...result});
console.log(`已保存:${result.filename} (${result.bytes} bytes)`);
}).catch(error=>{const failed={status:'error',jobId,error:error.message || '导出失败。'};jobs.set(jobId,failed);try{options.store?.recordJob(failed);}catch(storeError){console.error('保存任务状态失败:'+storeError.message);}}).finally(()=>{busy=false;});
} catch(error) { if (!response.writableEnded) reply(error.status || 500,{error:error.message || '导出失败。'}); }
});
}
async function startService(options) {
// Complete file preparation before opening a socket: failed startup must exit cleanly.
await fs.mkdir(options.installedExtension,{recursive:true});
await fs.cp(options.extensionSourceDir,options.installedExtension,{recursive:true,filter:source => path.basename(source) !== 'local-config.js'});
await fs.writeFile(path.join(options.installedExtension,'local-config.js'),'globalThis.ORDER_LOCAL_CONFIG = '+JSON.stringify({endpoint:`http://127.0.0.1:${options.port}`,token:options.token})+';\n');
const server = createServer(options);
await new Promise((resolve,reject) => { server.once('error',reject); server.listen(options.port,'127.0.0.1',resolve); });
return server;
}
async function main(options = {}) {
const root = path.resolve(__dirname,'..');
let config = options.config;
if(!config){
config={};
try { config = JSON.parse(await fs.readFile(path.join(root,'config.json'),'utf8')); } catch(error) { if(error.code !== 'ENOENT') throw error; }
}
const port = config.port || 18765;
if (!Number.isInteger(port) || port < 1024 || port > 65535) throw new Error('端口需为 1024–65535。');
const stateDir = options.stateDir || path.join(process.env.LOCALAPPDATA || os.homedir(),'OrderNotificationAutomation');
await fs.mkdir(stateDir,{recursive:true});
const tokenPath = path.join(stateDir,'pairing.key');
let token;
try { token = (await fs.readFile(tokenPath,'utf8')).trim(); } catch(error) { if(error.code !== 'ENOENT') throw error; token=crypto.randomBytes(32).toString('hex'); await fs.writeFile(tokenPath,token,{mode:0o600}); }
if (!/^[a-f0-9]{64}$/.test(token)) throw new Error('本地配对文件损坏,请删除 pairing.key 后重启。');
const outputDir = path.resolve(root,config.outputDir || 'output/pdf');
const installedExtension = path.join(stateDir,'extension');
const dashboardConfig=config.dashboard || {};
const dashboardPort=dashboardConfig.port ?? 18766;
const dashboardHost=dashboardConfig.host || '0.0.0.0';
if(!Number.isInteger(dashboardPort) || dashboardPort<1024 || dashboardPort>65535 || dashboardPort===port)throw new Error('Web 看板端口需为 1024–65535,且不能与扩展服务相同。');
if(!['0.0.0.0','127.0.0.1'].includes(dashboardHost))throw new Error('Web 看板 host 请设置为 0.0.0.0(局域网)或 127.0.0.1(仅本机)。');
if(dashboardConfig.trustedProxy!==undefined && typeof dashboardConfig.trustedProxy!=='boolean')throw new Error('dashboard.trustedProxy 必须为布尔值。');
const store=new Store(path.join(stateDir,'dashboard'));
const workspace=new WorkspaceStore(path.join(stateDir,'workspace'));
const bpmSessions=new BpmSessionManager({stateDir:path.join(stateDir,'bpm-sessions')});
const custodian=new BpmCustodian({workspace,manager:bpmSessions});
let server;
let dashboard;
let mailStore,mail,scanStore,scanner;
try {
mailStore=new MailStore(path.join(stateDir,'mail'));mail=new MailService({store:mailStore});
mailStore.migrateLegacy(store.settings().templates);
scanStore=new BpmScanStore(path.join(stateDir,'bpm-scan'));scanner=new BpmScanner({store:scanStore,workspace,manager:bpmSessions,settings:()=>store.settings()});
await bpmSessions.migrateAccounts(workspace.snapshot().connections);
workspace.markSessionChecksPending();
server=await startService({token,port,outputDir,scale:config.scale,installedExtension,extensionSourceDir:path.join(root,'extension'),store});
dashboard=createDashboard({store,workspace,outputDir,bpmSessions,mail,scanner,trustedProxy:dashboardConfig.trustedProxy===true});
await new Promise((resolve,reject)=>{dashboard.once('error',reject);dashboard.listen(dashboardPort,dashboardHost,resolve);});store.recoverJobs();mailStore.recoverSends();custodian.start();mail.start();scanner.start();
}
catch(error){if(server?.listening)await new Promise(resolve=>server.close(resolve));if(dashboard?.listening)await new Promise(resolve=>dashboard.close(resolve));await scanner?.stop();scanStore?.close();await mail?.stop();mailStore?.close();await bpmSessions.shutdown();workspace.close();throw error;}
if(!options.quiet){
console.log('订单通知中心已启动。\nWeb 工作台支持业务日历、异常待办与转交、BPM 连接管理。\n在 Chrome 订单页仍可点击扩展中的“导出当前订单”。');
console.log(`首次使用:Chrome 扩展管理 → 开发者模式 → 加载已解压的扩展程序\n选择目录:${installedExtension}\n输出目录:${outputDir}\n本地服务:http://127.0.0.1:${port}`);
console.log(`Web 看板:http://127.0.0.1:${dashboardPort}\n${store.users().length?'使用已创建的工作台账号登录。':'首次请在部署机创建管理员。'}`);
if(dashboardHost==='0.0.0.0')for(const list of Object.values(os.networkInterfaces()))for(const address of list || [])if(address.family==='IPv4' && !address.internal)console.log(`局域网地址:http://${address.address}:${dashboardPort}`);
}
let stopping;
const stop=()=>stopping ||= (async()=>{
await scanner.stop();await mail.stop();await custodian.stop();await bpmSessions.shutdown();
await Promise.all([dashboard,server].map(socket=>new Promise((resolve,reject)=>socket.close(error=>error?reject(error):resolve()))));
workspace.close();
mailStore.close();
scanStore.close();
})();
return {server,dashboard,workspace,bpmSessions,custodian,mail,scanner,stop};
}
if (require.main === module) main().then(app=>{
const stop=()=>app.stop().then(()=>process.exit(0),()=>process.exit(1));
process.once('SIGINT',stop);process.once('SIGTERM',stop);
}).catch(error => { console.error('启动失败:'+error.message); process.exitCode=1; });
module.exports = { createServer, startService, main };
+15
View File
@@ -0,0 +1,15 @@
// This router is called only after dashboard authentication and same-origin validation.
function workspaceApi({workspace,store,user,route,method,body,reply,bpmSessions}){
if(!workspace)return false;
const members=()=>store.users();
if(route==='/api/workspace' && method==='GET'){const snapshot=workspace.snapshot(members());snapshot.capabilities.remoteLogin=Boolean(bpmSessions);reply(200,snapshot);return true;}
if(method!=='POST')return false;
if(route==='/api/calendar'){reply(200,workspace.saveCalendar(body,user));return true;}
if(route==='/api/exceptions'){reply(201,workspace.createException(body,user,members()));return true;}
const action=/^\/api\/exceptions\/([\w-]+)\/action$/.exec(route);if(action){reply(200,workspace.actOnException(action[1],body,user,members()));return true;}
if(route==='/api/connections'){reply(201,workspace.createConnection(body,user,members()));return true;}
const disable=/^\/api\/connections\/([\w-]+)\/disable$/.exec(route);if(disable){if(Object.keys(body).length)throw Object.assign(new Error('停用连接不接受额外数据。'),{status:400});reply(200,workspace.disableConnection(disable[1],user));return true;}
if(route==='/api/supervisor'){reply(200,workspace.saveSupervisor(body,user,members()));return true;}
return false;
}
module.exports={workspaceApi};
+130
View File
@@ -0,0 +1,130 @@
const fs=require('node:fs');const path=require('node:path');const crypto=require('node:crypto');const {DatabaseSync}=require('node:sqlite');
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
const object=(input,keys)=>{if(!input || Array.isArray(input) || typeof input!=='object' || Object.keys(input).some(key=>!keys.includes(key)))fail('数据格式不正确或包含不支持的字段。');};
const text=(value,label,max,required=false)=>{if(typeof value!=='string' || value.length>max || (required && !value.trim()))fail(`${label}格式不正确。`);return value.trim();};
const version=value=>{if(!Number.isSafeInteger(value) || value<1)fail('版本号不正确。');};
const authorize=(actor,roles)=>{if(!actor || typeof actor.username!=='string' || !roles.includes(actor.role))fail('当前账号没有执行此操作的权限。',403);};
const owner=(value,members,required=false)=>{const name=text(value,'负责人',40,required);if(name && !members?.some(user=>user.username===name && ['admin','operator'].includes(user.role)))fail('请选择有效的管理员或操作员作为负责人。');return name;};
const validDate=date=>typeof date==='string' && /^\d{4}-\d{2}-\d{2}$/.test(date) && date>='0001-01-01' && date<='9999-12-31' && !Number.isNaN(Date.parse(date+'T00:00:00Z')) && new Date(date+'T00:00:00Z').toISOString().slice(0,10)===date;
class WorkspaceStore {
constructor(dir){
fs.mkdirSync(dir,{recursive:true});this.db=new DatabaseSync(path.join(dir,'workspace.sqlite'));
this.db.exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON;
CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS exceptions(id TEXT PRIMARY KEY,value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS connections(id TEXT PRIMARY KEY,value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS audit(seq INTEGER PRIMARY KEY AUTOINCREMENT,value TEXT NOT NULL);`);
const insert=this.db.prepare('INSERT OR IGNORE INTO metadata(key,value) VALUES(?,?)');
insert.run('calendar',JSON.stringify({version:1,overrides:[]}));insert.run('supervisor',JSON.stringify({version:1,defaultOwner:'',notifyChannel:'none',maxAttempts:0}));
this.transaction(()=>{for(const row of this.db.prepare('SELECT id,value FROM connections').all()){
const item=JSON.parse(row.value);if(!('detailUrl' in item) && !item.checks?.detail && item.status!=='partial')continue;
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);
}});
}
transaction(work){this.db.exec('BEGIN IMMEDIATE');try{const result=work();this.db.exec('COMMIT');return result;}catch(error){this.db.exec('ROLLBACK');throw error;}}
meta(key){return JSON.parse(this.db.prepare('SELECT value FROM metadata WHERE key=?').get(key).value);}
setMeta(key,value){this.db.prepare('UPDATE metadata SET value=? WHERE key=?').run(JSON.stringify(value),key);}
record(actor,action,detail){this.db.prepare('INSERT INTO audit(value) VALUES(?)').run(JSON.stringify({id:crypto.randomUUID(),at:new Date().toISOString(),actor:actor.username,action,detail}));this.db.exec('DELETE FROM audit WHERE seq <= (SELECT COALESCE(MAX(seq),0)-2000 FROM audit)');}
snapshot(members=[]){
return this.transaction(()=>{
const calendar=this.meta('calendar'),supervisor=this.meta('supervisor');
const exceptions=this.db.prepare('SELECT value FROM exceptions ORDER BY rowid DESC').all().map(row=>JSON.parse(row.value));
const connections=this.db.prepare('SELECT value FROM connections ORDER BY rowid DESC').all().map(row=>JSON.parse(row.value));
const audit=this.db.prepare('SELECT value FROM audit ORDER BY seq DESC LIMIT 2000').all().map(row=>JSON.parse(row.value));
return {calendar,exceptions,connections,supervisor,audit,members:members.map(({username,role})=>({username,role})),capabilities:{remoteLogin:false,zcode:false,automaticProcessing:false},stats:{open:exceptions.filter(e=>e.status==='open').length,inProgress:exceptions.filter(e=>e.status==='in_progress').length,verifying:exceptions.filter(e=>e.status==='verifying').length,resolved:exceptions.filter(e=>e.status==='resolved').length,connections:connections.filter(c=>c.status!=='disabled').length,overrides:calendar.overrides.length}};
});
}
saveCalendar(input,actor){
authorize(actor,['admin']);object(input,['version','overrides']);version(input.version);
if(!Array.isArray(input.overrides) || input.overrides.length>1500)fail('日期覆盖格式不正确,最多保存 1500 天。');
const dates=new Set();const overrides=input.overrides.map(item=>{object(item,['date','kind','scan','send','note']);if(!validDate(item.date) || dates.has(item.date))fail('日期不存在或重复。');dates.add(item.date);if(!['workday','restday','pause'].includes(item.kind) || typeof item.scan!=='boolean' || typeof item.send!=='boolean')fail('日历选项不正确。');if(item.kind==='pause' && (item.scan || item.send))fail('暂停日期必须同时停止采集和发送。');return {date:item.date,kind:item.kind,scan:item.scan,send:item.send,note:text(item.note,'备注',1000)};}).sort((a,b)=>a.date.localeCompare(b.date));
return this.transaction(()=>{const previous=this.meta('calendar');if(previous.version!==input.version)fail('日历已被其他人更新,请刷新后重试。',409);const saved={version:previous.version+1,overrides};this.setMeta('calendar',saved);this.record(actor,'保存业务日历',`${overrides.length} 个日期覆盖`);return saved;});
}
createException(input,actor,members){
authorize(actor,['admin','operator']);object(input,['title','component','priority','description','owner']);
const title=text(input.title,'标题',200,true),description=text(input.description,'说明',10000),assigned=owner(input.owner,members);
if(!['bpm','pdf','archive','mail','system','rules'].includes(input.component) || !['normal','high','critical'].includes(input.priority))fail('异常组件或优先级不正确。');
return this.transaction(()=>{const at=new Date().toISOString();const item={id:crypto.randomUUID(),title,description,component:input.component,priority:input.priority,owner:assigned,status:assigned?'in_progress':'open',version:1,createdAt:at,updatedAt:at,history:[{at,actor:actor.username,action:'create',note:description,toOwner:assigned}]};this.db.prepare('INSERT INTO exceptions(id,value) VALUES(?,?)').run(item.id,JSON.stringify(item));this.record(actor,'建立异常',title);return item;});
}
actOnException(id,input,actor,members){
authorize(actor,['admin','operator']);object(input,['version','action','owner','note']);version(input.version);
if(!['claim','transfer','verify','resolve','reopen'].includes(input.action))fail('异常操作不正确。');
const note=input.note===undefined?'':text(input.note,'处理记录',5000);
if(['transfer','resolve','reopen'].includes(input.action) && !note)fail('请填写交接原因或人工核验依据。');
const assigned=input.action==='transfer'?owner(input.owner,members,true):undefined;
if(input.action!=='transfer' && input.owner!==undefined)fail('此操作不接受指定负责人。');
return this.transaction(()=>{
const row=this.db.prepare('SELECT value FROM exceptions WHERE id=?').get(id);if(!row)fail('没有找到此异常。',404);const item=JSON.parse(row.value);
if(item.version!==input.version)fail('异常已被其他人更新,请刷新后重试。',409);
if(input.action==='claim'){
if(item.status!=='open' || item.owner)fail('此异常已被认领或不允许认领。',409);
owner(actor.username,members,true);item.owner=actor.username;item.status='in_progress';
}else {
if(actor.role!=='admin' && item.owner!==actor.username)fail('只有负责人或管理员可以处理此异常。',403);
if(input.action==='transfer'){
if(!['open','in_progress','verifying'].includes(item.status))fail('已关闭异常需先重新打开。',409);
if(assigned===item.owner)fail('新负责人必须与当前负责人不同。');
}else if(input.action==='verify'){
if(item.status!=='in_progress')fail('只有处理中的异常可以提交验证。',409);item.status='verifying';
}else if(input.action==='resolve'){
if(item.status!=='verifying')fail('异常需要先提交验证,再记录人工核验依据关闭。',409);item.status='resolved';
}else if(input.action==='reopen'){
if(item.status!=='resolved')fail('只有已关闭异常可以重新打开。',409);item.status='open';
}
}
const at=new Date().toISOString();const history={at,actor:actor.username,action:input.action,note};
if(input.action==='transfer'){history.fromOwner=item.owner;history.toOwner=assigned;item.owner=assigned;item.status='in_progress';}
if(input.action==='reopen'){history.fromOwner=item.owner;history.toOwner='';item.owner='';}
item.updatedAt=at;item.version++;item.history.push(history);this.db.prepare('UPDATE exceptions SET value=? WHERE id=?').run(JSON.stringify(item),id);this.record(actor,({claim:'认领异常',transfer:'转交异常',verify:'提交异常验证',resolve:'人工核验关闭异常',reopen:'重新打开异常'})[input.action],item.title+(note?':'+note:''));return item;
});
}
createConnection(input,actor,members){
authorize(actor,['admin']);object(input,['name','owner']);const name=text(input.name,'连接名称',100,true),assigned=owner(input.owner,members,true);
return this.transaction(()=>{const at=new Date().toISOString();const item={id:crypto.randomUUID(),name,owner:assigned,status:'disconnected',mainUrl:'https://bpmn.skyworthdigital.com',createdAt:at,updatedAt:at};this.db.prepare('INSERT INTO connections(id,value) VALUES(?,?)').run(item.id,JSON.stringify(item));this.record(actor,'创建连接',name);return item;});
}
getConnection(id){const row=this.db.prepare('SELECT value FROM connections WHERE id=?').get(id);if(!row)fail('没有找到此连接。',404);return JSON.parse(row.value);}
resetConnectionSession(id,actor){
authorize(actor,['admin','operator']);return this.transaction(()=>{
const item=this.getConnection(id);if(actor.role!=='admin' && item.owner!==actor.username)fail('仅连接负责人或管理员可以操作此连接。',403);if(item.status==='disabled')fail('此连接已停用。',409);
item.status='disconnected';for(const key of ['identity','checks','checkedAt','lastConnectedAt','savedAt'])delete item[key];item.updatedAt=new Date().toISOString();
this.db.prepare('UPDATE connections SET value=? WHERE id=?').run(JSON.stringify(item),id);return item;
});
}
markSessionChecksPending(){
return this.transaction(()=>{let count=0;for(const row of this.db.prepare('SELECT id,value FROM connections').all()){const item=JSON.parse(row.value);if(item.status!=='connected')continue;item.status='unchecked';this.db.prepare('UPDATE connections SET value=? WHERE id=?').run(JSON.stringify(item),row.id);count++;}return count;});
}
updateConnectionSession(id,result,actor){
authorize(actor,['admin','operator']);object(result,['status','identity','checkedAt','checks']);
if(!['connected','login_required','error'].includes(result.status))fail('连接检查状态不正确。');
const identity=text(result.identity,'BPM 账号',200);
if(typeof result.checkedAt!=='string' || !/^\d{4}-\d{2}-\d{2}T/.test(result.checkedAt) || !Number.isFinite(Date.parse(result.checkedAt)))fail('连接检查时间不正确。');
object(result.checks,['portal']);const checks={};
const check=result.checks.portal;object(check,['ok','message']);if(typeof check.ok!=='boolean')fail('连接检查结果不正确。');checks.portal={ok:check.ok,message:text(check.message,'检查说明',500)};
if((result.status==='connected')!==checks.portal.ok)fail('连接检查结果不完整。');
return this.transaction(()=>{
const item=this.getConnection(id);if(actor.role!=='admin' && item.owner!==actor.username)fail('仅连接负责人或管理员可以操作此连接。',403);if(item.status==='disabled')fail('此连接已停用。',409);
const at=new Date().toISOString();Object.assign(item,{status:result.status,identity,checkedAt:result.checkedAt,checks,updatedAt:at});if(item.status==='connected')item.lastConnectedAt=result.checkedAt;
this.db.prepare('UPDATE connections SET value=? WHERE id=?').run(JSON.stringify(item),id);
if(['error','login_required'].includes(item.status) && item.lastConnectedAt){
const existing=this.db.prepare('SELECT value FROM exceptions').all().map(row=>JSON.parse(row.value)).some(entry=>entry.connectionId===id && entry.kind==='bpm_login' && entry.status!=='resolved');
if(!existing){const unavailable=item.status==='error',title=unavailable?'BPM 连接需要检查:'+item.name:item.name+' 需要登录验证',description=unavailable?'新版 BPM 暂时无法连接,请检查网络和连接状态。':'BPM 自动续登未完成,请连接负责人检查托管账号或完成登录验证。';const task={id:crypto.randomUUID(),title,description,component:'bpm',priority:'high',owner:item.owner,status:'in_progress',version:1,kind:'bpm_login',connectionId:id,createdAt:at,updatedAt:at,history:[{at,actor:actor.username,action:'create',note:unavailable?'连接检查未通过':'连接检查需要登录验证'}]};this.db.prepare('INSERT INTO exceptions(id,value) VALUES(?,?)').run(task.id,JSON.stringify(task));this.record(actor,unavailable?'创建 BPM 连接检查待办':'创建 BPM 续登待办',item.name);}
}
this.record(actor,'检查 BPM 连接',item.name+':'+item.status);return item;
});
}
disableConnection(id,actor){
authorize(actor,['admin']);return this.transaction(()=>{const item=this.getConnection(id);if(item.status==='disabled')return item;item.status='disabled';for(const key of ['identity','checks','checkedAt','lastConnectedAt','savedAt'])delete item[key];item.updatedAt=new Date().toISOString();this.db.prepare('UPDATE connections SET value=? WHERE id=?').run(JSON.stringify(item),id);this.record(actor,'停用连接',item.name);return item;});
}
deleteConnection(id,actor){
authorize(actor,['admin']);return this.transaction(()=>{const item=this.getConnection(id);if(item.status!=='disabled')fail('请先停用连接再删除。',409);this.db.prepare('DELETE FROM connections WHERE id=?').run(id);this.record(actor,'删除连接',item.name);return {id,deleted:true};});
}
saveSupervisor(input,actor,members){
authorize(actor,['admin']);object(input,['version','defaultOwner','notifyChannel','maxAttempts']);version(input.version);const defaultOwner=owner(input.defaultOwner,members);
if(!['none','manual'].includes(input.notifyChannel) || !Number.isInteger(input.maxAttempts) || input.maxAttempts<0 || input.maxAttempts>3)fail('监管草稿渠道或尝试次数不正确。');
return this.transaction(()=>{const previous=this.meta('supervisor');if(previous.version!==input.version)fail('监管草稿已被其他人更新,请刷新后重试。',409);const saved={version:previous.version+1,defaultOwner,notifyChannel:input.notifyChannel,maxAttempts:input.maxAttempts};this.setMeta('supervisor',saved);this.record(actor,'保存监管策略草稿','仅保存草稿,不执行自动处理或通知');return saved;});
}
close(){if(this.db){this.db.close();this.db=null;}}
}
module.exports={WorkspaceStore};