refactor: organize source web and tests by business module
This commit is contained in:
1 parent
9854d2d5c2
commit
2aed328774
113 files changed
+189
-183
No files matched your search
+1
-1
@@ -11,7 +11,7 @@
|
||||
"service:status": "node scripts/service.cjs status",
|
||||
"service:stop": "node scripts/service.cjs stop",
|
||||
"service:restart": "node scripts/service.cjs restart",
|
||||
"test": "node --test --test-concurrency=2 tests/*.test.cjs",
|
||||
"test": "node --test --test-concurrency=2 \"tests/**/*.test.cjs\"",
|
||||
"preview": "node scripts/preview.cjs"
|
||||
},
|
||||
"engines": {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Regression/import entry point for offline captures. Never contacts BPM.
|
||||
const fs = require('node:fs/promises');
|
||||
const path = require('node:path');
|
||||
const { renderSnapshot } = require('../src/exporter.cjs');
|
||||
const { renderSnapshot } = require('../src/modules/pdf/exporter.cjs');
|
||||
|
||||
async function main() {
|
||||
const args = process.argv.slice(2);
|
||||
|
||||
+3
-3
@@ -3,9 +3,9 @@ const crypto=require('node:crypto');
|
||||
const fs=require('node:fs');
|
||||
const os=require('node:os');
|
||||
const path=require('node:path');
|
||||
const {Store}=require('../src/dashboard-store.cjs');
|
||||
const {WorkspaceStore}=require('../src/workspace-store.cjs');
|
||||
const {createDashboard}=require('../src/dashboard.cjs');
|
||||
const {Store}=require('../src/modules/dashboard/store.cjs');
|
||||
const {WorkspaceStore}=require('../src/modules/workspace/store.cjs');
|
||||
const {createDashboard}=require('../src/app/dashboard.cjs');
|
||||
|
||||
async function startPreview({stateDir=path.join(process.env.LOCALAPPDATA || os.homedir(),'OrderNotificationAutomation','preview'),port=18776}={}) {
|
||||
fs.mkdirSync(stateDir,{recursive:true});
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs'),path=require('node:path'),{spawn}=require('node:child_process'),{ServiceSupervisor}=require('../src/service-supervisor.cjs'),{defaultStateDir,requestControl,readSupervisor,canConfirmStopped}=require('../src/service-control.cjs');
|
||||
const fs=require('node:fs'),path=require('node:path'),{spawn}=require('node:child_process'),{ServiceSupervisor}=require('../src/platform/service/supervisor.cjs'),{defaultStateDir,requestControl,readSupervisor,canConfirmStopped}=require('../src/platform/service/control.cjs');
|
||||
const root=path.resolve(__dirname,'..'),pause=ms=>new Promise(r=>setTimeout(r,ms));
|
||||
function ports(){let config={};try{config=JSON.parse(fs.readFileSync(path.join(root,'config.json'),'utf8'));}catch(e){if(e.code!=='ENOENT')throw e;}const result=[config.port||18765,config.dashboard?.port??18766];if(result.some(p=>!Number.isInteger(p)||p<1024||p>65535)||result[0]===result[1])throw Error('服务端口配置无效。');return result;}
|
||||
async function waitRunning(stateDir,previousInstance){const end=Date.now()+130000;let last;
|
||||
@@ -10,7 +10,7 @@ async function main(action=process.argv[2]||'start'){
|
||||
if(action==='run'){
|
||||
const guard=new ServiceSupervisor({stateDir,ports:ports()});await guard.start();const stop=()=>guard.stop().then(()=>process.exit(0),()=>process.exit(1));process.once('SIGINT',stop);process.once('SIGTERM',stop);return;
|
||||
}
|
||||
if(action==='install'||action==='uninstall'){const startup=require('../src/windows-startup.cjs');const result=action==='install'?startup.installAutostart({stateDir}):startup.uninstallAutostart({stateDir});console.log(result.enabled?'Windows 登录自启动已启用(当前用户,后台运行)。':'Windows 登录自启动已移除。');return;}
|
||||
if(action==='install'||action==='uninstall'){const startup=require('../src/platform/service/windows-startup.cjs');const result=action==='install'?startup.installAutostart({stateDir}):startup.uninstallAutostart({stateDir});console.log(result.enabled?'Windows 登录自启动已启用(当前用户,后台运行)。':'Windows 登录自启动已移除。');return;}
|
||||
if(action==='status'){let live;try{live=await requestControl({stateDir});}catch{}const saved=readSupervisor(stateDir);console.log(JSON.stringify({supervisorResponding:!!live,state:live?.state||saved.state,autostartEnabled:!!(saved.autostart?.enabled&&fs.existsSync(saved.autostart.linkPath)),events:saved.events},null,2));return;}
|
||||
if(action==='stop'){
|
||||
let expected;try{expected=(await requestControl({stateDir,action:'stop'})).state;}catch(e){if(['ENOENT','ECONNREFUSED'].includes(e.code)){console.log('服务守护未运行。');return;}throw e;}
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
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 {storageApi}=require('./storage-api.cjs');
|
||||
const {notificationApi}=require('./notification-api.cjs');
|
||||
const {assistantApi}=require('./assistant-api.cjs');
|
||||
const {respondToPing}=require('./service-ping.cjs');
|
||||
const {previewAsset,PREVIEW_CSP}=require('./storage-preview-assets.cjs');
|
||||
const {SessionStore,SESSION_MS}=require('./dashboard-sessions.cjs');
|
||||
const {nextSlots}=require('../shared/schedule.cjs');
|
||||
const {workspaceApi}=require('../modules/workspace/api.cjs');
|
||||
const {bpmApi}=require('../modules/bpm/api.cjs');
|
||||
const {mailApi}=require('../modules/mail/api.cjs');
|
||||
const {bpmScanApi}=require('../modules/bpm/scan-api.cjs');
|
||||
const {storageApi}=require('../modules/storage/api.cjs');
|
||||
const {notificationApi}=require('../modules/notifications/api.cjs');
|
||||
const {assistantApi}=require('../modules/assistant/api.cjs');
|
||||
const {respondToPing}=require('../platform/service/ping.cjs');
|
||||
const {previewAsset,PREVIEW_CSP}=require('../modules/storage/preview-assets.cjs');
|
||||
const {SessionStore,SESSION_MS}=require('../modules/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'});
|
||||
|
||||
@@ -17,23 +17,23 @@ function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,ma
|
||||
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 webRoot=require('../shared/paths.cjs').WEB_ROOT;
|
||||
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'},
|
||||
'/storage.js':{path:path.join(webRoot,'storage.js'),type:'text/javascript'},
|
||||
'/storage-preview.html':{path:path.join(webRoot,'storage-preview.html'),type:'text/html',preview:true},
|
||||
'/storage-preview.js':{path:path.join(webRoot,'storage-preview.js'),type:'text/javascript',preview:true},
|
||||
'/storage-preview-office.js':{path:path.join(webRoot,'storage-preview-office.js'),type:'text/javascript',preview:true},
|
||||
'/storage-preview-host.js':{path:path.join(webRoot,'storage-preview-host.js'),type:'text/javascript'},
|
||||
'/storage-preview.css':{path:path.join(webRoot,'storage-preview.css'),type:'text/css',preview:true},
|
||||
'/notifications.js':{path:path.join(webRoot,'notifications.js'),type:'text/javascript'},
|
||||
'/assistant.js':{path:path.join(webRoot,'assistant.js'),type:'text/javascript'},
|
||||
'/health.js':{path:path.join(webRoot,'health.js'),type:'text/javascript'},
|
||||
'/workspace.js':{path:path.join(webRoot,'modules/workspace/view.js'),type:'text/javascript'},
|
||||
'/bpm.js':{path:path.join(webRoot,'modules/bpm/view.js'),type:'text/javascript'},
|
||||
'/mail.js':{path:path.join(webRoot,'modules/mail/view.js'),type:'text/javascript'},
|
||||
'/orders.js':{path:path.join(webRoot,'modules/bpm/arrivals.js'),type:'text/javascript'},
|
||||
'/storage.js':{path:path.join(webRoot,'modules/storage/view.js'),type:'text/javascript'},
|
||||
'/storage-preview.html':{path:path.join(webRoot,'modules/storage/preview.html'),type:'text/html',preview:true},
|
||||
'/storage-preview.js':{path:path.join(webRoot,'modules/storage/preview.js'),type:'text/javascript',preview:true},
|
||||
'/storage-preview-office.js':{path:path.join(webRoot,'modules/storage/preview-office.js'),type:'text/javascript',preview:true},
|
||||
'/storage-preview-host.js':{path:path.join(webRoot,'modules/storage/preview-host.js'),type:'text/javascript'},
|
||||
'/storage-preview.css':{path:path.join(webRoot,'modules/storage/preview.css'),type:'text/css',preview:true},
|
||||
'/notifications.js':{path:path.join(webRoot,'modules/notifications/view.js'),type:'text/javascript'},
|
||||
'/assistant.js':{path:path.join(webRoot,'modules/assistant/view.js'),type:'text/javascript'},
|
||||
'/health.js':{path:path.join(webRoot,'modules/health/view.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'}
|
||||
@@ -1,5 +1,5 @@
|
||||
'use strict';
|
||||
const {fail}=require('./assistant-store.cjs'),{secureBpmTransport}=require('./bpm-api.cjs');
|
||||
const {fail}=require('./store.cjs'),{secureBpmTransport}=require('../bpm/api.cjs');
|
||||
function bodyKeys(body,keys){if(!body||Array.isArray(body)||Object.keys(body).some(k=>!keys.includes(k)))throw fail('助手请求包含不支持的字段。');}
|
||||
async function assistantApi({assistant,user,sessionId,route,method,body,request,reply,workspace,trustedProxy=false}){
|
||||
if(!route.startsWith('/api/assistant'))return false;if(!assistant)throw fail('ZCode 助手服务未启动。',503);const principal={user,sessionId};
|
||||
@@ -1,5 +1,5 @@
|
||||
'use strict';
|
||||
const crypto=require('node:crypto'),{fail}=require('./assistant-store.cjs');
|
||||
const crypto=require('node:crypto'),{fail}=require('./store.cjs');
|
||||
function redact(value,maxLength=2000){return String(value??'').replace(/\b(?:Bearer\s+)[^\s,;]+/gi,'Bearer [已隐藏]').replace(/((?:password|passwd|api[_-]?key|token|cookie|authorization|密码)\s*[=::]\s*)([^\s,;]+)/gi,'$1[已隐藏]').replace(/\b[A-Za-z]:[\\/][^\r\n"'<>]*/g,'[本机路径已隐藏]').replace(/\\\\[^\r\n"'<>]*/g,'[共享路径已隐藏]').slice(0,maxLength);}
|
||||
const cleanMessage=(value,key)=>String(value??'').split(key||'\u0000').join('[已隐藏]');
|
||||
function snapshot({workspace,scanner,storage,dashboard},user){
|
||||
@@ -1,5 +1,5 @@
|
||||
'use strict';
|
||||
const {fail}=require('./assistant-store.cjs'),{redact,cleanMessage,snapshot,checkAction,parseResponse}=require('./assistant-policy.cjs');
|
||||
const {fail}=require('./store.cjs'),{redact,cleanMessage,snapshot,checkAction,parseResponse}=require('./policy.cjs');
|
||||
class AssistantService{
|
||||
constructor({store,runtime,...deps}){this.store=store;this.runtime=runtime;this.deps=deps;this.running=new Map();this.actions=new Set();this.stopped=false;}
|
||||
context(user){return snapshot(this.deps,user);}
|
||||
@@ -1,5 +1,5 @@
|
||||
'use strict';
|
||||
const path=require('node:path'),crypto=require('node:crypto'),fs=require('node:fs'),{DatabaseSync}=require('node:sqlite'),{BpmVault}=require('./bpm-vault.cjs');
|
||||
const path=require('node:path'),crypto=require('node:crypto'),fs=require('node:fs'),{DatabaseSync}=require('node:sqlite'),{BpmVault}=require('../../platform/security/vault.cjs');
|
||||
const fail=(message,status=400)=>Object.assign(new Error(message),{status}),now=()=>new Date().toISOString();
|
||||
const day=()=>new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date());
|
||||
function installedRuntime(dir){try{
|
||||
@@ -1,5 +1,5 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs/promises'),path=require('node:path'),crypto=require('node:crypto'),{spawn,execFile}=require('node:child_process'),{BpmVault}=require('./bpm-vault.cjs'),{fail}=require('./assistant-store.cjs');
|
||||
const fs=require('node:fs/promises'),path=require('node:path'),crypto=require('node:crypto'),{spawn,execFile}=require('node:child_process'),{BpmVault}=require('../../platform/security/vault.cjs'),{fail}=require('./store.cjs');
|
||||
// Exact names from zai-org/ZCode v3.14.3 core/tool/handlers/index.ts.
|
||||
// This version's CLI uses exact names, so '*' would NOT disable all tools.
|
||||
const DISALLOWED=Object.freeze(['Read','Write','Edit','Bash','Glob','Grep','WebFetch','WebSearch','TodoRead','TodoWrite','CronCreate','CronList','CronUpdate','CronDelete','OffPeakCreate','OffPeakList','EnterPlanMode','ExitPlanMode','AskUserQuestion','SendMessage','RespondToCoordinator','submit_result','escalate','TaskOutput','TaskStop','ReadSessionContext','Agent','Task','Skill','js','Workflow','CreateWorkflow','AmendWorkflow','SaveWorkflow','EvalWorkflowSnippet','ListWorkflowRuns','GetWorkflowRun','ResumeWorkflowRun','ResolveWorkflowQuestion','ListSavedWorkflows','ListModels']);
|
||||
File renamed without changes.
File renamed without changes.
@@ -1,6 +1,6 @@
|
||||
'use strict';
|
||||
const sanitize=require('sanitize-html');
|
||||
const {loadPlaywright}=require('./runtime.cjs');
|
||||
const {loadPlaywright}=require('../../platform/browser.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){
|
||||
File renamed without changes.
File renamed without changes.
@@ -1,5 +1,5 @@
|
||||
'use strict';
|
||||
const crypto=require('node:crypto');const {dayPolicy}=require('./schedule.cjs');
|
||||
const crypto=require('node:crypto');const {dayPolicy}=require('../../shared/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()};}
|
||||
@@ -1,9 +1,9 @@
|
||||
'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 { BpmVault } = require('../../platform/security/vault.cjs');
|
||||
const { loadPlaywright, browserOptions } = require('../../platform/browser.cjs');
|
||||
const { BpmListClient } = require('./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' }
|
||||
File renamed without changes.
File renamed without changes.
@@ -1,5 +1,5 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs'),path=require('node:path'),{DatabaseSync}=require('node:sqlite'),{readSupervisor}=require('./service-control.cjs'),{redact}=require('./assistant-policy.cjs');
|
||||
const fs=require('node:fs'),path=require('node:path'),{DatabaseSync}=require('node:sqlite'),{readSupervisor}=require('../../platform/service/control.cjs'),{redact}=require('../assistant/policy.cjs');
|
||||
function timestamp(value){if(typeof value!=='string')return null;const normalized=/^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d$/.test(value)?value.replace(' ','T')+'Z':value;const n=Date.parse(normalized);return Number.isFinite(n)?new Date(n).toISOString():null;}
|
||||
const latest=(...values)=>values.map(timestamp).filter(Boolean).sort().at(-1)||null;
|
||||
const groupStatus=items=>!items.length?'unconfigured':['error','unknown','running','pending','healthy','paused','disabled'].find(s=>items.some(i=>i.status===s))||'pending';
|
||||
@@ -1,5 +1,5 @@
|
||||
'use strict';
|
||||
const {secureBpmTransport}=require('./bpm-api.cjs');const {escape}=require('./mail-parser.cjs');
|
||||
const {secureBpmTransport}=require('../bpm/api.cjs');const {escape}=require('./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;
|
||||
File renamed without changes.
@@ -1,5 +1,5 @@
|
||||
'use strict';
|
||||
const {ImapFlow}=require('imapflow');const nodemailer=require('nodemailer');const {parseTemplate,renderTemplate,MAX_MAIL}=require('./mail-parser.cjs');
|
||||
const {ImapFlow}=require('imapflow');const nodemailer=require('nodemailer');const {parseTemplate,renderTemplate,MAX_MAIL}=require('./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{
|
||||
@@ -1,5 +1,5 @@
|
||||
'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 path=require('node:path');const crypto=require('node:crypto');const {DatabaseSync}=require('node:sqlite');const {BpmVault}=require('../../platform/security/vault.cjs');const {validateVariables}=require('./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();};
|
||||
File renamed without changes.
@@ -1,5 +1,5 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs');const path=require('node:path');const crypto=require('node:crypto');const {DatabaseSync}=require('node:sqlite');const {BpmVault}=require('./bpm-vault.cjs');const {nextSlots}=require('./schedule.cjs');
|
||||
const fs=require('node:fs');const path=require('node:path');const crypto=require('node:crypto');const {DatabaseSync}=require('node:sqlite');const {BpmVault}=require('../../platform/security/vault.cjs');const {nextSlots}=require('../../shared/schedule.cjs');
|
||||
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
|
||||
const hash=value=>crypto.createHash('sha256').update(value).digest('hex');
|
||||
const DEFAULT_MAP={id:'id',version:'version',industry:'industry',brief:'brief',subject:'subject',occurredAt:'occurredAt'};
|
||||
@@ -1,6 +1,6 @@
|
||||
const fs = require('node:fs/promises');
|
||||
const path = require('node:path');
|
||||
const { loadPlaywright, browserOptions } = require('./runtime.cjs');
|
||||
const { loadPlaywright, browserOptions } = require('../../platform/browser.cjs');
|
||||
const fields = { order: '订单号', project: '项目编号', model: '产品型号', serial: '通知书编号' };
|
||||
|
||||
function buildFilename(metadata = {}) {
|
||||
@@ -39,7 +39,7 @@ async function reserveFile(outputDir, filename) {
|
||||
async function renderSnapshot(snapshot, options = {}) {
|
||||
validateSnapshot(snapshot);
|
||||
const filename = buildFilename(snapshot.metadata);
|
||||
const outputDir = path.resolve(options.outputDir || path.join(__dirname, '../output/pdf'));
|
||||
const outputDir = path.resolve(options.outputDir || path.join(require('../../shared/paths.cjs').PROJECT_ROOT, '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());
|
||||
@@ -1,5 +1,5 @@
|
||||
'use strict';
|
||||
const {secureBpmTransport}=require('./bpm-api.cjs');
|
||||
const {secureBpmTransport}=require('../bpm/api.cjs');
|
||||
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
|
||||
function payload(body,keys){if(!body||Object.keys(body).some(k=>!keys.includes(k)))fail('存储操作参数无效。');}
|
||||
async function storageApi({storage,workspace,user,url,route,method,body,request,response,reply,trustedProxy}){
|
||||
@@ -3,7 +3,7 @@ const fs=require('node:fs/promises');
|
||||
const path=require('node:path');
|
||||
const crypto=require('node:crypto');
|
||||
const native=require('./smb-native.cjs');
|
||||
const {describePreview,validatePreview}=require('./storage-preview.cjs');
|
||||
const {describePreview,validatePreview}=require('./preview.cjs');
|
||||
const MAX_FILE=64*1024*1024;
|
||||
const fail=(message,status=400)=>Object.assign(new Error(message),{status});
|
||||
function segments(relative=''){
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -1,7 +1,7 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs/promises');const path=require('node:path');
|
||||
const {SmbClient,segments,inside}=require('./storage-files.cjs');
|
||||
const {orderFolder}=require('./storage-order.cjs');
|
||||
const {SmbClient,segments,inside}=require('./files.cjs');
|
||||
const {orderFolder}=require('./order.cjs');
|
||||
const fail=(message,status=400)=>Object.assign(new Error(message),{status});
|
||||
const safe=e=>e.status?e:fail(({ENOENT:'找不到文件或归档目录,请检查路径。',EACCES:'没有共享目录访问权限。',EPERM:'没有共享目录操作权限。',ENOSPC:'存储服务器空间不足。',ENOTDIR:'指定路径不是目录。'})[e.code]||'存储操作未完成,请检查服务器与网络。',502);
|
||||
class StorageService{
|
||||
@@ -6,7 +6,7 @@ const path=require('node:path');
|
||||
const messages={5:'存储服务器拒绝访问,请检查账号权限。',53:'找不到存储服务器,请检查地址与网络。',67:'找不到共享目录,请检查共享名称。',86:'SMB 账号或密码不正确。',1326:'SMB 账号或密码不正确。',1219:'此服务器已使用其他账号连接,请先由管理员处理 Windows SMB 凭据冲突。',183:'目标文件已存在。',80:'目标文件已存在。'};
|
||||
function native(operation,input){
|
||||
return new Promise((resolve,reject)=>{
|
||||
const child=execFile('powershell.exe',['-NoLogo','-NoProfile','-NonInteractive','-ExecutionPolicy','Bypass','-File',path.resolve(__dirname,'../scripts/smb-native.ps1')],{windowsHide:true,timeout:25000,maxBuffer:operation==='shares'?384*1024:16384,encoding:'utf8'},(error,stdout)=>{
|
||||
const child=execFile('powershell.exe',['-NoLogo','-NoProfile','-NonInteractive','-ExecutionPolicy','Bypass','-File',path.join(require('../../shared/paths.cjs').SCRIPTS_ROOT,'smb-native.ps1')],{windowsHide:true,timeout:25000,maxBuffer:operation==='shares'?384*1024:16384,encoding:'utf8'},(error,stdout)=>{
|
||||
let result;try{result=JSON.parse(stdout.replace(/^\uFEFF/,''));}catch{}
|
||||
if(result?.ok)return resolve(result);
|
||||
const code=result?.code;const failure=Object.assign(new Error(messages[code]||'SMB 操作未完成,请检查网络、共享权限或服务器状态。'),{status:502});
|
||||
@@ -1,5 +1,5 @@
|
||||
'use strict';
|
||||
const {SmbClient,segments}=require('./storage-files.cjs');
|
||||
const {SmbClient,segments}=require('./files.cjs');
|
||||
const native=require('./smb-native.cjs');
|
||||
let input='';process.stdin.setEncoding('utf8');process.stdin.on('data',chunk=>{input+=chunk;if(input.length>32768)process.exit(1);});
|
||||
process.stdin.on('end',async()=>{
|
||||
File renamed without changes.
@@ -3,8 +3,8 @@ const fs=require('node:fs');
|
||||
const path=require('node:path');
|
||||
const crypto=require('node:crypto');
|
||||
const {DatabaseSync}=require('node:sqlite');
|
||||
const {BpmVault}=require('./bpm-vault.cjs');
|
||||
const {segments}=require('./storage-files.cjs');
|
||||
const {BpmVault}=require('../../platform/security/vault.cjs');
|
||||
const {segments}=require('./files.cjs');
|
||||
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
|
||||
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 now=()=>new Date().toISOString();
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -1,5 +1,5 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs'),path=require('node:path'),crypto=require('node:crypto'),{DatabaseSync}=require('node:sqlite'),{BpmVault}=require('./bpm-vault.cjs');
|
||||
const fs=require('node:fs'),path=require('node:path'),crypto=require('node:crypto'),{DatabaseSync}=require('node:sqlite'),{BpmVault}=require('../security/vault.cjs');
|
||||
class SupervisorStore {
|
||||
constructor(stateDir){
|
||||
this.dir=path.join(path.resolve(stateDir),'supervisor');new BpmVault({stateDir:this.dir}).destroy();
|
||||
@@ -1,11 +1,11 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs'),path=require('node:path'),net=require('node:net'),crypto=require('node:crypto'),{spawn,execFile}=require('node:child_process'),{promisify}=require('node:util');
|
||||
const {SupervisorStore}=require('./supervisor-store.cjs'),{controlAddress}=require('./service-control.cjs'),{checkPing,sameToken}=require('./service-ping.cjs');
|
||||
const {SupervisorStore}=require('./store.cjs'),{controlAddress}=require('./control.cjs'),{checkPing,sameToken}=require('./ping.cjs');
|
||||
const execFileAsync=promisify(execFile),DEFAULTS={intervalMs:10000,pingTimeoutMs:5000,startupGraceMs:120000,failureThreshold:4,stopGraceMs:15000,backoffMs:[2000,5000,10000,30000,60000],windowMs:900000,maxRestarts:8,cooldownMs:300000};
|
||||
function restartPlan({failures=0,recent=0,...options}={}){const t={...DEFAULTS,...options},cooldown=recent>=t.maxRestarts;return {cooldown,delayMs:cooldown?t.cooldownMs:t.backoffMs[Math.min(failures,t.backoffMs.length-1)]};}
|
||||
async function portsAvailable(ports){for(const port of ports){const server=net.createServer();await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(port,'127.0.0.1',resolve);});await new Promise(r=>server.close(r));}}
|
||||
class ServiceSupervisor {
|
||||
constructor({stateDir,entry=path.resolve(__dirname,'server.cjs'),ports=[18765,18766],env={},timing={}}){Object.assign(this,{stateDir:path.resolve(stateDir),entry:path.resolve(entry),ports,env});this.timing={...DEFAULTS,...timing};this.state={};this.restarts=[];this.failures=0;this.stopping=false;this.started=false;}
|
||||
constructor({stateDir,entry=path.join(require('../../shared/paths.cjs').PROJECT_ROOT,'src/server.cjs'),ports=[18765,18766],env={},timing={}}){Object.assign(this,{stateDir:path.resolve(stateDir),entry:path.resolve(entry),ports,env});this.timing={...DEFAULTS,...timing};this.state={};this.restarts=[];this.failures=0;this.stopping=false;this.started=false;}
|
||||
snapshot(){return {...this.state};}
|
||||
update(patch){Object.assign(this.state,patch,{updatedAt:new Date().toISOString()});this.store.set('state',this.state);}
|
||||
async start(){
|
||||
@@ -37,7 +37,7 @@ class ServiceSupervisor {
|
||||
async launch(){
|
||||
if(this.stopping)return;this.misses=0;this.spawnedAt=Date.now();const instanceId=crypto.randomUUID(),heartbeatToken=crypto.randomBytes(32).toString('hex'),logFile=path.join(this.store.dir,'service.log');this.rotateLog();
|
||||
const fd=fs.openSync(logFile,'a',0o600);let child;
|
||||
try{child=spawn(process.execPath,[this.entry],{cwd:path.resolve(__dirname,'..'),env:{...process.env,...this.env,ORDER_SUPERVISOR_TOKEN:heartbeatToken,ORDER_SUPERVISOR_INSTANCE:instanceId},windowsHide:true,shell:false,stdio:['ignore',fd,fd,'ipc']});}finally{fs.closeSync(fd);}
|
||||
try{child=spawn(process.execPath,[this.entry],{cwd:require('../../shared/paths.cjs').PROJECT_ROOT,env:{...process.env,...this.env,ORDER_SUPERVISOR_TOKEN:heartbeatToken,ORDER_SUPERVISOR_INSTANCE:instanceId},windowsHide:true,shell:false,stdio:['ignore',fd,fd,'ipc']});}finally{fs.closeSync(fd);}
|
||||
this.child=child;this.instanceId=instanceId;this.heartbeatToken=heartbeatToken;this.childClosed=new Promise(resolve=>{this.resolveClosed=resolve;});
|
||||
this.update({status:'starting',childPid:child.pid||null,childInstanceId:instanceId,childStartedAt:new Date().toISOString(),heartbeatAt:null,nextRestartAt:null});
|
||||
child.on('error',()=>{this.store?.event('spawn_failed');});
|
||||
@@ -1,5 +1,5 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs'),path=require('node:path'),{execFileSync}=require('node:child_process'),{SupervisorStore}=require('./supervisor-store.cjs');
|
||||
const fs=require('node:fs'),path=require('node:path'),{execFileSync}=require('node:child_process'),{SupervisorStore}=require('./store.cjs');
|
||||
function powershell(script,data){return execFileSync('powershell.exe',['-NoLogo','-NoProfile','-NonInteractive','-Command','$ErrorActionPreference="Stop"; [Console]::InputEncoding=New-Object System.Text.UTF8Encoding; [Console]::OutputEncoding=New-Object System.Text.UTF8Encoding; '+script],{input:JSON.stringify(data),encoding:'utf8',windowsHide:true,timeout:15000,stdio:['pipe','pipe','pipe']}).trim();}
|
||||
function locations({stateDir,startupDir}){
|
||||
if(process.platform!=='win32')throw Error('登录自启动仅支持 Windows。');
|
||||
@@ -10,7 +10,7 @@ function readShortcut(file){const raw=powershell('$d=[Console]::In.ReadToEnd()|C
|
||||
function ownedShortcut(paths){if(!fs.existsSync(paths.linkPath))return true;const old=readShortcut(paths.linkPath);return path.resolve(old.target).toLowerCase()===path.resolve(paths.wscript).toLowerCase()&&old.args==='//B "'+paths.launcherPath+'"';}
|
||||
function removeFile(file){try{fs.unlinkSync(file);}catch(e){if(e.code!=='ENOENT')throw e;}if(fs.existsSync(file))throw Error('无法确认自启动文件已移除。');}
|
||||
function writeShortcut({paths,projectRoot}){powershell('$d=[Console]::In.ReadToEnd()|ConvertFrom-Json; $s=(New-Object -ComObject WScript.Shell).CreateShortcut($d.link); $s.TargetPath=$d.target; $s.Arguments=$d.args; $s.WorkingDirectory=$d.cwd; $s.Description="Order workspace service supervisor"; $s.Save()',{link:paths.linkPath,target:paths.wscript,args:'//B "'+paths.launcherPath+'"',cwd:path.resolve(projectRoot)});}
|
||||
function installAutostart({stateDir,projectRoot=path.resolve(__dirname,'..'),nodePath=process.execPath,startupDir,shortcutWriter=writeShortcut}={}){
|
||||
function installAutostart({stateDir,projectRoot=require('../../shared/paths.cjs').PROJECT_ROOT,nodePath=process.execPath,startupDir,shortcutWriter=writeShortcut}={}){
|
||||
const paths=locations({stateDir,startupDir}),store=new SupervisorStore(stateDir);
|
||||
try{
|
||||
if(!ownedShortcut(paths))throw Error('同名启动快捷方式属于其他程序,未覆盖。');
|
||||
+18
-18
@@ -3,24 +3,24 @@ 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');
|
||||
const { AssistantStore } = require('./assistant-store.cjs');
|
||||
const { AssistantService } = require('./assistant-service.cjs');
|
||||
const { ZcodeRuntime } = require('./zcode-runtime.cjs');
|
||||
const { RuntimeHealth } = require('./runtime-health.cjs');
|
||||
const { respondToPing } = require('./service-ping.cjs');
|
||||
const { StorageStore } = require('./storage-store.cjs');
|
||||
const { StorageService } = require('./storage-service.cjs');
|
||||
const { NotificationStore, NotificationService } = require('./notifications.cjs');
|
||||
const { renderSnapshot, validateSnapshot } = require('./modules/pdf/exporter.cjs');
|
||||
const { Store } = require('./modules/dashboard/store.cjs');
|
||||
const { createDashboard } = require('./app/dashboard.cjs');
|
||||
const { WorkspaceStore } = require('./modules/workspace/store.cjs');
|
||||
const { BpmSessionManager } = require('./modules/bpm/session-manager.cjs');
|
||||
const { BpmCustodian } = require('./modules/bpm/custodian.cjs');
|
||||
const { MailStore } = require('./modules/mail/store.cjs');
|
||||
const { MailService } = require('./modules/mail/service.cjs');
|
||||
const { BpmScanStore } = require('./modules/bpm/scan-store.cjs');
|
||||
const { BpmScanner } = require('./modules/bpm/scanner.cjs');
|
||||
const { AssistantStore } = require('./modules/assistant/store.cjs');
|
||||
const { AssistantService } = require('./modules/assistant/service.cjs');
|
||||
const { ZcodeRuntime } = require('./modules/assistant/zcode-runtime.cjs');
|
||||
const { RuntimeHealth } = require('./modules/health/runtime-health.cjs');
|
||||
const { respondToPing } = require('./platform/service/ping.cjs');
|
||||
const { StorageStore } = require('./modules/storage/store.cjs');
|
||||
const { StorageService } = require('./modules/storage/service.cjs');
|
||||
const { NotificationStore, NotificationService } = require('./modules/notifications/notifications.cjs');
|
||||
|
||||
function createServer(options) {
|
||||
let busy = false;
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
const path=require('node:path');
|
||||
const PROJECT_ROOT=path.resolve(__dirname,'../..');
|
||||
const WEB_ROOT=path.join(PROJECT_ROOT,'web');
|
||||
const SCRIPTS_ROOT=path.join(PROJECT_ROOT,'scripts');
|
||||
const EXTENSION_ROOT=path.join(PROJECT_ROOT,'extension');
|
||||
module.exports={PROJECT_ROOT,WEB_ROOT,SCRIPTS_ROOT,EXTENSION_ROOT};
|
||||
File renamed without changes.
@@ -4,7 +4,7 @@ const fs = require('node:fs/promises');
|
||||
const vm = require('node:vm');
|
||||
|
||||
test('asset collection keeps source CSS order even when network completion order differs', async () => {
|
||||
const worker = await fs.readFile(require.resolve('../extension/worker.js'),'utf8');
|
||||
const worker = await fs.readFile(require.resolve('../../extension/worker.js'),'utf8');
|
||||
const responses = {
|
||||
'https://bpm.skyworthdigital.com/first.css': {delay:30,text:'body{color:red}'},
|
||||
'https://bpm.skyworthdigital.com/second.css': {delay:0,text:'body{color:blue}'}
|
||||
@@ -1,8 +1,8 @@
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
|
||||
let createDashboard;try{({createDashboard}=require('../src/dashboard.cjs'));}catch(e){if(e.code!=='MODULE_NOT_FOUND')throw e;}
|
||||
let createDashboard;try{({createDashboard}=require('../../src/app/dashboard.cjs'));}catch(e){if(e.code!=='MODULE_NOT_FOUND')throw e;}
|
||||
test('dashboard requires login, persists settings and enforces viewer and same-origin restrictions',async t=>{
|
||||
assert.equal(typeof createDashboard,'function','web dashboard server not implemented');
|
||||
const {Store}=require('../src/dashboard-store.cjs');
|
||||
const {Store}=require('../../src/modules/dashboard/store.cjs');
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'dashboard-http-'));const store=new Store(path.join(dir,'data'));
|
||||
const outputDir=path.join(dir,'pdf');fs.mkdirSync(outputDir);fs.writeFileSync(path.join(outputDir,'ok.pdf'),'%PDF-test');fs.writeFileSync(path.join(dir,'secret.pdf'),'%PDF-private');
|
||||
const server=createDashboard({store,outputDir});await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
|
||||
@@ -6,7 +6,7 @@ test('late overview response cannot overwrite a newly opened settings form',asyn
|
||||
let resolve;
|
||||
const container={innerHTML:'unsaved template draft'};
|
||||
const context=vm.createContext({document:{querySelector:()=>({})},Intl,setTimeout,window:{addEventListener(){}},fetch(){throw Error('unexpected fetch');}});
|
||||
const source=fs.readFileSync(require.resolve('../web/app.js'),'utf8').replace(/boot\(\)\.catch[\s\S]*$/,'');
|
||||
const source=fs.readFileSync(require.resolve('../../web/app.js'),'utf8').replace(/boot\(\)\.catch[\s\S]*$/,'');
|
||||
vm.runInContext(source,context);
|
||||
context.pending=new Promise(r=>{resolve=r;});context.container=container;
|
||||
vm.runInContext("api=()=>pending;currentUser={role:'admin'};",context);
|
||||
@@ -1,7 +1,7 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
|
||||
async function fixture(t){
|
||||
const {Store}=require('../src/dashboard-store.cjs'),{RuntimeHealth}=require('../src/runtime-health.cjs'),{createDashboard}=require('../src/dashboard.cjs');
|
||||
const {Store}=require('../../src/modules/dashboard/store.cjs'),{RuntimeHealth}=require('../../src/modules/health/runtime-health.cjs'),{createDashboard}=require('../../src/app/dashboard.cjs');
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'health-http-')),store=new Store(path.join(dir,'dashboard'));store.bootstrap('admin','Health-test-password-123');
|
||||
const health=new RuntimeHealth({stateDir:dir,workspace:{snapshot:()=>({connections:[{id:'c',owner:'admin',name:'<img src=x onerror=alert(1)>',status:'connected',checkedAt:new Date().toISOString(),lastConnectedAt:new Date().toISOString()}]})}}),watchdog={token:'a'.repeat(64),instanceId:'health-fixture',startedAt:new Date().toISOString()};
|
||||
const server=createDashboard({store,health,watchdog,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(async()=>{server.closeAllConnections();await new Promise(r=>server.close(r));health.close();await fs.rm(dir,{recursive:true,force:true});});
|
||||
@@ -14,7 +14,7 @@ test('health API is authenticated and watchdog requires a secret token and exact
|
||||
const response=await fetch(base+'/api/health',{headers:{Cookie:cookie}});assert.equal(response.status,200);assert.doesNotMatch(await response.text(),/a{64}|password|health-fixture/);
|
||||
});
|
||||
test('health page shows historical checks, escapes labels, and recovers from an offline refresh',{timeout:60000},async t=>{
|
||||
const {base}=await fixture(t),{loadPlaywright,browserOptions}=require('../src/runtime.cjs'),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage({viewport:{width:1280,height:900}}),errors=[];page.on('pageerror',e=>errors.push(e.message));
|
||||
const {base}=await fixture(t),{loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage({viewport:{width:1280,height:900}}),errors=[];page.on('pageerror',e=>errors.push(e.message));
|
||||
await page.goto(base+'/#health');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Health-test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();
|
||||
await page.getByRole('heading',{name:'系统健康',exact:true}).waitFor();await page.getByText('上次检查结果,非实时连通性检测',{exact:true}).waitFor();assert.equal(await page.locator('#health-groups img').count(),0);
|
||||
await page.route('**/api/health',route=>route.abort());await page.getByRole('button',{name:'刷新健康状态',exact:true}).click();await page.getByText('暂时无法连接服务,保留上次状态;恢复后会自动更新。',{exact:true}).waitFor();
|
||||
@@ -4,7 +4,7 @@ const fs=require('node:fs');
|
||||
const os=require('node:os');
|
||||
const path=require('node:path');
|
||||
let startPreview;
|
||||
try { ({startPreview}=require('../scripts/preview.cjs')); } catch(error) { if(error.code!=='MODULE_NOT_FOUND')throw error; }
|
||||
try { ({startPreview}=require('../../scripts/preview.cjs')); } catch(error) { if(error.code!=='MODULE_NOT_FOUND')throw error; }
|
||||
|
||||
test('isolated preview signs in locally with fictional workspace data and survives restart',async t=>{
|
||||
assert.equal(typeof startPreview,'function','isolated preview runtime not implemented');
|
||||
@@ -1,7 +1,7 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
|
||||
test('health keeps success/failure history across restart, filters BPM ownership, and never checks external systems',async t=>{
|
||||
const {RuntimeHealth}=require('../src/runtime-health.cjs'),stateDir=await fs.mkdtemp(path.join(os.tmpdir(),'order-health-'));let health;
|
||||
const {RuntimeHealth}=require('../../src/modules/health/runtime-health.cjs'),stateDir=await fs.mkdtemp(path.join(os.tmpdir(),'order-health-'));let health;
|
||||
t.after(async()=>{health?.close();await fs.rm(stateDir,{recursive:true,force:true});});
|
||||
const connections=[{id:'mine',name:'我的连接',owner:'worker',status:'connected',checkedAt:'2026-10-18T01:00:00Z',lastConnectedAt:'2026-10-18T01:00:00Z',password:'PRIVATE'},{id:'other',name:'PRIVATE_OTHER',owner:'other',status:'connected'}];
|
||||
const deps={stateDir,workspace:{snapshot:()=>({connections})},scanner:{store:{status:()=>({config:{enabled:false},runs:[{connectionId:'mine',status:'error',finishedAt:'2026-10-18T02:00:00Z'}]})},scan:()=>assert.fail('must not scan')},storage:{store:{servers:()=>[{id:'s',name:'共享',enabled:true,state:{checkedAt:'2026-10-18T01:00:00Z',readable:true,writable:true,message:'password=PRIVATE C:/PRIVATE/file'}}]},check:()=>assert.fail('must not write/check')},mail:{store:{channels:()=>[]},verify:()=>assert.fail('must not verify/send')}};
|
||||
@@ -11,6 +11,6 @@ test('health keeps success/failure history across restart, filters BPM ownership
|
||||
assert.equal(health.snapshot({username:'admin',role:'admin'}).groups.find(g=>g.key==='bpm').items.length,2);
|
||||
});
|
||||
test('a damaged module is reported unknown without hiding other modules or claiming real-time connectivity',async t=>{
|
||||
const {RuntimeHealth}=require('../src/runtime-health.cjs'),stateDir=await fs.mkdtemp(path.join(os.tmpdir(),'order-health-errors-'));const health=new RuntimeHealth({stateDir,workspace:{snapshot:()=>({connections:[]})},storage:{store:{servers:()=>{throw Error('PRIVATE failure');}}},mail:{store:{channels:()=>[{id:'m',name:'邮箱',enabled:false,state:{checkedAt:null,smtp:false,imap:false}}]}}});t.after(async()=>{health.close();await fs.rm(stateDir,{recursive:true,force:true});});
|
||||
const {RuntimeHealth}=require('../../src/modules/health/runtime-health.cjs'),stateDir=await fs.mkdtemp(path.join(os.tmpdir(),'order-health-errors-'));const health=new RuntimeHealth({stateDir,workspace:{snapshot:()=>({connections:[]})},storage:{store:{servers:()=>{throw Error('PRIVATE failure');}}},mail:{store:{channels:()=>[{id:'m',name:'邮箱',enabled:false,state:{checkedAt:null,smtp:false,imap:false}}]}}});t.after(async()=>{health.close();await fs.rm(stateDir,{recursive:true,force:true});});
|
||||
const data=health.snapshot({role:'admin'});assert.equal(data.groups.find(g=>g.key==='storage').status,'unknown');assert.equal(data.groups.find(g=>g.key==='mail').items[0].status,'pending');assert.equal(data.runtime.managed,false);assert.doesNotMatch(JSON.stringify(data),/PRIVATE/);
|
||||
});
|
||||
@@ -4,10 +4,10 @@ const fs = require('node:fs/promises');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const net = require('node:net');
|
||||
const serverModule = (() => { try { return require('../src/server.cjs'); } catch(e) { if(e.code === 'MODULE_NOT_FOUND') return {}; throw e; } })();
|
||||
const serverModule = (() => { try { return require('../../src/server.cjs'); } catch(e) { if(e.code === 'MODULE_NOT_FOUND') return {}; throw e; } })();
|
||||
const origin = 'chrome-extension://' + 'a'.repeat(32);
|
||||
test('BPM field evidence must match the current order binding and captured value',()=>{
|
||||
const {validateSnapshot}=require('../src/exporter.cjs');
|
||||
const {validateSnapshot}=require('../../src/modules/pdf/exporter.cjs');
|
||||
const snapshot={html:'<form>订单</form>',metadata:{order:'001234',project:'project',model:'model',serial:'notice'}};
|
||||
assert.doesNotThrow(()=>validateSnapshot(snapshot));
|
||||
for(const field of ['OFR_LSCP_Applicant.OrderNum','OFR_BS_Applicant.OrderNum','OFR_KD_Applicant.OrderNum','OFR_WY_Applicant.OrderNum'])assert.doesNotThrow(()=>validateSnapshot({...snapshot,bpmOrder:{field,value:'001234'}}));
|
||||
@@ -33,7 +33,7 @@ test('loopback API rejects web origins, unpaired callers and oversized bodies',
|
||||
|
||||
test('paired HTTP export returns a readable PDF saved to the configured directory', async () => {
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-http-test-'));
|
||||
const {Store}=require('../src/dashboard-store.cjs');
|
||||
const {Store}=require('../../src/modules/dashboard/store.cjs');
|
||||
const store=new Store(path.join(dir,'state'));
|
||||
const bpmOrder={field:'OFR_WY_Applicant.OrderNum',value:'900001'};
|
||||
const server=serverModule.createServer({token:'test-pairing-key',outputDir:dir,store});
|
||||
@@ -70,7 +70,7 @@ test('extension setup failure leaves no listening service behind', async () => {
|
||||
try {
|
||||
const invalid=path.join(dir,'extension');
|
||||
await fs.writeFile(invalid,'not a directory');
|
||||
await assert.rejects(serverModule.startService({port,token:'test-key',outputDir:dir,extensionSourceDir:path.resolve(__dirname,'../extension'),installedExtension:invalid}));
|
||||
await assert.rejects(serverModule.startService({port,token:'test-key',outputDir:dir,extensionSourceDir:path.resolve(__dirname,'../../extension'),installedExtension:invalid}));
|
||||
const free=net.createServer();
|
||||
await new Promise((resolve,reject)=>{free.once('error',reject);free.listen(port,'127.0.0.1',resolve);});
|
||||
await new Promise(resolve=>free.close(resolve));
|
||||
@@ -10,7 +10,7 @@ async function workerContext(saved) {
|
||||
chrome:{runtime:{onMessage:{addListener:()=>{}}},storage:{session:{get:async()=>storage,set:async value=>Object.assign(storage,value)}}},
|
||||
fetch:async()=>({ok:true,json:async()=>({status:'success',filename:'saved.pdf',path:'output/saved.pdf',bytes:1000})})
|
||||
});
|
||||
vm.runInContext(await fs.readFile(require.resolve('../extension/worker.js'),'utf8'),context);
|
||||
vm.runInContext(await fs.readFile(require.resolve('../../extension/worker.js'),'utf8'),context);
|
||||
return context;
|
||||
}
|
||||
test('reopening popup after worker restart recovers a completed local job',async()=>{
|
||||
@@ -1,6 +1,6 @@
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
|
||||
async function fixture(t){
|
||||
const {Store}=require('../src/dashboard-store.cjs'),{AssistantStore}=require('../src/assistant-store.cjs'),{AssistantService}=require('../src/assistant-service.cjs'),{createDashboard}=require('../src/dashboard.cjs');
|
||||
const {Store}=require('../../src/modules/dashboard/store.cjs'),{AssistantStore}=require('../../src/modules/assistant/store.cjs'),{AssistantService}=require('../../src/modules/assistant/service.cjs'),{createDashboard}=require('../../src/app/dashboard.cjs');
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'assistant-http-')),users=new Store(path.join(dir,'users'));users.bootstrap('admin','Test-password-123');users.addUser({username:'viewer',role:'viewer',password:'Test-password-123'},'admin');const store=new AssistantStore(path.join(dir,'assistant'));let checks=0;
|
||||
const storage={store:{servers:()=>[{id:'server',name:'测试存储',enabled:true,state:{readable:true,writable:true,message:'正常'}}],archives:()=>[]},check:async()=>{checks++;return {state:{readable:true,writable:true}};}};
|
||||
const runtime={probe:async()=>({available:true,version:'3.14.3',message:'运行包已就绪'}),chat:async({text,signal,config})=>{if(text.includes('挂起'))return new Promise((resolve,reject)=>signal.addEventListener('abort',()=>reject(signal.reason),{once:true}));return JSON.stringify({reply:'已读取运行状态。<img src=x onerror=alert(1)>',actions:config.allowActions?[{kind:'check_storage',targetId:'server'}]:[]});}};
|
||||
@@ -20,7 +20,7 @@ test('assistant HTTP enforces authentication, ownership, body validation and rol
|
||||
});
|
||||
test('chat UI persists conversations, shows escaped messages and explicit fixed action results, and cancels a running reply',{timeout:120000},async t=>{
|
||||
const {base,store,checks}=await fixture(t);store.saveSettings({...store.settings(),enabled:true,runtimePath:process.execPath,apiBase:'https://models.example/v1',model:'fixture',apiKey:'PRIVATE_UI_KEY',allowActions:true});
|
||||
const {loadPlaywright,browserOptions}=require('../src/runtime.cjs'),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage({viewport:{width:1440,height:1000}}),errors=[];page.on('pageerror',e=>errors.push(e.message));page.setDefaultTimeout(15000);
|
||||
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage({viewport:{width:1440,height:1000}}),errors=[];page.on('pageerror',e=>errors.push(e.message));page.setDefaultTimeout(15000);
|
||||
await page.goto(base+'/#assistant');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'新建对话',exact:true}).click();
|
||||
await page.getByLabel('发送给 ZCode',{exact:true}).fill('分析订单运行状态');await page.getByRole('button',{name:'发送',exact:true}).click();await page.locator('.assistant-reply').getByText('已读取运行状态。<img src=x onerror=alert(1)>',{exact:true}).waitFor();assert.equal(await page.locator('.assistant-reply img').count(),0);assert.equal(checks(),0);
|
||||
await page.getByRole('button',{name:'执行:检查存储连接',exact:true}).click();await page.getByText('操作已完成',{exact:true}).waitFor();assert.equal(checks(),1);await page.reload();await page.locator('.assistant-reply').getByText('已读取运行状态。<img src=x onerror=alert(1)>',{exact:true}).waitFor();
|
||||
@@ -1,7 +1,7 @@
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
|
||||
const admin={user:{id:'admin',username:'admin',role:'admin'},sessionId:'admin-session'},operator={user:{id:'operator',username:'operator',role:'operator'},sessionId:'operator-session'},viewer={user:{id:'viewer',username:'viewer',role:'viewer'},sessionId:'viewer-session'};
|
||||
async function fixture(t,runtime){
|
||||
const {AssistantStore}=require('../src/assistant-store.cjs'),{AssistantService}=require('../src/assistant-service.cjs');
|
||||
const {AssistantStore}=require('../../src/modules/assistant/store.cjs'),{AssistantService}=require('../../src/modules/assistant/service.cjs');
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-assistant-')),store=new AssistantStore(dir);let checks=0,scans=0,archives=0;
|
||||
const connections=[{id:'own',owner:'operator',name:'Own BPM',status:'connected',identity:'PRIVATE_IDENTITY'},{id:'other',owner:'other',name:'Other BPM',status:'connected'}];
|
||||
const workspace={snapshot:()=>({connections,exceptions:[{id:'e1',owner:'operator',title:'扫描失败',status:'open',description:'password=PRIVATE_PASSWORD Cookie=PRIVATE_COOKIE'}]}),getConnection:id=>connections.find(c=>c.id===id),record(){}};
|
||||
@@ -14,7 +14,7 @@ async function fixture(t,runtime){
|
||||
return {dir,store,service,workspace,counters:()=>({checks,scans,archives})};
|
||||
}
|
||||
test('assistant conversations are private, encrypted and survive restart without exposing the API key',async t=>{
|
||||
const {AssistantStore}=require('../src/assistant-store.cjs'),{dir,store,service}=await fixture(t),c=store.create(admin.user.id);const turn=service.send(c.id,admin,'PRIVATE_CHAT_MESSAGE');await service.running.get(turn.id).task;
|
||||
const {AssistantStore}=require('../../src/modules/assistant/store.cjs'),{dir,store,service}=await fixture(t),c=store.create(admin.user.id);const turn=service.send(c.id,admin,'PRIVATE_CHAT_MESSAGE');await service.running.get(turn.id).task;
|
||||
assert.throws(()=>store.conversation(c.id,operator.user.id),e=>e.status===404);assert.deepEqual(store.conversations(operator.user.id),[]);assert.equal(store.settings().hasApiKey,true);assert.equal(store.settings().apiKey,undefined);
|
||||
const restart=new AssistantStore(dir);try{assert.equal(restart.conversation(c.id,admin.user.id).turns[0].text,'PRIVATE_CHAT_MESSAGE');assert.equal(restart.secretSettings().apiKey,'PRIVATE_API_KEY');}finally{restart.close();}
|
||||
for(const name of await fs.readdir(dir))if(name.includes('.sqlite')){const bytes=await fs.readFile(path.join(dir,name));assert.equal(bytes.includes(Buffer.from('PRIVATE_CHAT_MESSAGE')),false);assert.equal(bytes.includes(Buffer.from('PRIVATE_API_KEY')),false);}
|
||||
@@ -54,7 +54,7 @@ test('a cancellation signal alone cannot label an unconfirmed runtime failure as
|
||||
assert.equal(store.conversation(c.id,admin.user.id).turns[0].status,'error');
|
||||
});
|
||||
test('only a matching installed runtime is discovered, without enabling the model',async t=>{
|
||||
const {AssistantStore}=require('../src/assistant-store.cjs'),crypto=require('node:crypto'),root=await fs.mkdtemp(path.join(os.tmpdir(),'order-zcode-discovery-')),dir=path.join(root,'assistant'),install=path.join(root,'zcode-runtime'),runtimePath=path.join(install,'3.14.3/package/resources/glm/zcode.cjs');t.after(()=>fs.rm(root,{recursive:true,force:true}));
|
||||
const {AssistantStore}=require('../../src/modules/assistant/store.cjs'),crypto=require('node:crypto'),root=await fs.mkdtemp(path.join(os.tmpdir(),'order-zcode-discovery-')),dir=path.join(root,'assistant'),install=path.join(root,'zcode-runtime'),runtimePath=path.join(install,'3.14.3/package/resources/glm/zcode.cjs');t.after(()=>fs.rm(root,{recursive:true,force:true}));
|
||||
await fs.mkdir(path.dirname(runtimePath),{recursive:true});await fs.writeFile(runtimePath,'fixture');await fs.writeFile(path.join(install,'manifest.json'),JSON.stringify({releaseVersion:'3.14.3',cliVersion:'0.16.9',runtimePath,runtimeSha256:'sha256:'+crypto.createHash('sha256').update('fixture').digest('hex')}));
|
||||
const store=new AssistantStore(dir);assert.equal(store.settings().runtimePath,runtimePath);assert.equal(store.settings().enabled,false);assert.equal(store.settings().hasApiKey,false);store.close();
|
||||
await fs.writeFile(runtimePath,'modified');const changed=new AssistantStore(dir);try{assert.equal(changed.settings().runtimePath,'');}finally{changed.close();}
|
||||
@@ -1,6 +1,6 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict'),http=require('node:http'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
|
||||
const {ZcodeRuntime}=require('../src/zcode-runtime.cjs');
|
||||
const {ZcodeRuntime}=require('../../src/modules/assistant/zcode-runtime.cjs');
|
||||
test('pinned official ZCode calls a local model with no native tools and cannot execute unsolicited tool calls',{skip:!process.env.ORDER_TEST_ZCODE_CLI,timeout:180000},async t=>{
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-official-zcode-')),runtime=new ZcodeRuntime({stateDir:dir}),requests=[];let attack=false,attackSent=0,attackRequests=0;
|
||||
t.after(()=>fs.rm(dir,{recursive:true,force:true}));
|
||||
@@ -1,15 +1,15 @@
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
|
||||
test('ZCode bridge uses fixed permissions, isolated profile and filtered environment; secrets are not command arguments',async t=>{
|
||||
const {ZcodeRuntime}=require('../src/zcode-runtime.cjs'),dir=await fs.mkdtemp(path.join(os.tmpdir(),'zcode-driver-')),runtime=new ZcodeRuntime({stateDir:dir});t.after(()=>fs.rm(dir,{recursive:true,force:true}));process.env.PRIVATE_TEST_KEY='must-not-reach-zcode';t.after(()=>delete process.env.PRIVATE_TEST_KEY);
|
||||
const {ZcodeRuntime}=require('../../src/modules/assistant/zcode-runtime.cjs'),dir=await fs.mkdtemp(path.join(os.tmpdir(),'zcode-driver-')),runtime=new ZcodeRuntime({stateDir:dir});t.after(()=>fs.rm(dir,{recursive:true,force:true}));process.env.PRIVATE_TEST_KEY='must-not-reach-zcode';t.after(()=>delete process.env.PRIVATE_TEST_KEY);
|
||||
const config={runtimePath:path.resolve('tests/fixtures/zcode-fixture.cjs'),model:'fixture',apiBase:'https://models.example/v1',apiKey:'NEVER-IN-ARGV',timeoutSeconds:15,allowActions:false};
|
||||
assert.equal((await runtime.probe(config.runtimePath)).available,true);
|
||||
const result=JSON.parse(await runtime.chat({config,text:'hello $() `shell`',history:[],context:{servers:[]},signal:new AbortController().signal}));assert.equal(result.observed.privateEnv,undefined);assert.equal(result.observed.args[result.observed.args.indexOf('--mode')+1],'plan');assert.ok(result.observed.args.includes('--disallowed-tools'));assert.doesNotMatch(JSON.stringify(result.observed.args),/NEVER-IN-ARGV/);assert.equal(result.observed.config.plugins.enabled,false);assert.equal(result.observed.config.features.mcp,false);assert.equal(result.observed.config.features.subagent,false);assert.match(result.observed.cwd,/zcode-driver/);assert.deepEqual(await fs.readdir(path.join(dir,'runs')),[]);
|
||||
});
|
||||
test('ZCode cancellation and excessive output terminate the invocation and clean private profiles',async t=>{
|
||||
const {ZcodeRuntime}=require('../src/zcode-runtime.cjs'),dir=await fs.mkdtemp(path.join(os.tmpdir(),'zcode-abort-')),runtime=new ZcodeRuntime({stateDir:dir});t.after(()=>fs.rm(dir,{recursive:true,force:true}));const config={runtimePath:path.resolve('tests/fixtures/zcode-fixture.cjs'),model:'fixture',apiBase:'https://models.example/v1',apiKey:'secret',timeoutSeconds:15};
|
||||
const {ZcodeRuntime}=require('../../src/modules/assistant/zcode-runtime.cjs'),dir=await fs.mkdtemp(path.join(os.tmpdir(),'zcode-abort-')),runtime=new ZcodeRuntime({stateDir:dir});t.after(()=>fs.rm(dir,{recursive:true,force:true}));const config={runtimePath:path.resolve('tests/fixtures/zcode-fixture.cjs'),model:'fixture',apiBase:'https://models.example/v1',apiKey:'secret',timeoutSeconds:15};
|
||||
const controller=new AbortController(),pending=runtime.chat({config,text:'FIXTURE_HANG',history:[],context:{},signal:controller.signal});setTimeout(()=>controller.abort(Object.assign(new Error('cancelled'),{status:499})),350);await assert.rejects(pending,e=>e.status===499);assert.deepEqual(await fs.readdir(path.join(dir,'runs')),[]);
|
||||
await assert.rejects(runtime.chat({config,text:'FIXTURE_OVERFLOW',history:[],context:{},signal:new AbortController().signal}),e=>e.status===502);assert.deepEqual(await fs.readdir(path.join(dir,'runs')),[]);
|
||||
});
|
||||
test('cancelling during runtime discovery interrupts the probe and cleans its profile',async t=>{
|
||||
const {ZcodeRuntime}=require('../src/zcode-runtime.cjs'),dir=await fs.mkdtemp(path.join(os.tmpdir(),'zcode-probe-abort-')),entry=path.join(dir,'slow-probe.cjs'),runtime=new ZcodeRuntime({stateDir:dir});t.after(()=>fs.rm(dir,{recursive:true,force:true}));await fs.writeFile(entry,"setInterval(()=>{},1000);");const controller=new AbortController();const pending=runtime.chat({config:{runtimePath:entry,timeoutSeconds:15},text:'hello',history:[],context:{},signal:controller.signal});setTimeout(()=>controller.abort(Object.assign(new Error('cancelled'),{status:499})),500);await assert.rejects(pending,e=>e.status===499);assert.deepEqual(await fs.readdir(path.join(dir,'runs')),[]);
|
||||
const {ZcodeRuntime}=require('../../src/modules/assistant/zcode-runtime.cjs'),dir=await fs.mkdtemp(path.join(os.tmpdir(),'zcode-probe-abort-')),entry=path.join(dir,'slow-probe.cjs'),runtime=new ZcodeRuntime({stateDir:dir});t.after(()=>fs.rm(dir,{recursive:true,force:true}));await fs.writeFile(entry,"setInterval(()=>{},1000);");const controller=new AbortController();const pending=runtime.chat({config:{runtimePath:entry,timeoutSeconds:15},text:'hello',history:[],context:{},signal:controller.signal});setTimeout(()=>controller.abort(Object.assign(new Error('cancelled'),{status:499})),500);await assert.rejects(pending,e=>e.status===499);assert.deepEqual(await fs.readdir(path.join(dir,'runs')),[]);
|
||||
});
|
||||
@@ -5,8 +5,8 @@ const fs=require('node:fs/promises');
|
||||
const os=require('node:os');
|
||||
const path=require('node:path');
|
||||
const http=require('node:http');
|
||||
const {BpmSessionManager}=require('../src/bpm-session-manager.cjs');
|
||||
const {loadPlaywright,browserOptions}=require('../src/runtime.cjs');
|
||||
const {BpmSessionManager}=require('../../src/modules/bpm/session-manager.cjs');
|
||||
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
|
||||
const principal={user:{username:'owner',role:'operator'},sessionId:'session-one'};
|
||||
const connection={id:'account-test',owner:'owner',status:'disconnected'};
|
||||
const credentials={username:'Fixture User',password:' Fixture-password-123 '};
|
||||
@@ -1,8 +1,8 @@
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');
|
||||
const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
|
||||
const {WorkspaceStore}=require('../src/workspace-store.cjs');
|
||||
const {WorkspaceStore}=require('../../src/modules/workspace/store.cjs');
|
||||
test('custodian restores managed or saved sessions, skips busy/disabled connections and never overlaps',async t=>{
|
||||
let BpmCustodian;try{({BpmCustodian}=require('../src/bpm-custodian.cjs'));}catch(e){if(e.code!=='MODULE_NOT_FOUND')throw e;}
|
||||
let BpmCustodian;try{({BpmCustodian}=require('../../src/modules/bpm/custodian.cjs'));}catch(e){if(e.code!=='MODULE_NOT_FOUND')throw e;}
|
||||
assert.equal(typeof BpmCustodian,'function');
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'custodian-'));const workspace=new WorkspaceStore(dir);
|
||||
t.after(()=>{workspace.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
@@ -22,7 +22,7 @@ test('custodian restores managed or saved sessions, skips busy/disabled connecti
|
||||
const stopped=custodian.stop();await stopped;await custodian.tick();assert.equal(calls.length,2);
|
||||
});
|
||||
test('custodian start restores saved state without managed credentials and stop waits for running check',async()=>{
|
||||
const {BpmCustodian}=require('../src/bpm-custodian.cjs');let finish,started;const active=new Promise(r=>started=r),gate=new Promise(r=>finish=r);let updates=0;
|
||||
const {BpmCustodian}=require('../../src/modules/bpm/custodian.cjs');let finish,started;const active=new Promise(r=>started=r),gate=new Promise(r=>finish=r);let updates=0;
|
||||
const connection={id:'saved',status:'unchecked',lastConnectedAt:'2026-10-16T00:00:00Z'};
|
||||
const workspace={snapshot:()=>({connections:[connection]}),getConnection:()=>connection,updateConnectionSession:()=>updates++};
|
||||
const manager={account:async()=>({configured:false}),ensure:async()=>{started();await gate;return {};}};
|
||||
@@ -1,5 +1,5 @@
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');const http=require('node:http');
|
||||
const {Store}=require('../src/dashboard-store.cjs');const {WorkspaceStore}=require('../src/workspace-store.cjs');const {createDashboard}=require('../src/dashboard.cjs');
|
||||
const {Store}=require('../../src/modules/dashboard/store.cjs');const {WorkspaceStore}=require('../../src/modules/workspace/store.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs');
|
||||
const result=(status='connected')=>({status,identity:'alice@bpm',checkedAt:'2026-10-16T01:00:00.000Z',checks:{portal:{ok:status==='connected',message:'门户检查'}}});
|
||||
async function setup(t,options={}){
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'bpm-http-'));const store=new Store(path.join(dir,'users'));const admin=store.bootstrap('admin','Test-password-123');for(const [username,role] of [['alice','operator'],['bob','operator'],['reader','viewer']])store.addUser({username,password:'Test-password-123',role},'admin');const workspace=new WorkspaceStore(path.join(dir,'workspace'));let lease;let next=result();let disabled=0,released=0;const jpg=Buffer.from([255,216,255,217]);
|
||||
@@ -50,7 +50,7 @@ test('remote credentials require local host or explicit local HTTPS proxy and re
|
||||
const trusted=await setup(t,{trustedProxy:true});const proxy={host:'workspace.example',origin:'https://workspace.example',headers:{'X-Forwarded-Proto':'https'}};const proxyLogin=await trusted.call('/api/login',{username:'alice',password:'Test-password-123'},undefined,proxy);assert.match(proxyLogin.headers['set-cookie'][0],/; Secure(?:;|$)/);const owner=proxyLogin.headers['set-cookie'][0].split(';')[0];assert.equal((await trusted.call(trusted.route+'/login/open',{},owner,proxy)).status,200);
|
||||
});
|
||||
test('transport never trusts remote LAN address with local Host or forwarded HTTPS, but accepts TLS and configured loopback proxy',()=>{
|
||||
const {secureBpmTransport}=require('../src/bpm-api.cjs');
|
||||
const {secureBpmTransport}=require('../../src/modules/bpm/api.cjs');
|
||||
const request=(host,remoteAddress,encrypted=false,proto)=>({socket:{remoteAddress,encrypted},headers:{host,'x-forwarded-proto':proto}});
|
||||
for(const trusted of [false,true]){
|
||||
assert.equal(secureBpmTransport(request('localhost','192.168.1.10',false,'https'),trusted),false);
|
||||
@@ -4,13 +4,13 @@ const fs=require('node:fs/promises');
|
||||
const os=require('node:os');
|
||||
const path=require('node:path');
|
||||
const http=require('node:http');
|
||||
const {loadPlaywright,browserOptions}=require('../src/runtime.cjs');
|
||||
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
|
||||
|
||||
test('formal dashboard remote screen signs into an isolated BPM fixture under production CSP',async t=>{
|
||||
const {Store}=require('../src/dashboard-store.cjs');
|
||||
const {WorkspaceStore}=require('../src/workspace-store.cjs');
|
||||
const {BpmSessionManager}=require('../src/bpm-session-manager.cjs');
|
||||
const {createDashboard}=require('../src/dashboard.cjs');
|
||||
const {Store}=require('../../src/modules/dashboard/store.cjs');
|
||||
const {WorkspaceStore}=require('../../src/modules/workspace/store.cjs');
|
||||
const {BpmSessionManager}=require('../../src/modules/bpm/session-manager.cjs');
|
||||
const {createDashboard}=require('../../src/app/dashboard.cjs');
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-full-ui-'));
|
||||
const site=http.createServer((req,res)=>{
|
||||
res.setHeader('Content-Type','text/html; charset=utf-8');
|
||||
@@ -1,5 +1,5 @@
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
|
||||
const {WorkspaceStore}=require('../src/workspace-store.cjs');
|
||||
const {WorkspaceStore}=require('../../src/modules/workspace/store.cjs');
|
||||
test('new BPM portal alone marks connected and legacy connection metadata migrates without losing ownership',t=>{
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'bpm-portal-'));let store=new WorkspaceStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
const actor={username:'owner',role:'admin'},c=store.createConnection({name:'BPM',owner:'owner'},actor,[actor]);
|
||||
@@ -1,6 +1,6 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
|
||||
const {BpmSessionManager}=require('../src/bpm-session-manager.cjs');
|
||||
const {BpmSessionManager}=require('../../src/modules/bpm/session-manager.cjs');
|
||||
test('disposed BPM responses and rejected navigation aborts are contained in the route handler',async t=>{
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-route-errors-'));let handler;
|
||||
const origin='http://127.0.0.1:18888',page={url:()=>origin+'/',goto:async()=>{},on(){}},network={on(){},send:async method=>method==='Page.getFrameTree'?{frameTree:{frame:{id:'main'}}}:{}};
|
||||
@@ -8,7 +8,7 @@ const net=require('node:net');
|
||||
async function freePort(){const server=net.createServer();await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));const port=server.address().port;await new Promise(resolve=>server.close(resolve));return port;}
|
||||
|
||||
test('formal runtime wires BPM sessions and preserves users across restart',async t=>{
|
||||
const {main}=require('../src/server.cjs');
|
||||
const {main}=require('../../src/server.cjs');
|
||||
assert.equal(typeof main,'function','formal runtime must support isolated startup and shutdown');
|
||||
const stateDir=fs.mkdtempSync(path.join(os.tmpdir(),'order-runtime-'));
|
||||
let app;
|
||||
@@ -1,5 +1,5 @@
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
|
||||
const {Store}=require('../src/dashboard-store.cjs');const {WorkspaceStore}=require('../src/workspace-store.cjs');const {BpmScanStore}=require('../src/bpm-scan-store.cjs');const {BpmScanner}=require('../src/bpm-scanner.cjs');const {createDashboard}=require('../src/dashboard.cjs');const {normalizeArrival}=require('../src/bpm-list-client.cjs');const {loadPlaywright,browserOptions}=require('../src/runtime.cjs');
|
||||
const {Store}=require('../../src/modules/dashboard/store.cjs');const {WorkspaceStore}=require('../../src/modules/workspace/store.cjs');const {BpmScanStore}=require('../../src/modules/bpm/scan-store.cjs');const {BpmScanner}=require('../../src/modules/bpm/scanner.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs');const {normalizeArrival}=require('../../src/modules/bpm/list-client.cjs');const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
|
||||
async function setup(t){
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'scan-http-')),store=new Store(path.join(dir,'users')),workspace=new WorkspaceStore(path.join(dir,'workspace')),scanStore=new BpmScanStore(path.join(dir,'scan'));
|
||||
store.bootstrap('admin','Test-password-123');store.addUser({username:'reader',password:'Test-password-123',role:'viewer'},'admin');store.addUser({username:'other',password:'Test-password-123',role:'operator'},'admin');
|
||||
@@ -1,8 +1,8 @@
|
||||
const test=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');const http=require('node:http');
|
||||
const {BpmListClient,normalizeArrival}=require('../src/bpm-list-client.cjs');
|
||||
const {BpmScanStore}=require('../src/bpm-scan-store.cjs');
|
||||
const {BpmScanner}=require('../src/bpm-scanner.cjs');
|
||||
const {BpmSessionManager}=require('../src/bpm-session-manager.cjs');
|
||||
const {BpmListClient,normalizeArrival}=require('../../src/modules/bpm/list-client.cjs');
|
||||
const {BpmScanStore}=require('../../src/modules/bpm/scan-store.cjs');
|
||||
const {BpmScanner}=require('../../src/modules/bpm/scanner.cjs');
|
||||
const {BpmSessionManager}=require('../../src/modules/bpm/session-manager.cjs');
|
||||
const row=(id,date='2026-10-15T16:33:58')=>({taskId:id,serialNum:'SN-'+id,processName:'订单评审',activityName:'知会',startTime:date,processInstanceSubject:'<b>订单号:</b>123 & 456',processInstanceInitiatorShortName:'甲'});
|
||||
test('arrival uses received time in Shanghai, strips HTML, never substitutes scan time',()=>{
|
||||
const a=normalizeArrival(row('1'),'portal-v4');assert.equal(a.arrivalDay,'2026-10-15');assert.equal(a.arrivedAt,'2026-10-15T08:33:58.000Z');assert.equal(a.subject,'订单号:123 & 456');
|
||||
@@ -4,7 +4,7 @@ const fs = require('node:fs/promises');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const http = require('node:http');
|
||||
const { loadPlaywright, browserOptions } = require('../src/runtime.cjs');
|
||||
const { loadPlaywright, browserOptions } = require('../../src/platform/browser.cjs');
|
||||
const principal = { user: { id: '1', username: 'owner', role: 'operator' }, sessionId: 'dashboard-session' };
|
||||
const connection = { id: 'a', owner: 'owner', status: 'disconnected' };
|
||||
const other = { user: { id: '2', username: 'intruder', role: 'operator' }, sessionId: 'other-session' };
|
||||
@@ -15,7 +15,7 @@ async function login(){const db=await dbp;await new Promise(r=>{const t=db.trans
|
||||
</script>`;
|
||||
|
||||
async function fixture(t) {
|
||||
const { BpmSessionManager } = require('../src/bpm-session-manager.cjs');
|
||||
const { BpmSessionManager } = require('../../src/modules/bpm/session-manager.cjs');
|
||||
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'bpm-browser-'));
|
||||
let blockedHits = 0;const requests=[];
|
||||
const forbidden = http.createServer((req,res) => { blockedHits++; res.end('forbidden'); });
|
||||
@@ -109,7 +109,7 @@ test('legacy detail navigation is rejected before any request',async t=>{
|
||||
});
|
||||
|
||||
test('production origin policy permits verified company SSO but rejects lookalikes and arbitrary injections', async t => {
|
||||
const { BpmSessionManager } = require('../src/bpm-session-manager.cjs');
|
||||
const { BpmSessionManager } = require('../../src/modules/bpm/session-manager.cjs');
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-origin-'));
|
||||
t.after(()=>fs.rm(dir,{recursive:true,force:true}));
|
||||
const manager=new BpmSessionManager({stateDir:dir}); t.after(()=>manager.shutdown());
|
||||
@@ -3,11 +3,11 @@ const assert=require('node:assert/strict');
|
||||
const fs=require('node:fs');
|
||||
const http=require('node:http');
|
||||
const path=require('node:path');
|
||||
const {loadPlaywright,browserOptions}=require('../src/runtime.cjs');
|
||||
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
|
||||
const {setTimeout:delay}=require('node:timers/promises');
|
||||
async function waitUntil(predicate){const deadline=Date.now()+10000;while(!predicate()){assert.ok(Date.now()<deadline,'expected browser request did not arrive');await delay(25);}}
|
||||
let browser,server,base,jpeg;
|
||||
const source=path.join(__dirname,'../web/bpm.js');
|
||||
const source=path.join(__dirname,'../../web/modules/bpm/view.js');
|
||||
before(async()=>{
|
||||
browser=await loadPlaywright().chromium.launch(browserOptions());
|
||||
const page=await browser.newPage({viewport:{width:1280,height:800}});jpeg=await page.screenshot({type:'jpeg'});await page.close();
|
||||
@@ -42,7 +42,7 @@ async function fixture(t,{user={username:'alice',role:'operator'},connections,ac
|
||||
await route.fulfill({json:result});
|
||||
});
|
||||
await page.goto(base);
|
||||
await page.addStyleTag({path:path.join(__dirname,'../web/app.css')});
|
||||
await page.addStyleTag({path:path.join(__dirname,'../../web/app.css')});
|
||||
if(fs.existsSync(source))await page.addScriptTag({path:source});
|
||||
assert.equal(await page.evaluate(()=>typeof window.BpmLogin?.mount),'function','BPM page exposes a working mount function');
|
||||
await page.evaluate(async user=>{
|
||||
@@ -259,7 +259,7 @@ test('refresh and logout release BPM control before rendering or dropping authen
|
||||
const vm=require('node:vm'),events=[],elements=new Map();
|
||||
const element=id=>{if(!elements.has(id))elements.set(id,{innerHTML:'',textContent:'',classList:{remove(){}},querySelector(){return {disabled:false};}});return elements.get(id);};
|
||||
const context=vm.createContext({Intl,setTimeout,clearInterval,location:{hash:'#overview'},document:{querySelector:element,querySelectorAll:()=>[]},window:{addEventListener(){},BpmLogin:{dispose:async()=>events.push('release')},WorkspaceViews:{overview:async()=>events.push('render')}}});
|
||||
const source=fs.readFileSync(path.join(__dirname,'../web/app.js'),'utf8').replace(/boot\(\)\.catch[\s\S]*$/,'');
|
||||
const source=fs.readFileSync(path.join(__dirname,'../../web/app.js'),'utf8').replace(/boot\(\)\.catch[\s\S]*$/,'');
|
||||
vm.runInContext(source,context);
|
||||
await vm.runInContext("currentUser={username:'alice',role:'admin'};renderView()",context);
|
||||
assert.deepEqual(events,['release','render']);events.length=0;
|
||||
@@ -269,14 +269,14 @@ test('refresh and logout release BPM control before rendering or dropping authen
|
||||
test('an expired login request rejects without waiting on its own remote cleanup',async()=>{
|
||||
const vm=require('node:vm'),events=[];
|
||||
const context=vm.createContext({Intl,setTimeout,fetch:async()=>({status:401,ok:false,json:async()=>({error:'请重新登录。'})}),document:{querySelector:()=>({})},window:{addEventListener(){},BpmLogin:{dispose:()=>new Promise(()=>{})}},events});
|
||||
const source=fs.readFileSync(path.join(__dirname,'../web/app.js'),'utf8').replace(/boot\(\)\.catch[\s\S]*$/,'');vm.runInContext(source,context);
|
||||
const source=fs.readFileSync(path.join(__dirname,'../../web/app.js'),'utf8').replace(/boot\(\)\.catch[\s\S]*$/,'');vm.runInContext(source,context);
|
||||
const pending=vm.runInContext("currentUser={username:'alice',role:'operator'};boot=async()=>events.push('login');api('/connections/one/login/open',{}).then(()=> 'resolved',()=> 'rejected')",context);
|
||||
assert.equal(await Promise.race([pending,new Promise(resolve=>setTimeout(()=>resolve('pending'),100))]),'rejected');assert.deepEqual(events,['login']);
|
||||
});
|
||||
for(const pendingAction of ['open','save'])test(`document unload sends authenticated close while ${pendingAction} is pending`,async t=>{
|
||||
const calls=[];let finishPending=()=>{},pendingStarted;
|
||||
const started=new Promise(resolve=>pendingStarted=resolve);
|
||||
const appSource=fs.readFileSync(path.join(__dirname,'../web/app.js'),'utf8').replace(/boot\(\)\.catch[\s\S]*$/,'');
|
||||
const appSource=fs.readFileSync(path.join(__dirname,'../../web/app.js'),'utf8').replace(/boot\(\)\.catch[\s\S]*$/,'');
|
||||
const fixtureServer=http.createServer(async(req,res)=>{
|
||||
const requestPath=new URL(req.url,'http://localhost').pathname;
|
||||
if(requestPath==='/bpm.js'||requestPath==='/app.js'){res.setHeader('Content-Type','application/javascript; charset=utf-8');return res.end(requestPath==='/bpm.js'?fs.readFileSync(source):appSource);}
|
||||
@@ -5,7 +5,7 @@ const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
|
||||
test('session updates remain atomic when the state directory rejects file renames',async t=>{
|
||||
const {BpmVault}=require('../src/bpm-vault.cjs');
|
||||
const {BpmVault}=require('../../src/platform/security/vault.cjs');
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-session-rename-'));
|
||||
const vault=new BpmVault({stateDir:dir});
|
||||
t.after(async()=>{vault.destroy();await fs.rm(dir,{recursive:true,force:true});});
|
||||
@@ -18,7 +18,7 @@ test('session updates remain atomic when the state directory rejects file rename
|
||||
});
|
||||
|
||||
test('managed accounts use an encrypted SQLite registry with uniqueness across connections and restarts',async t=>{
|
||||
const {BpmVault}=require('../src/bpm-vault.cjs');
|
||||
const {BpmVault}=require('../../src/platform/security/vault.cjs');
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-accounts-db-'));
|
||||
const vault=new BpmVault({stateDir:dir}),second=new BpmVault({stateDir:dir});
|
||||
t.after(async()=>{vault.destroy();second.destroy();await fs.rm(dir,{recursive:true,force:true});});
|
||||
@@ -38,7 +38,7 @@ test('managed accounts use an encrypted SQLite registry with uniqueness across c
|
||||
});
|
||||
|
||||
test('simultaneous account saves admit only one normalized username and preserve other records',async t=>{
|
||||
const {BpmVault}=require('../src/bpm-vault.cjs');const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-unique-'));
|
||||
const {BpmVault}=require('../../src/platform/security/vault.cjs');const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-unique-'));
|
||||
const vault=new BpmVault({stateDir:dir}),other=new BpmVault({stateDir:dir});
|
||||
t.after(async()=>{vault.destroy();other.destroy();await fs.rm(dir,{recursive:true,force:true});});
|
||||
await vault.write('account:existing',{username:'different',password:'keep-this'});
|
||||
@@ -49,7 +49,7 @@ test('simultaneous account saves admit only one normalized username and preserve
|
||||
});
|
||||
|
||||
test('legacy encrypted account files migrate atomically and conflicting legacy files are retained',async t=>{
|
||||
const {BpmVault}=require('../src/bpm-vault.cjs'),crypto=require('node:crypto');const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-legacy-'));
|
||||
const {BpmVault}=require('../../src/platform/security/vault.cjs'),crypto=require('node:crypto');const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-legacy-'));
|
||||
const vault=new BpmVault({stateDir:dir});t.after(async()=>{vault.destroy();await fs.rm(dir,{recursive:true,force:true});});
|
||||
const legacy=async(id,username)=>{const key='account:'+id,iv=crypto.randomBytes(12),cipher=crypto.createCipheriv('aes-256-gcm',vault.ensureKey(),iv);cipher.setAAD(Buffer.from(key));const data=Buffer.concat([cipher.update(JSON.stringify({username,password:'legacy-secret',nextAttemptAt:'2030-01-01T00:00:00Z'})),cipher.final()]);await fs.writeFile(vault.filename(key),Buffer.concat([Buffer.from('BPM1'),iv,cipher.getAuthTag(),data]));};
|
||||
await legacy('one','First.User');await legacy('two','first.user');
|
||||
@@ -63,7 +63,7 @@ test('legacy encrypted account files migrate atomically and conflicting legacy f
|
||||
});
|
||||
|
||||
test('vault encrypts state, survives restart, rejects corruption and keeps connection isolation', async t => {
|
||||
const { BpmVault } = require('../src/bpm-vault.cjs');
|
||||
const { BpmVault } = require('../../src/platform/security/vault.cjs');
|
||||
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'bpm-vault-'));
|
||||
const vault = new BpmVault({ stateDir: dir });
|
||||
t.after(async()=>{vault.destroy();await fs.rm(dir,{recursive:true,force:true});});
|
||||
@@ -82,7 +82,7 @@ test('vault encrypts state, survives restart, rejects corruption and keeps conne
|
||||
});
|
||||
|
||||
test('vault binds ciphertext to connection identity and never leaves plaintext temporary files', async t => {
|
||||
const { BpmVault } = require('../src/bpm-vault.cjs');
|
||||
const { BpmVault } = require('../../src/platform/security/vault.cjs');
|
||||
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'bpm-vault-'));
|
||||
const vault = new BpmVault({ stateDir: dir });
|
||||
t.after(async()=>{vault.destroy();await fs.rm(dir,{recursive:true,force:true});});
|
||||
@@ -95,7 +95,7 @@ test('vault binds ciphertext to connection identity and never leaves plaintext t
|
||||
});
|
||||
|
||||
test('legacy session ciphertext migrates, database state wins, and removal cannot restore a stale file',async t=>{
|
||||
const {BpmVault}=require('../src/bpm-vault.cjs'),dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-legacy-session-')),vault=new BpmVault({stateDir:dir});
|
||||
const {BpmVault}=require('../../src/platform/security/vault.cjs'),dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-legacy-session-')),vault=new BpmVault({stateDir:dir});
|
||||
t.after(async()=>{vault.destroy();await fs.rm(dir,{recursive:true,force:true});});
|
||||
const old={storageState:{cookies:[]},sessionStorage:{portal:{token:'legacy-private-token'}}};
|
||||
await fs.writeFile(vault.filename('legacy'),vault.encode('legacy',old));
|
||||
@@ -4,7 +4,7 @@ const fs=require('node:fs');
|
||||
const os=require('node:os');
|
||||
const path=require('node:path');
|
||||
test('workbench sessions persist for thirty days, renew with activity and revoke without storing raw tokens',t=>{
|
||||
let SessionStore;try{({SessionStore}=require('../src/dashboard-sessions.cjs'));}catch(error){if(error.code!=='MODULE_NOT_FOUND')throw error;}
|
||||
let SessionStore;try{({SessionStore}=require('../../src/modules/dashboard/sessions.cjs'));}catch(error){if(error.code!=='MODULE_NOT_FOUND')throw error;}
|
||||
assert.equal(typeof SessionStore,'function','persistent workbench sessions missing');
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'workbench-auth-'));let store;
|
||||
t.after(()=>{store?.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
@@ -4,7 +4,7 @@ const fs=require('node:fs');
|
||||
const os=require('node:os');
|
||||
const path=require('node:path');
|
||||
let Store, nextSlots;
|
||||
try { ({Store}=require('../src/dashboard-store.cjs')); ({nextSlots}=require('../src/schedule.cjs')); } catch(e){if(e.code!=='MODULE_NOT_FOUND')throw e;}
|
||||
try { ({Store}=require('../../src/modules/dashboard/store.cjs')); ({nextSlots}=require('../../src/shared/schedule.cjs')); } catch(e){if(e.code!=='MODULE_NOT_FOUND')throw e;}
|
||||
function fixture(t){assert.equal(typeof Store,'function','dashboard store not implemented');const dir=fs.mkdtempSync(path.join(os.tmpdir(),'dashboard-store-'));t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));return {dir,store:new Store(dir)};}
|
||||
test('configuration is persisted and stale edits cannot overwrite another colleague',t=>{
|
||||
const {dir,store}=fixture(t);
|
||||
Vendored
+1
-1
@@ -1,5 +1,5 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs'),http=require('node:http'),{respondToPing}=require('../../src/service-ping.cjs');
|
||||
const fs=require('node:fs'),http=require('node:http'),{respondToPing}=require('../../src/platform/service/ping.cjs');
|
||||
const file=process.env.ORDER_FIXTURE_COUNT,generation=(fs.existsSync(file)?Number(fs.readFileSync(file,'utf8')):0)+1;fs.writeFileSync(file,String(generation));
|
||||
const startedAt=new Date().toISOString();let hang=false;
|
||||
const server=http.createServer((req,res)=>{fs.writeFileSync(file+'.heartbeat',String(req.headers['x-order-watchdog']||''));if(hang)return;respondToPing(req,res,{token:process.env.ORDER_SUPERVISOR_TOKEN,instanceId:process.env.ORDER_SUPERVISOR_INSTANCE,startedAt});});
|
||||
|
||||
Vendored
+1
-1
@@ -1,6 +1,6 @@
|
||||
// Local test fixture, never used by the production launcher. No BPM/mail access.
|
||||
const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
|
||||
const {Store}=require('../../src/dashboard-store.cjs');const {createDashboard}=require('../../src/dashboard.cjs');
|
||||
const {Store}=require('../../src/modules/dashboard/store.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs');
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'order-dashboard-ui-'));const store=new Store(dir);
|
||||
store.bootstrap('preview','Preview-only-test-2026');
|
||||
const server=createDashboard({store,outputDir:dir});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
|
||||
const {Store}=require('../src/dashboard-store.cjs');const {createDashboard}=require('../src/dashboard.cjs');const {MailStore}=require('../src/mail-store.cjs');const {MailService}=require('../src/mail-service.cjs');const {parseTemplate}=require('../src/mail-parser.cjs');
|
||||
const {Store}=require('../../src/modules/dashboard/store.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs');const {MailStore}=require('../../src/modules/mail/store.cjs');const {MailService}=require('../../src/modules/mail/service.cjs');const {parseTemplate}=require('../../src/modules/mail/parser.cjs');
|
||||
const config={name:'邮箱',email:'orders@company.test',smtp:{host:'smtp.company.test',port:465,security:'tls',user:'orders',password:'Secret-mail-123'},imap:{host:'imap.company.test',port:993,security:'tls',user:'orders',password:'Secret-mail-123'},senders:['author@company.test'],enabled:true};
|
||||
async function setup(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'mail-http-'));const store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');store.addUser({username:'reader',password:'Test-password-123',role:'viewer'},'admin');const mailStore=new MailStore(path.join(dir,'mail'));const mail=new MailService({store:mailStore});const server=createDashboard({store,mail,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(async()=>{await mail.stop();await new Promise(r=>server.close(r));mailStore.close();fs.rmSync(dir,{recursive:true,force:true});});const base='http://127.0.0.1:'+server.address().port;const call=(route,body,cookie,origin=base)=>fetch(base+route,{method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{'Content-Type':'application/json',Origin:origin}),...(cookie?{Cookie:cookie}:{})},body:body===undefined?undefined:JSON.stringify(body)});const login=async username=>(await call('/api/login',{username,password:'Test-password-123'})).headers.get('set-cookie').split(';')[0];return {mail,mailStore,call,login};}
|
||||
test('mail API uses authentication, roles, same origin, redacted config and actual overview status',async t=>{
|
||||
@@ -1,5 +1,5 @@
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const path=require('node:path');const os=require('node:os');const {SMTPServer}=require('smtp-server');const {simpleParser}=require('mailparser');
|
||||
const {MailStore}=require('../src/mail-store.cjs');const {MailService}=require('../src/mail-service.cjs');
|
||||
const {MailStore}=require('../../src/modules/mail/store.cjs');const {MailService}=require('../../src/modules/mail/service.cjs');
|
||||
const config={name:'邮箱',email:'orders@company.test',smtp:{host:'smtp.company.test',port:465,security:'tls',user:'orders',password:'Secret-mail-123'},imap:{host:'imap.company.test',port:993,security:'tls',user:'orders',password:'Secret-mail-123'},senders:['author@company.test'],enabled:true};
|
||||
const raw=Buffer.from('From: author@company.test\r\nTo: orders@company.test\r\nSubject: [模板]Notice\r\nMessage-ID: <a@company.test>\r\n\r\nHello {{订单号}}');
|
||||
async function fixture(t,options={}){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'mail-service-'));const store=new MailStore(dir);const service=new MailService({store,...options});t.after(async()=>{await service.stop();store.close();fs.rmSync(dir,{recursive:true,force:true});});return {store,service};}
|
||||
@@ -15,5 +15,5 @@ test('initial empty seven-day scan retains date boundary on future polls',async
|
||||
test('SMTP verification never sends; explicit self-test uses confirmed template and durable send record',async t=>{
|
||||
let messages=[];const smtp=new SMTPServer({secure:false,hideSTARTTLS:true,authOptional:true,disabledCommands:['AUTH'],onData(stream,session,cb){const chunks=[];stream.on('data',c=>chunks.push(c));stream.on('end',()=>{messages.push(Buffer.concat(chunks));cb();});}});await new Promise(r=>smtp.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>smtp.close(r)));
|
||||
const nodemailer=require('nodemailer');const {store,service}=await fixture(t,{smtpFactory:()=>nodemailer.createTransport({host:'127.0.0.1',port:smtp.server.address().port,secure:false,ignoreTLS:true}),imapFactory:()=>({on(){},async connect(){},async getMailboxLock(){return {release(){}};},async logout(){},close(){}})});
|
||||
const c=store.saveChannel(config);await service.verify(c.id);assert.equal(messages.length,0);const p=require('../src/mail-parser.cjs');const draft=store.ingest(c.id,'1',1,await p.parseTemplate(raw,config),raw,c.version);assert.equal(store.active(c.id,''),null);await assert.rejects(service.sendTest(c.id,draft.id),e=>e.status===409);store.confirm(draft.id,{version:1,subject:'Notice {{订单号}}',scope:'',text:'Hello {{订单号}}',useText:false},'admin');await service.sendTest(c.id,draft.id);assert.equal(messages.length,1);const sent=await simpleParser(messages[0]);assert.equal(sent.to.value[0].address,config.email);assert.match(sent.text,/Hello TEST/);assert.equal(store.sends()[0].status,'sent');
|
||||
const c=store.saveChannel(config);await service.verify(c.id);assert.equal(messages.length,0);const p=require('../../src/modules/mail/parser.cjs');const draft=store.ingest(c.id,'1',1,await p.parseTemplate(raw,config),raw,c.version);assert.equal(store.active(c.id,''),null);await assert.rejects(service.sendTest(c.id,draft.id),e=>e.status===409);store.confirm(draft.id,{version:1,subject:'Notice {{订单号}}',scope:'',text:'Hello {{订单号}}',useText:false},'admin');await service.sendTest(c.id,draft.id);assert.equal(messages.length,1);const sent=await simpleParser(messages[0]);assert.equal(sent.to.value[0].address,config.email);assert.match(sent.text,/Hello TEST/);assert.equal(store.sends()[0].status,'sent');
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');const {loadPlaywright,browserOptions}=require('../src/runtime.cjs');const {Store}=require('../src/dashboard-store.cjs');const {createDashboard}=require('../src/dashboard.cjs');const {MailStore}=require('../src/mail-store.cjs');const {MailService}=require('../src/mail-service.cjs');const {parseTemplate}=require('../src/mail-parser.cjs');
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');const {Store}=require('../../src/modules/dashboard/store.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs');const {MailStore}=require('../../src/modules/mail/store.cjs');const {MailService}=require('../../src/modules/mail/service.cjs');const {parseTemplate}=require('../../src/modules/mail/parser.cjs');
|
||||
test('mail management saves a real config, previews template under CSP and confirms after review; narrow layout stays inside viewport',async t=>{
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'mail-ui-')),store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');const mailStore=new MailStore(path.join(dir,'mail')),mail=new MailService({store:mailStore});const server=createDashboard({store,mail,outputDir:dir});let browser;
|
||||
t.after(async()=>{await browser?.close();await mail.stop();await new Promise(r=>server.close(r));mailStore.close();fs.rmSync(dir,{recursive:true,force:true});});await new Promise(r=>server.listen(0,'127.0.0.1',r));const base='http://127.0.0.1:'+server.address().port;browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage({viewport:{width:1360,height:950}});const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto(base+'/#mail');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'添加邮箱',exact:true}).click({timeout:5000});
|
||||
@@ -1,6 +1,6 @@
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
|
||||
const {parseTemplate,renderTemplate}=require('../src/mail-parser.cjs');
|
||||
const {MailStore}=require('../src/mail-store.cjs');
|
||||
const {parseTemplate,renderTemplate}=require('../../src/modules/mail/parser.cjs');
|
||||
const {MailStore}=require('../../src/modules/mail/store.cjs');
|
||||
const config={name:'通知邮箱',email:'Orders@company.test',smtp:{host:'smtp.company.test',port:465,security:'tls',user:'orders',password:'Secret-mail-123'},imap:{host:'imap.company.test',port:993,security:'tls',user:'orders',password:'Secret-mail-123'},senders:['author@company.test'],enabled:true};
|
||||
const eml=(subject='[模板][海外运营]订单 {{订单号}}',body='你好,{{产品线}}\r\n{{订单列表}}',from='author@company.test')=>Buffer.from(`From: ${from}\r\nTo: orders@company.test\r\nSubject: =?UTF-8?B?${Buffer.from(subject).toString('base64')}?=\r\nMessage-ID: <test1@company.test>\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n${body}`);
|
||||
async function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'mail-'));const store=new MailStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});return {dir,store};}
|
||||
@@ -41,6 +41,6 @@ test('source message duplicates under new UID and epoch never generate new versi
|
||||
store.saveChannel({...config,id:c.id,version:1,enabled:false});assert.throws(()=>store.ingest(c.id,'2',100,p,eml(),1),e=>e.status===409);assert.equal(store.cursor(c.id).uid,99);
|
||||
});
|
||||
module.exports={config,eml};
|
||||
test('repeated CID references are rejected before expanding to unbounded HTML',()=>{const {cleanHtml}=require('../src/mail-parser.cjs');assert.throws(()=>cleanHtml('<img src="cid:logo">'.repeat(200),[{cid:'logo',contentType:'image/png',content:Buffer.alloc(100000).toString('base64')}]),e=>e.status===400&&/内嵌图片/.test(e.message));});
|
||||
test('repeated CID references are rejected before expanding to unbounded HTML',()=>{const {cleanHtml}=require('../../src/modules/mail/parser.cjs');assert.throws(()=>cleanHtml('<img src="cid:logo">'.repeat(200),[{cid:'logo',contentType:'image/png',content:Buffer.alloc(100000).toString('base64')}]),e=>e.status===400&&/内嵌图片/.test(e.message));});
|
||||
test('outgoing embedded images use MIME content IDs and template lists never decode raw messages',async t=>{const {store}=await fixture(t);const c=store.saveChannel(config);const parsed={subject:'Notice',scope:'',text:'Image',html:'<img src="data:image/png;base64,aGVsbG8=">',sender:'author@company.test',attachments:[{filename:'a.png',cid:'logo',contentType:'image/png',content:'aGVsbG8=',inline:true,size:5}]};const d=store.ingest(c.id,'1',1,parsed,Buffer.from('raw'),1);assert.match(renderTemplate(parsed,{}).html,/src="cid:logo"/);const decode=store.decode;store.decode=()=>{throw new Error('must not decode payload');};try{assert.equal(store.templates()[0].id,d.id);}finally{store.decode=decode;}});
|
||||
test('legacy draft can be assigned once to a real mailbox without losing body',async t=>{const {store}=await fixture(t);const c=store.saveChannel(config);store.migrateLegacy({subject:'旧草稿',body:'保留正文'});const d=store.templates()[0];const saved=store.confirm(d.id,{version:1,channelId:c.id,subject:'正式标题',scope:'',useText:false},'admin');assert.equal(saved.channelId,c.id);assert.equal(saved.text,'保留正文');assert.equal(store.active(c.id,'').id,d.id);store.migrateLegacy({subject:'旧草稿',body:'保留正文'});assert.equal(store.templates().length,1);});
|
||||
@@ -1,5 +1,5 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs/promises');const os=require('node:os');const path=require('node:path');const {Store}=require('../src/dashboard-store.cjs');const {NotificationStore,NotificationService}=require('../src/notifications.cjs');const {createDashboard}=require('../src/dashboard.cjs');
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs/promises');const os=require('node:os');const path=require('node:path');const {Store}=require('../../src/modules/dashboard/store.cjs');const {NotificationStore,NotificationService}=require('../../src/modules/notifications/notifications.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs');
|
||||
test('notification HTTP exposes configurable mapping and preview without sending, with role and origin checks',async t=>{
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'notice-http-')),store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');for(const role of ['operator','viewer'])store.addUser({username:role,password:'Test-password-123',role},'admin');const notificationStore=new NotificationStore(path.join(dir,'notifications')),notifications=new NotificationService({store:notificationStore,mail:{},settings:()=>store.settings()}),server=createDashboard({store,notifications,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(async()=>{await notifications.stop();server.closeAllConnections();await new Promise(r=>server.close(r));notificationStore.close();await fs.rm(dir,{recursive:true,force:true});});const base='http://127.0.0.1:'+server.address().port,call=(route,body,cookie,origin=base)=>fetch(base+route,{method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{'Content-Type':'application/json',Origin:origin}),...(cookie?{Cookie:cookie}:{})},body:body===undefined?undefined:JSON.stringify(body)}),login=async username=>(await call('/api/login',{username,password:'Test-password-123'})).headers.get('set-cookie').split(';')[0];
|
||||
assert.equal((await call('/api/notifications')).status,401);const admin=await login('admin'),operator=await login('operator'),viewer=await login('viewer');const config=notificationStore.settings();assert.equal((await call('/api/notifications/settings',config,operator)).status,403);assert.equal((await call('/api/notifications/settings',config,admin,'https://evil.test')).status,403);assert.equal((await call('/api/notifications/settings',config,admin)).status,200);
|
||||
@@ -1,5 +1,5 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs/promises');const os=require('node:os');const path=require('node:path');const {Store}=require('../src/dashboard-store.cjs');const {NotificationStore,NotificationService}=require('../src/notifications.cjs');const {createDashboard}=require('../src/dashboard.cjs');const {loadPlaywright,browserOptions}=require('../src/runtime.cjs');
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs/promises');const os=require('node:os');const path=require('node:path');const {Store}=require('../../src/modules/dashboard/store.cjs');const {NotificationStore,NotificationService}=require('../../src/modules/notifications/notifications.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs');const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
|
||||
test('notification page saves field maps and previews original text without queuing or sending',{timeout:90000},async t=>{
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'notice-ui-')),store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');const notificationStore=new NotificationStore(path.join(dir,'notifications')),notifications=new NotificationService({store:notificationStore,mail:{},settings:()=>store.settings()}),server=createDashboard({store,notifications,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));let browser;t.after(async()=>{await browser?.close();await notifications.stop();server.closeAllConnections();await new Promise(r=>server.close(r));notificationStore.close();await fs.rm(dir,{recursive:true,force:true});});browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(6000);const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto('http://127.0.0.1:'+server.address().port+'/#notifications');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByLabel('来源名称',{exact:true}).fill('团队业务');await page.getByRole('button',{name:'保存通知配置',exact:true}).click();await page.getByText('业务通知配置已保存。',{exact:true}).waitFor();assert.equal(notificationStore.settings().sourceName,'团队业务');await page.getByLabel('来源 JSON 样本',{exact:true}).fill(JSON.stringify({id:'SAMPLE-001',industry:'同事后续配置',brief:'原始简要说明\n第二行'}));await page.getByRole('button',{name:'预览字段映射',exact:true}).click();await page.locator('#notification-preview pre').getByText('原始简要说明\n第二行',{exact:true}).waitFor();assert.equal(notificationStore.items().length,0);assert.equal(await page.locator('#notification-preview pre').evaluate(el=>{const node=el.firstChild,index=node.textContent.indexOf('\n'),range=document.createRange();range.setStart(node,0);range.setEnd(node,1);const first=range.getBoundingClientRect().top;range.setStart(node,index+1);range.setEnd(node,index+2);return range.getBoundingClientRect().top>first;}),true);await fs.mkdir(path.resolve('output/verification'),{recursive:true});await page.evaluate(()=>window.scrollTo(0,0));await page.screenshot({path:path.resolve('output/verification/notifications-desktop.png'),fullPage:true});await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.deepEqual(errors,[]);
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs/promises');const os=require('node:os');const path=require('node:path');
|
||||
const {NotificationStore,NotificationService}=require('../src/notifications.cjs');const {MailStore}=require('../src/mail-store.cjs');const {MailService}=require('../src/mail-service.cjs');
|
||||
const {NotificationStore,NotificationService}=require('../../src/modules/notifications/notifications.cjs');const {MailStore}=require('../../src/modules/mail/store.cjs');const {MailService}=require('../../src/modules/mail/service.cjs');
|
||||
const fields={id:'flow.id',version:'flow.version',industry:'flow.industry',brief:'flow.brief',subject:'flow.subject',occurredAt:'flow.at'};
|
||||
const event={flow:{id:'FLOW-001',version:'v1',industry:'宽带',brief:'第一行原文\n第二行 <原文> & 保留',subject:'业务提醒',at:'2026-10-17T08:00:00+08:00'}};
|
||||
async function fixture(t,{uncertain=false}={}){const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-notice-'));const store=new NotificationStore(path.join(dir,'notifications'));const mailStore=new MailStore(path.join(dir,'mail'));const channel=mailStore.saveChannel({name:'工作邮箱',email:'notice@company.test',smtp:{host:'smtp.company.test',port:465,security:'tls',user:'notice',password:'Fixture-only-password'},imap:{host:'imap.company.test',port:993,security:'tls',user:'notice',password:'Fixture-only-password'},senders:['author@company.test'],enabled:false});mailStore.setState(channel.id,1,{smtp:true});const sent=[];const mail=new MailService({store:mailStore,smtpFactory:()=>({verify:async()=>{},sendMail:async payload=>{sent.push(payload);if(uncertain)throw new Error('socket disconnected');return {accepted:['interface@company.test'],rejected:[]};},close(){}})});const service=new NotificationService({store,mail,settings:()=>({schedule:{times:['09:00','17:00'],timezone:'Asia/Shanghai',weekends:true,mode:'product_line',missed:'next_window'},groups:[{productLine:'宽带',to:['interface@company.test'],cc:[]}]}),calendar:()=>[],clock:()=>new Date('2026-10-17T08:59:00+08:00')});service.saveSettings({version:1,enabled:false,sourceName:'业务流程',channelId:channel.id,fieldMap:fields,maxAttempts:3});t.after(async()=>{await service.stop();await mail.stop();store.close();mailStore.close();await fs.rm(dir,{recursive:true,force:true});});return {dir,store,service,sent,channel};}
|
||||
@@ -1,11 +1,11 @@
|
||||
const { test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const load = () => { try { return require('../extension/capture.js'); } catch(e) { if(e.code === 'MODULE_NOT_FOUND') return {}; throw e; } };
|
||||
const load = () => { try { return require('../../extension/capture.js'); } catch(e) { if(e.code === 'MODULE_NOT_FOUND') return {}; throw e; } };
|
||||
|
||||
test('capture keeps live values and names while excluding hidden secrets and actions', async () => {
|
||||
const { captureOrder } = load();
|
||||
assert.equal(typeof captureOrder, 'function', 'browser capture is not implemented');
|
||||
const { loadPlaywright, browserOptions } = require('../src/runtime.cjs');
|
||||
const { loadPlaywright, browserOptions } = require('../../src/platform/browser.cjs');
|
||||
const browser = await loadPlaywright().chromium.launch(browserOptions());
|
||||
try {
|
||||
const page = await browser.newPage();
|
||||
@@ -26,7 +26,7 @@ test('capture keeps live values and names while excluding hidden secrets and act
|
||||
|
||||
|
||||
test('capture identifies the BPM order field for each known form and rejects conflicting order IDs',async()=>{
|
||||
const {captureOrder}=load(),{loadPlaywright,browserOptions}=require('../src/runtime.cjs');const browser=await loadPlaywright().chromium.launch(browserOptions());
|
||||
const {captureOrder}=load(),{loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');const browser=await loadPlaywright().chromium.launch(browserOptions());
|
||||
try{const page=await browser.newPage();
|
||||
for(const [binding,value]of [['OFR_LSCP_Applicant.OrderNum','1234567'],['OFR_BS_Applicant.OrderNum','001234'],['OFR_KD_Applicant.OrderNum','7654321'],['OFR_WY_Applicant.OrderNum','123456']]){
|
||||
await page.setContent(`<form><label xdatabind="${binding}">${value}</label><input xdatabind="OFR_KD_Applicant.OrderNum_Original" value="999999"><input type="hidden" xdatabind="${binding}" value="888888"><div style="display:none"><input xdatabind="${binding}" value="777777"></div></form>`);
|
||||
@@ -3,7 +3,7 @@ const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs/promises');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const core = (() => { try { return require('../src/exporter.cjs'); } catch (e) { if (e.code === 'MODULE_NOT_FOUND') return {}; throw e; } })();
|
||||
const core = (() => { try { return require('../../src/modules/pdf/exporter.cjs'); } catch (e) { if (e.code === 'MODULE_NOT_FOUND') return {}; throw e; } })();
|
||||
const metadata = { order: '900001', project: 'DEMO-PROJECT-001', model: 'DEMO-MODEL', serial: 'DEMO-CHANGE-001' };
|
||||
|
||||
test('filename uses all four identifiers in the agreed order', () => {
|
||||
@@ -1,7 +1,7 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict');
|
||||
test('stop confirmation rejects timeouts, authentication errors and stale states',()=>{
|
||||
const {canConfirmStopped}=require('../src/service-control.cjs'),expected={supervisorPid:123,childInstanceId:'expected'},state={...expected,status:'stopped',childPid:null,reason:'manual_stop'};
|
||||
const {canConfirmStopped}=require('../../src/platform/service/control.cjs'),expected={supervisorPid:123,childInstanceId:'expected'},state={...expected,status:'stopped',childPid:null,reason:'manual_stop'};
|
||||
assert.equal(canConfirmStopped(Error('timeout'),state,expected),false);assert.equal(canConfirmStopped({status:403},state,expected),false);assert.equal(canConfirmStopped({code:'ECONNREFUSED'},{...state,status:'running'},expected),false);
|
||||
assert.equal(canConfirmStopped({code:'ENOENT'},{...state,childInstanceId:'another'},expected),false);assert.equal(canConfirmStopped({code:'ENOENT'},state,expected),true);
|
||||
});
|
||||
@@ -3,14 +3,14 @@ const {test}=require('node:test'),assert=require('node:assert/strict'),fs=requir
|
||||
async function port(){const s=net.createServer();await new Promise(r=>s.listen(0,'127.0.0.1',r));const p=s.address().port;await new Promise(r=>s.close(r));return p;}
|
||||
async function until(fn,timeout=15000){const end=Date.now()+timeout;while(Date.now()<end){if(await fn())return;await new Promise(r=>setTimeout(r,30));}assert.fail('condition did not become true');}
|
||||
test('external guard recovers a crashed child and a live but unresponsive child, then stops without respawning',{timeout:60000},async t=>{
|
||||
const {ServiceSupervisor}=require('../src/service-supervisor.cjs'),{requestControl,readSupervisor}=require('../src/service-control.cjs');
|
||||
const {ServiceSupervisor}=require('../../src/platform/service/supervisor.cjs'),{requestControl,readSupervisor}=require('../../src/platform/service/control.cjs');
|
||||
const stateDir=await fs.mkdtemp(path.join(os.tmpdir(),'order-guard-')),listenPort=await port(),countFile=path.join(stateDir,'count');let guard;
|
||||
t.after(async()=>{await guard?.stop();await fs.rm(stateDir,{recursive:true,force:true});});
|
||||
guard=new ServiceSupervisor({stateDir,entry:path.resolve('tests/fixtures/managed-service.cjs'),ports:[listenPort],env:{ORDER_FIXTURE_PORT:String(listenPort),ORDER_FIXTURE_COUNT:countFile},timing:{intervalMs:50,pingTimeoutMs:80,startupGraceMs:1800,failureThreshold:2,stopGraceMs:500,backoffMs:[30,50,80],cooldownMs:500,windowMs:30000,maxRestarts:8}});
|
||||
await guard.start();await until(()=>guard.snapshot().status==='running'&&guard.snapshot().restartCount>=2,30000);
|
||||
const state=guard.snapshot();assert.ok(state.childPid>0);assert.ok(state.heartbeatAt);assert.ok(Number(await fs.readFile(countFile,'utf8'))>=3);
|
||||
assert.equal(await fs.readFile(countFile+'.heartbeat','utf8')===await fs.readFile(path.join(stateDir,'supervisor','control.key'),'utf8'),false,'HTTP heartbeats must never send the management token');
|
||||
const {controlAddress}=require('../src/service-control.cjs');
|
||||
const {controlAddress}=require('../../src/platform/service/control.cjs');
|
||||
for(const value of [null,42,'text',[],true,{token:{toString:null},action:'stop'}]){
|
||||
const reply=await new Promise((resolve,reject)=>{const s=net.createConnection(controlAddress(stateDir));s.setTimeout(600,()=>{s.destroy();reject(Error('malformed control request was not rejected'));});s.on('error',reject);s.on('connect',()=>s.write(JSON.stringify(value)+'\n'));s.on('data',data=>{s.destroy();resolve(JSON.parse(data.toString('utf8')));});});assert.equal(reply.status,value&&typeof value==='object'&&!Array.isArray(value)?403:400);
|
||||
}
|
||||
@@ -23,11 +23,11 @@ test('external guard recovers a crashed child and a live but unresponsive child,
|
||||
await guard.stop();const generations=await fs.readFile(countFile,'utf8');await new Promise(r=>setTimeout(r,250));assert.equal(await fs.readFile(countFile,'utf8'),generations);assert.equal(readSupervisor(stateDir).state.status,'stopped');
|
||||
});
|
||||
test('unknown port owners remain running, and repeated real exits enter cooldown',{timeout:60000},async t=>{
|
||||
const {ServiceSupervisor}=require('../src/service-supervisor.cjs'),stateDir=await fs.mkdtemp(path.join(os.tmpdir(),'order-guard-conflict-')),listenPort=await port(),owner=net.createServer(socket=>socket.end('owner'));await new Promise(r=>owner.listen(listenPort,'127.0.0.1',r));let guard;
|
||||
const {ServiceSupervisor}=require('../../src/platform/service/supervisor.cjs'),stateDir=await fs.mkdtemp(path.join(os.tmpdir(),'order-guard-conflict-')),listenPort=await port(),owner=net.createServer(socket=>socket.end('owner'));await new Promise(r=>owner.listen(listenPort,'127.0.0.1',r));let guard;
|
||||
t.after(async()=>{await guard?.stop();if(owner.listening)await new Promise(r=>owner.close(r));await fs.rm(stateDir,{recursive:true,force:true});});
|
||||
const blocked=new ServiceSupervisor({stateDir,ports:[listenPort]});await assert.rejects(blocked.start(),e=>e.code==='EADDRINUSE');assert.equal(owner.listening,true);await new Promise(r=>owner.close(r));
|
||||
guard=new ServiceSupervisor({stateDir,entry:path.resolve('tests/fixtures/managed-service.cjs'),ports:[listenPort],env:{ORDER_FIXTURE_PORT:String(listenPort),ORDER_FIXTURE_COUNT:path.join(stateDir,'count'),ORDER_FIXTURE_ALWAYS_CRASH:'1'},timing:{intervalMs:40,pingTimeoutMs:50,startupGraceMs:1000,backoffMs:[30],maxRestarts:1,cooldownMs:1000,windowMs:30000,stopGraceMs:500}});await guard.start();await until(()=>guard.snapshot().status==='cooldown');assert.ok(guard.snapshot().nextRestartAt);await guard.stop();
|
||||
});
|
||||
test('restart backoff is bounded and repeated failures enter a cooldown',()=>{
|
||||
const {restartPlan}=require('../src/service-supervisor.cjs');assert.deepEqual([0,1,2,20].map(failures=>restartPlan({failures,recent:0}).delayMs),[2000,5000,10000,60000]);assert.equal(restartPlan({failures:9,recent:8}).cooldown,true);assert.equal(restartPlan({failures:9,recent:8}).delayMs,300000);
|
||||
const {restartPlan}=require('../../src/platform/service/supervisor.cjs');assert.deepEqual([0,1,2,20].map(failures=>restartPlan({failures,recent:0}).delayMs),[2000,5000,10000,60000]);assert.equal(restartPlan({failures:9,recent:8}).cooldown,true);assert.equal(restartPlan({failures:9,recent:8}).delayMs,300000);
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
|
||||
test('Windows login shortcut uses the current account, supports spaces and can be removed without deleting service state',{skip:process.platform!=='win32',timeout:30000},async t=>{
|
||||
const {installAutostart,uninstallAutostart,readShortcut}=require('../src/windows-startup.cjs'),root=await fs.mkdtemp(path.join(os.tmpdir(),'order startup ')),startupDir=path.join(root,'登录启动'),stateDir=path.join(root,'状态库');t.after(()=>fs.rm(root,{recursive:true,force:true}));
|
||||
const {installAutostart,uninstallAutostart,readShortcut}=require('../../src/platform/service/windows-startup.cjs'),root=await fs.mkdtemp(path.join(os.tmpdir(),'order startup ')),startupDir=path.join(root,'登录启动'),stateDir=path.join(root,'状态库');t.after(()=>fs.rm(root,{recursive:true,force:true}));
|
||||
const projectRoot=path.join(root,'项目 带空格'),marker=path.join(root,'started.txt');await fs.mkdir(path.join(projectRoot,'scripts'),{recursive:true});await fs.writeFile(path.join(projectRoot,'scripts','service.cjs'),'require("node:fs").writeFileSync('+JSON.stringify(marker)+',process.argv[2]);');
|
||||
const installed=installAutostart({stateDir,startupDir,projectRoot,nodePath:process.execPath});const shortcut=readShortcut(installed.linkPath);
|
||||
assert.match(shortcut.target,/wscript\.exe$/i);assert.ok(shortcut.args.includes(installed.launcherPath));assert.equal(installed.enabled,true);
|
||||
@@ -11,7 +11,7 @@ test('Windows login shortcut uses the current account, supports spaces and can b
|
||||
uninstallAutostart({stateDir,startupDir});await assert.rejects(fs.access(installed.linkPath));assert.ok(await fs.stat(path.join(stateDir,'supervisor','supervisor.sqlite')));
|
||||
});
|
||||
test('failed shortcut creation never reports enabled, and foreign shortcuts are preserved',{skip:process.platform!=='win32',timeout:30000},async t=>{
|
||||
const {installAutostart,uninstallAutostart}=require('../src/windows-startup.cjs'),{readSupervisor}=require('../src/service-control.cjs'),root=await fs.mkdtemp(path.join(os.tmpdir(),'order-startup-ownership-')),stateDir=path.join(root,'state'),startupDir=path.join(root,'startup');t.after(()=>fs.rm(root,{recursive:true,force:true}));
|
||||
const {installAutostart,uninstallAutostart}=require('../../src/platform/service/windows-startup.cjs'),{readSupervisor}=require('../../src/platform/service/control.cjs'),root=await fs.mkdtemp(path.join(os.tmpdir(),'order-startup-ownership-')),stateDir=path.join(root,'state'),startupDir=path.join(root,'startup');t.after(()=>fs.rm(root,{recursive:true,force:true}));
|
||||
assert.throws(()=>installAutostart({stateDir,startupDir,shortcutWriter:()=>{}}),/验证失败/);assert.equal(readSupervisor(stateDir).autostart,null);
|
||||
const record=installAutostart({stateDir,startupDir});
|
||||
const script='$d=[Console]::In.ReadToEnd()|ConvertFrom-Json; $s=(New-Object -ComObject WScript.Shell).CreateShortcut($d.file); $s.TargetPath=$d.target; $s.Arguments=""; $s.Save()';
|
||||
@@ -1,5 +1,5 @@
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict');
|
||||
const {StorageService}=require('../src/storage-service.cjs');
|
||||
const {StorageService}=require('../../src/modules/storage/service.cjs');
|
||||
test('a stalled connection check times out and releases pending state',async()=>{
|
||||
const service=new StorageService({store:{prepareServer:()=>({saved:{host:'server',share:'orders'}})},client:{area:async()=>({list:()=>new Promise(()=>{})})},checkTimeoutMs:40});
|
||||
await assert.rejects(service.checkConnection({}),e=>e.status===504);assert.equal(service.pendingChecks.size,0);await service.stop();
|
||||
@@ -18,12 +18,12 @@ test('failed Windows tree termination falls back and waits for worker closure',{
|
||||
const {EventEmitter}=require('node:events'),{PassThrough}=require('node:stream'),cp=require('node:child_process');let kills=0,closed=false;
|
||||
const child=new EventEmitter();child.pid=123;child.stdin=new PassThrough();child.stdout=new PassThrough();child.stderr=new PassThrough();child.kill=()=>{kills++;queueMicrotask(()=>{closed=true;child.emit('close',1);});};
|
||||
t.mock.method(cp,'spawn',(file)=>{if(file===process.execPath)return child;const killer=new EventEmitter();queueMicrotask(()=>killer.emit('exit',1));return killer;});
|
||||
const key=require.resolve('../src/smb-probe.cjs');delete require.cache[key];t.after(()=>delete require.cache[key]);const {probe}=require(key);
|
||||
const key=require.resolve('../../src/modules/storage/smb-probe.cjs');delete require.cache[key];t.after(()=>delete require.cache[key]);const {probe}=require(key);
|
||||
await assert.rejects(probe({host:'server'},{timeoutMs:5}),e=>e.status===504);assert.equal(kills,1);assert.equal(closed,true);
|
||||
});
|
||||
|
||||
test('share enumeration reserves enough bounded output for hundreds of Unicode names',async t=>{
|
||||
const cp=require('node:child_process'),names=Array.from({length:501},(_,i)=>'共享目录'.repeat(10)+i),payload=JSON.stringify({ok:true,shares:names});
|
||||
t.mock.method(cp,'execFile',(file,args,options,callback)=>{assert.ok(options.maxBuffer>=Buffer.byteLength(payload));return {stdin:{on(){},end(){callback(null,payload);}}};});
|
||||
const key=require.resolve('../src/smb-native.cjs');delete require.cache[key];t.after(()=>delete require.cache[key]);const {listShares}=require(key);assert.deepEqual(await listShares({host:'server',authMode:'windows'}),names);
|
||||
const key=require.resolve('../../src/modules/storage/smb-native.cjs');delete require.cache[key];t.after(()=>delete require.cache[key]);const {listShares}=require(key);assert.deepEqual(await listShares({host:'server',authMode:'windows'}),names);
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs/promises');const os=require('node:os');const path=require('node:path');
|
||||
const {Store}=require('../src/dashboard-store.cjs');const {StorageStore}=require('../src/storage-store.cjs');const {StorageService}=require('../src/storage-service.cjs');const {FileArea}=require('../src/storage-files.cjs');const {createDashboard}=require('../src/dashboard.cjs');
|
||||
const {Store}=require('../../src/modules/dashboard/store.cjs');const {StorageStore}=require('../../src/modules/storage/store.cjs');const {StorageService}=require('../../src/modules/storage/service.cjs');const {FileArea}=require('../../src/modules/storage/files.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs');
|
||||
const config={name:'210',host:'storage.company.test',share:'orders',directory:'',username:'archive',password:'Private-storage-password',enabled:true};
|
||||
async function fixture(t){const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-storage-http-'));const outputDir=path.join(dir,'pdf'),remote=path.join(dir,'remote');await fs.mkdir(outputDir);await fs.mkdir(remote);const store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');for(const role of ['operator','viewer'])store.addUser({username:role,password:'Test-password-123',role},'admin');const storageStore=new StorageStore(path.join(dir,'storage'));const storage=new StorageService({store:storageStore,jobs:store,outputDir,client:{area:async()=>new FileArea(remote),browse:async server=>server.share?{...await new FileArea(remote).list(''),serverRoot:false,readable:true,address:'shared'}:{serverRoot:true,readable:false,address:String.fromCharCode(92).repeat(2)+server.host,entries:[{name:'orders',type:'directory',address:String.fromCharCode(92).repeat(2)+server.host+String.fromCharCode(92)+'orders'}]}}});const server=createDashboard({store,storage,outputDir});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(async()=>{await storage.stop();server.closeAllConnections();await new Promise(r=>server.close(r));storageStore.close();await fs.rm(dir,{recursive:true,force:true});});const base='http://127.0.0.1:'+server.address().port;const call=(route,body,cookie,origin=base)=>fetch(base+route,{method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{'Content-Type':'application/json',Origin:origin}),...(cookie?{Cookie:cookie}:{})},body:body===undefined?undefined:JSON.stringify(body)});const login=async username=>(await call('/api/login',{username,password:'Test-password-123'})).headers.get('set-cookie').split(';')[0];return {dir,outputDir,remote,store,storage,storageStore,call,login};}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
|
||||
const {Store}=require('../src/dashboard-store.cjs'),{StorageStore}=require('../src/storage-store.cjs'),{StorageService}=require('../src/storage-service.cjs'),{FileArea}=require('../src/storage-files.cjs');
|
||||
const {Store}=require('../../src/modules/dashboard/store.cjs'),{StorageStore}=require('../../src/modules/storage/store.cjs'),{StorageService}=require('../../src/modules/storage/service.cjs'),{FileArea}=require('../../src/modules/storage/files.cjs');
|
||||
async function fixture(t){
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-group-')),remote=path.join(dir,'remote'),output=path.join(dir,'pdf');await fs.mkdir(remote);await fs.mkdir(output);
|
||||
const jobs=new Store(path.join(dir,'users')),store=new StorageStore(path.join(dir,'storage')),service=new StorageService({store,jobs,outputDir:output,client:{area:async()=>new FileArea(remote)}});
|
||||
@@ -1,5 +1,5 @@
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
|
||||
const {Store}=require('../src/dashboard-store.cjs'),{StorageStore}=require('../src/storage-store.cjs'),{StorageService}=require('../src/storage-service.cjs'),{FileArea,segments}=require('../src/storage-files.cjs'),{createDashboard}=require('../src/dashboard.cjs'),{loadPlaywright,browserOptions}=require('../src/runtime.cjs');
|
||||
const {Store}=require('../../src/modules/dashboard/store.cjs'),{StorageStore}=require('../../src/modules/storage/store.cjs'),{StorageService}=require('../../src/modules/storage/service.cjs'),{FileArea,segments}=require('../../src/modules/storage/files.cjs'),{createDashboard}=require('../../src/app/dashboard.cjs'),{loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
|
||||
test('directory picker selects shares and folders; cancel and timeout unlock the form',{timeout:150000},async t=>{
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'storage-picker-')),remote=path.join(dir,'remote');await fs.mkdir(path.join(remote,'子目录'),{recursive:true});const store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');const storageStore=new StorageStore(path.join(dir,'storage'));let aborted=0;
|
||||
const slash=String.fromCharCode(92),address=(server)=>slash.repeat(2)+server.host+(server.share?slash+[server.share,...segments(server.directory)].join(slash):'');
|
||||
@@ -1,6 +1,6 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs/promises');const os=require('node:os');const path=require('node:path');
|
||||
const {Store}=require('../src/dashboard-store.cjs');const {StorageStore}=require('../src/storage-store.cjs');const {StorageService}=require('../src/storage-service.cjs');const {FileArea}=require('../src/storage-files.cjs');const {createDashboard}=require('../src/dashboard.cjs');const {makePreviewFiles}=require('./fixtures/storage-preview-files.cjs');
|
||||
const {Store}=require('../../src/modules/dashboard/store.cjs');const {StorageStore}=require('../../src/modules/storage/store.cjs');const {StorageService}=require('../../src/modules/storage/service.cjs');const {FileArea}=require('../../src/modules/storage/files.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs');const {makePreviewFiles}=require('../fixtures/storage-preview-files.cjs');
|
||||
|
||||
async function setup(t){
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-preview-http-')),remote=path.join(dir,'remote');await fs.mkdir(remote);await makePreviewFiles(remote);
|
||||
@@ -1,6 +1,6 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs/promises');const os=require('node:os');const path=require('node:path');
|
||||
const {Store}=require('../src/dashboard-store.cjs');const {StorageStore}=require('../src/storage-store.cjs');const {StorageService}=require('../src/storage-service.cjs');const {FileArea}=require('../src/storage-files.cjs');const {createDashboard}=require('../src/dashboard.cjs');const {loadPlaywright,browserOptions}=require('../src/runtime.cjs');const {makePreviewFiles}=require('./fixtures/storage-preview-files.cjs');
|
||||
const {Store}=require('../../src/modules/dashboard/store.cjs');const {StorageStore}=require('../../src/modules/storage/store.cjs');const {StorageService}=require('../../src/modules/storage/service.cjs');const {FileArea}=require('../../src/modules/storage/files.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs');const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');const {makePreviewFiles}=require('../fixtures/storage-preview-files.cjs');
|
||||
|
||||
test('already-managed storage previews real files locally in an isolated frame',{timeout:240000},async t=>{
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'storage-preview-ui-')),remote=path.join(dir,'remote');await fs.mkdir(remote);await makePreviewFiles(remote);
|
||||
@@ -1,7 +1,7 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs/promises');const os=require('node:os');const path=require('node:path');
|
||||
const {FileArea}=require('../src/storage-files.cjs');
|
||||
const {makePreviewFiles}=require('./fixtures/storage-preview-files.cjs');
|
||||
const {FileArea}=require('../../src/modules/storage/files.cjs');
|
||||
const {makePreviewFiles}=require('../fixtures/storage-preview-files.cjs');
|
||||
async function fixture(t){const root=await fs.mkdtemp(path.join(os.tmpdir(),'order-preview-files-'));t.after(()=>fs.rm(root,{recursive:true,force:true}));await makePreviewFiles(root);return {root,area:new FileArea(root)};}
|
||||
|
||||
test('managed file metadata distinguishes local preview formats and generic downloads',async t=>{
|
||||
@@ -1,6 +1,6 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs/promises');const os=require('node:os');const path=require('node:path');
|
||||
const {Store}=require('../src/dashboard-store.cjs');const {StorageStore}=require('../src/storage-store.cjs');const {StorageService}=require('../src/storage-service.cjs');const {FileArea}=require('../src/storage-files.cjs');const {createDashboard}=require('../src/dashboard.cjs');const {loadPlaywright,browserOptions}=require('../src/runtime.cjs');
|
||||
const {Store}=require('../../src/modules/dashboard/store.cjs');const {StorageStore}=require('../../src/modules/storage/store.cjs');const {StorageService}=require('../../src/modules/storage/service.cjs');const {FileArea}=require('../../src/modules/storage/files.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs');const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
|
||||
test('storage page edits redacted credentials, checks files and archives an exported PDF', {timeout:150000}, async t=>{
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'storage-ui-')),remote=path.join(dir,'remote'),output=path.join(dir,'output');await fs.mkdir(remote);await fs.mkdir(output);const store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');await fs.writeFile(path.join(output,'order.pdf'),'%PDF-1.7\nUI test');store.recordJob({jobId:'ui-job',filename:'order.pdf',path:path.join(output,'order.pdf'),status:'success',metadata:{order:'001234'}});const storageStore=new StorageStore(path.join(dir,'storage')),storage=new StorageService({store:storageStore,jobs:store,outputDir:output,client:{area:async()=>new FileArea(remote)}}),server=createDashboard({store,storage,outputDir:output});await new Promise(r=>server.listen(0,'127.0.0.1',r));let browser;t.after(async()=>{await browser?.close();await storage.stop();server.closeAllConnections();await new Promise(r=>server.close(r));storageStore.close();await fs.rm(dir,{recursive:true,force:true});});browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(30000);const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto('http://127.0.0.1:'+server.address().port+'/#storage');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'添加服务器',exact:true}).click();
|
||||
assert.equal(await page.getByLabel('访问方式',{exact:true}).inputValue(),'windows');assert.equal(await page.getByLabel('登录账号',{exact:true}).isVisible(),false);await page.getByLabel('访问方式',{exact:true}).selectOption('credentials');
|
||||
@@ -4,8 +4,8 @@ const assert=require('node:assert/strict');
|
||||
const fs=require('node:fs/promises');
|
||||
const os=require('node:os');
|
||||
const path=require('node:path');
|
||||
const {StorageStore}=require('../src/storage-store.cjs');
|
||||
const {FileArea}=require('../src/storage-files.cjs');
|
||||
const {StorageStore}=require('../../src/modules/storage/store.cjs');
|
||||
const {FileArea}=require('../../src/modules/storage/files.cjs');
|
||||
const config={name:'210 归档',host:'storage.company.test',share:'orders',directory:'通知书',username:'DOMAIN\\archive',password:'Storage-secret-123',enabled:true};
|
||||
async function fixture(t){const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-storage-'));t.after(()=>fs.rm(dir,{recursive:true,force:true}));return dir;}
|
||||
|
||||
@@ -74,8 +74,8 @@ test('explicit passwordless account does not accidentally retain a saved passwor
|
||||
});
|
||||
|
||||
test('Windows identity mode uses UNC access without requesting a new SMB login',async t=>{
|
||||
const native=require('../src/smb-native.cjs');let calls=0;t.mock.method(native,'connect',async()=>{calls++;});
|
||||
const {SmbClient}=require('../src/storage-files.cjs'),client=new SmbClient();
|
||||
const native=require('../../src/modules/storage/smb-native.cjs');let calls=0;t.mock.method(native,'connect',async()=>{calls++;});
|
||||
const {SmbClient}=require('../../src/modules/storage/files.cjs'),client=new SmbClient();
|
||||
const area=await client.area({host:'files.example.test',share:'orders',directory:'archive',authMode:'windows'});assert.equal(calls,0);assert.equal(area.root,path.resolve(String.raw`\\files.example.test\orders\archive`));
|
||||
await client.area({...config,authMode:'credentials'});assert.equal(calls,1);
|
||||
await client.area(config);assert.equal(calls,2);
|
||||
@@ -1,5 +1,5 @@
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
|
||||
const {Store}=require('../src/dashboard-store.cjs');const {createDashboard}=require('../src/dashboard.cjs');let WorkspaceStore;try{({WorkspaceStore}=require('../src/workspace-store.cjs'));}catch(error){if(error.code!=='MODULE_NOT_FOUND')throw error;}
|
||||
const {Store}=require('../../src/modules/dashboard/store.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs');let WorkspaceStore;try{({WorkspaceStore}=require('../../src/modules/workspace/store.cjs'));}catch(error){if(error.code!=='MODULE_NOT_FOUND')throw error;}
|
||||
const http=require('node:http');
|
||||
function hostCall(base,route,host,body){return new Promise((resolve,reject)=>{const request=http.request(base+route,{method:body===undefined?'GET':'POST',headers:{Host:host,...(body===undefined?{}:{Origin:'http://'+host,'Content-Type':'application/json'})}},response=>{const chunks=[];response.on('data',chunk=>chunks.push(chunk));response.on('end',()=>resolve({status:response.statusCode,json:()=>JSON.parse(Buffer.concat(chunks).toString())}));});request.on('error',reject);request.end(body===undefined?undefined:JSON.stringify(body));});}
|
||||
async function setup(t,preview=true){assert.equal(typeof WorkspaceStore,'function','workspace ledger is missing');const dir=fs.mkdtempSync(path.join(os.tmpdir(),'workspace-http-'));const store=new Store(path.join(dir,'users'));const admin=store.bootstrap('admin','Test-password-123');store.addUser({username:'operator',password:'Test-password-123',role:'operator'},'admin');store.addUser({username:'reader',password:'Test-password-123',role:'viewer'},'admin');const workspace=new WorkspaceStore(path.join(dir,'workspace'));const server=createDashboard({store,workspace,outputDir:dir,...(preview?{previewUserId:admin.id}:{})});await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));t.after(async()=>{await new Promise(resolve=>server.close(resolve));workspace.close();fs.rmSync(dir,{recursive:true,force:true});});const base='http://127.0.0.1:'+server.address().port;const call=(route,body,cookie,origin=base,host)=>fetch(base+route,{method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{'Content-Type':'application/json',Origin:origin}),...(cookie?{Cookie:cookie}:{}),...(host?{Host:host}:{})},body:body===undefined?undefined:JSON.stringify(body)});return {store,workspace,server,base,call};}
|
||||
@@ -1,5 +1,5 @@
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
|
||||
let WorkspaceStore;try{({WorkspaceStore}=require('../src/workspace-store.cjs'));}catch(error){if(error.code!=='MODULE_NOT_FOUND')throw error;}
|
||||
let WorkspaceStore;try{({WorkspaceStore}=require('../../src/modules/workspace/store.cjs'));}catch(error){if(error.code!=='MODULE_NOT_FOUND')throw error;}
|
||||
const admin={id:'a',username:'admin',role:'admin'},alice={id:'b',username:'alice',role:'operator'},bob={id:'c',username:'bob',role:'operator'},viewer={id:'d',username:'reader',role:'viewer'};const members=[admin,alice,bob,viewer];
|
||||
function setup(t){assert.equal(typeof WorkspaceStore,'function','workspace ledger is missing');const dir=fs.mkdtempSync(path.join(os.tmpdir(),'workspace-'));let store=new WorkspaceStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});return {dir,store};}
|
||||
const exception={title:'虚构订单 PDF 缺失',component:'pdf',priority:'high',description:'示例核对事项',owner:''};
|
||||
@@ -56,7 +56,7 @@ test('ledger rejects malformed input, invalid roles, unknown owners and forged c
|
||||
assert.equal(store.disableConnection(connection.id,admin).status,'disabled');assert.ok(store.snapshot(members).audit.some(entry=>entry.action==='停用连接'));
|
||||
});
|
||||
test('calendar day overrides independently control scan and send and slots skip paused workdays',()=>{
|
||||
const {nextSlots,dayPolicy}=require('../src/schedule.cjs');assert.equal(typeof dayPolicy,'function','day policy missing');
|
||||
const {nextSlots,dayPolicy}=require('../../src/shared/schedule.cjs');assert.equal(typeof dayPolicy,'function','day policy missing');
|
||||
const schedule={times:['09:00','17:00'],weekends:false};const overrides=[{date:'2026-10-17',kind:'workday',scan:true,send:true,note:'补班'},{date:'2026-10-19',kind:'restday',scan:true,send:false,note:'只采集'}];
|
||||
assert.deepEqual(dayPolicy('2026-10-18',schedule,overrides),{scan:false,send:false,kind:'restday',note:''});assert.deepEqual(dayPolicy('2026-10-19',schedule,overrides),{scan:true,send:false,kind:'restday',note:'只采集'});
|
||||
assert.deepEqual(nextSlots(schedule,new Date('2026-10-16T10:00:00Z'),3,overrides),['2026-10-17T01:00:00.000Z','2026-10-17T09:00:00.000Z','2026-10-20T01:00:00.000Z']);
|
||||
Loaded 100 of 113 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user