feat: add configurable SMB archival and notification queues
This commit is contained in:
1 parent
34770ed338
commit
c2f16a5c56
29 files changed
+809
-26
No files matched your search
@@ -0,0 +1,9 @@
|
||||
'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');
|
||||
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);
|
||||
const data={id:'external-1',industry:'待配置产业',brief:'简要说明原文\n保持换行'};const preview=await(await call('/api/notifications/preview',{data},operator)).json();assert.equal(preview.event.brief,data.brief);assert.equal(notificationStore.items().length,0);
|
||||
assert.equal((await call('/api/notifications/events',{data},viewer)).status,403);assert.equal((await call('/api/notifications/events',{data},operator)).status,201);assert.equal(notificationStore.items().length,1);
|
||||
assert.equal((await call('/api/notifications',undefined,viewer)).status,200);
|
||||
});
|
||||
@@ -0,0 +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');
|
||||
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,[]);
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
'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 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};}
|
||||
|
||||
test('mapped notifications copy brief text, deduplicate versions and send no attachments at a configured slot',async t=>{
|
||||
const {store,service,sent}=await fixture(t);const preview=service.preview(event);assert.equal(preview.event.brief,event.flow.brief);assert.equal(store.items().length,0);
|
||||
const item=service.ingest(event);assert.equal(service.ingest(event).id,item.id);assert.equal(store.items().length,1);
|
||||
assert.throws(()=>service.ingest({flow:{...event.flow,brief:'changed without version'}}),e=>e.status===409);
|
||||
service.saveSettings({...store.settings(),sourceName:'来源改名'});assert.equal(service.ingest(event).id,item.id);
|
||||
await service.tick(new Date('2026-10-17T09:00:01+08:00'));assert.equal(sent.length,0);
|
||||
const settings=store.settings();service.saveSettings({...settings,enabled:true});await service.tick(new Date('2026-10-17T09:00:01+08:00'));assert.equal(sent.length,1);
|
||||
assert.equal(sent[0].text,'第一行原文\n第二行 <原文> & 保留');assert.deepEqual(sent[0].attachments,[]);assert.deepEqual(sent[0].to,['interface@company.test']);assert.equal(store.items()[0].status,'sent');
|
||||
await service.tick(new Date('2026-10-17T09:00:20+08:00'));assert.equal(sent.length,1);
|
||||
});
|
||||
|
||||
test('unmapped industries cannot starve a later valid notification behind the queue read limit',async t=>{
|
||||
const {store,service,sent}=await fixture(t);for(let i=0;i<201;i++)service.ingest({flow:{...event.flow,id:'unmapped-'+i,industry:'尚未配置'}});
|
||||
service.ingest(event);service.saveSettings({...store.settings(),enabled:true});await service.tick(new Date('2026-10-17T09:00:00+08:00'));
|
||||
assert.equal(sent.length,1);assert.equal(sent[0].text,event.flow.brief);
|
||||
});
|
||||
|
||||
test('uncertain delivery remains blocked across restart and requires recorded human evidence to retry',async t=>{
|
||||
const {store,service,sent}=await fixture(t,{uncertain:true});service.ingest(event);service.saveSettings({...store.settings(),enabled:true});await service.tick(new Date('2026-10-17T09:00:00+08:00'));assert.equal(store.items()[0].status,'unknown');assert.equal(store.batches()[0].status,'unknown');
|
||||
await service.tick(new Date('2026-10-17T17:00:00+08:00'));assert.equal(sent.length,1);
|
||||
const unknownId=store.batches()[0].id;for(let index=0;index<101;index++){const item=service.ingest({flow:{...event.flow,id:'newer-'+index}}),batch=store.prepare([item],{industry:'宽带',to:['interface@company.test'],cc:[],text:'newer',subject:'newer'});store.mark(batch,'sent');}
|
||||
assert.equal(store.batches().some(batch=>batch.id===unknownId),true);
|
||||
assert.throws(()=>service.resolve(unknownId,{resolution:'retry',note:''},'admin'),e=>e.status===400);
|
||||
service.resolve(unknownId,{resolution:'sent',note:'已在 SMTP 服务端核实发送成功'},'admin');assert.equal(store.items()[0].status,'sent');
|
||||
});
|
||||
|
||||
test('an IMAP operation occupying the due slot does not consume the notification window',async t=>{
|
||||
const {store,service,sent}=await fixture(t);service.ingest(event);service.saveSettings({...store.settings(),enabled:true});
|
||||
let release;const occupied=service.mail.exclusive(store.settings().channelId,()=>new Promise(resolve=>{release=resolve;}));await Promise.resolve();
|
||||
await service.tick(new Date('2026-10-17T09:00:00+08:00'));assert.equal(sent.length,0);release();await occupied;
|
||||
await service.tick(new Date('2026-10-17T09:00:30+08:00'));assert.equal(sent.length,1);
|
||||
});
|
||||
|
||||
test('incomplete and unsafe field maps cannot enable delivery and unmapped industries stay visible',async t=>{
|
||||
const {store,service}=await fixture(t);assert.equal(service.preview({flow:{...event.flow,industry:'未配置产业'}}).valid,false);
|
||||
assert.throws(()=>service.ingest({flow:{...event.flow,brief:''}}),e=>e.status===400);
|
||||
assert.throws(()=>service.saveSettings({...store.settings(),fieldMap:{...fields,brief:'__proto__.secret'}}),e=>e.status===400);
|
||||
service.ingest({flow:{...event.flow,industry:'未配置产业'}});service.saveSettings({...store.settings(),enabled:true});await service.tick(new Date('2026-10-17T09:00:00+08:00'));assert.equal(store.items()[0].status,'blocked');
|
||||
});
|
||||
|
||||
test('field mapping supports Chinese object keys and rejects control characters in identity fields',async t=>{
|
||||
const {store,service}=await fixture(t);service.saveSettings({...store.settings(),fieldMap:{id:'来源.编号',version:'',industry:'来源.产业',brief:'来源.简要说明',subject:'',occurredAt:''}});
|
||||
const sample={来源:{编号:'FLOW-CN',产业:'宽带',简要说明:'中文字段原文'}};assert.equal(service.preview(sample).event.brief,'中文字段原文');
|
||||
assert.throws(()=>service.ingest({来源:{...sample.来源,编号:'bad\u0000identity'}}),e=>e.status===400);
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
'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 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)}});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};}
|
||||
|
||||
test('storage HTTP enforces roles, redacts passwords and archives only successful in-root PDFs',async t=>{
|
||||
const {dir,outputDir,store,storageStore,call,login}=await fixture(t);assert.equal((await call('/api/storage')).status,401);
|
||||
const admin=await login('admin'),operator=await login('operator'),viewer=await login('viewer');
|
||||
assert.equal((await call('/api/storage/servers',config,operator)).status,403);assert.equal((await call('/api/storage/servers',config,admin,'https://evil.test')).status,403);
|
||||
const saved=await call('/api/storage/servers',config,admin);assert.equal(saved.status,201);const server=await saved.json();assert.equal(server.password,undefined);
|
||||
assert.doesNotMatch(JSON.stringify(await(await call('/api/storage',undefined,viewer)).json()),/Private-storage/);
|
||||
assert.equal((await call(`/api/storage/servers/${server.id}/files`,undefined,viewer)).status,403);
|
||||
assert.equal((await call(`/api/storage/servers/${server.id}/check`,{},admin)).status,200);
|
||||
const overview=await(await call('/api/overview',undefined,admin)).json();assert.equal(overview.connections.find(c=>c.name==='存储服务器').ready,true);
|
||||
await fs.writeFile(path.join(outputDir,'order.pdf'),'%PDF-1.7\nHTTP document');store.recordJob({jobId:'job-1',status:'success',path:path.join(outputDir,'order.pdf'),filename:'order.pdf'});
|
||||
assert.equal((await call(`/api/storage/servers/${server.id}/archive`,{jobId:'job-1',directory:'产业A'},viewer)).status,403);
|
||||
const archived=await call(`/api/storage/servers/${server.id}/archive`,{jobId:'job-1',directory:'产业A'},operator);assert.equal(archived.status,200);assert.equal((await archived.json()).status,'success');
|
||||
assert.equal(storageStore.archives().length,1);
|
||||
const downloaded=await call(`/api/storage/servers/${server.id}/file?path=${encodeURIComponent('产业A/order.pdf')}`,undefined,operator);assert.equal(downloaded.status,200);assert.equal(await downloaded.text(),'%PDF-1.7\nHTTP document');
|
||||
store.recordJob({jobId:'outside',status:'success',path:path.join(dir,'outside.pdf'),filename:'outside.pdf'});await fs.writeFile(path.join(dir,'outside.pdf'),'%PDF-1.7\noutside');
|
||||
assert.equal((await call(`/api/storage/servers/${server.id}/archive`,{jobId:'outside',directory:''},admin)).status,400);
|
||||
});
|
||||
|
||||
test('automatic storage is opt-in, starts with new jobs and never queues mail',async t=>{
|
||||
const {outputDir,remote,store,storage,storageStore}=await fixture(t);const server=storage.saveServer(config);await fs.writeFile(path.join(outputDir,'new.pdf'),'%PDF-1.7\nnew');
|
||||
const old=store.recordJob({jobId:'old-job',status:'success',path:path.join(outputDir,'new.pdf'),filename:'new.pdf',createdAt:'2000-01-01T00:00:00Z'});
|
||||
await storage.automatic(old);assert.deepEqual(await fs.readdir(remote),[]);
|
||||
await assert.rejects(Promise.resolve().then(()=>storage.saveSettings({serverId:server.id,enabled:true})),e=>e.status===409);
|
||||
await storage.check(server.id);storage.saveSettings({serverId:server.id,enabled:true});await storage.automatic(old);assert.deepEqual(await fs.readdir(remote),[]);
|
||||
const job=store.recordJob({jobId:'new-job',status:'success',path:path.join(outputDir,'new.pdf'),filename:'new.pdf',createdAt:new Date(Date.now()+1).toISOString()});await storage.automatic(job);
|
||||
assert.deepEqual(await fs.readdir(remote),['new.pdf']);assert.equal(storageStore.archives()[0].status,'success');
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
'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');
|
||||
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'});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();
|
||||
for(const [label,value]of Object.entries({'服务器名称':'210 归档','服务器地址':'storage.company.test','共享名称':'orders','登录账号':'archive','SMB 密码':'UI-test-password'}))await page.getByLabel(label,{exact:true}).fill(value);
|
||||
const saveResponse=page.waitForResponse(r=>r.url().endsWith('/api/storage/servers')&&r.request().method()==='POST',{timeout:45000});await page.getByRole('button',{name:'保存服务器',exact:true}).click();const savedResponse=await saveResponse;assert.equal(savedResponse.status(),201,await savedResponse.text());await page.getByRole('button',{name:'检查读写',exact:true}).click();await page.getByText('共享目录读写正常',{exact:true}).waitFor();await page.getByRole('button',{name:'管理服务器',exact:true}).click();assert.equal(await page.getByLabel('SMB 密码',{exact:true}).inputValue(),'');await page.getByRole('button',{name:'取消编辑',exact:true}).click();await page.getByRole('button',{name:'浏览目录',exact:true}).click();await page.getByLabel('新目录名称',{exact:true}).fill('产业A');await page.getByRole('button',{name:'创建目录',exact:true}).click();await page.getByText('产业A',{exact:true}).waitFor();await page.getByLabel('归档 PDF',{exact:true}).selectOption('ui-job');await page.getByRole('button',{name:'归档到当前目录',exact:true}).click();await page.getByText('PDF 已归档。',{exact:true}).waitFor();assert.equal(await fs.readFile(path.join(remote,'order.pdf'),'utf8'),'%PDF-1.7\nUI test');await fs.mkdir(path.resolve('output/verification'),{recursive:true});await page.evaluate(()=>window.scrollTo(0,0));await page.screenshot({path:path.resolve('output/verification/storage-desktop.png'),fullPage:true});await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.deepEqual(errors,[]);
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
'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 {StorageStore}=require('../src/storage-store.cjs');
|
||||
const {FileArea}=require('../src/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;}
|
||||
|
||||
test('storage persists encrypted credentials, keeps blank passwords and rejects stale or changed identities',async t=>{
|
||||
let store;t.after(()=>store?.close());const dir=await fixture(t);store=new StorageStore(dir);
|
||||
const saved=store.saveServer(config);assert.equal(saved.hasPassword,true);assert.equal(saved.password,undefined);
|
||||
assert.doesNotMatch(JSON.stringify(store.servers()),/Storage-secret/);
|
||||
assert.doesNotMatch((await fs.readFile(path.join(dir,'storage.sqlite'))).toString('utf8'),/Storage-secret-123/);
|
||||
assert.equal(store.secret(saved.id).password,'Storage-secret-123');
|
||||
assert.equal(store.saveServer({...saved,password:'',name:'归档服务器'}).version,2);
|
||||
assert.throws(()=>store.saveServer({...saved,password:''}),e=>e.status===409);
|
||||
const current=store.publicServer(saved.id);
|
||||
assert.throws(()=>store.saveServer({...current,host:'other.company.test',password:''}),e=>e.status===400);
|
||||
assert.throws(()=>store.saveServer({...current,directory:'../outside',password:''}),e=>e.status===400);
|
||||
assert.throws(()=>store.saveServer({...current,share:'orders\\other',password:''}),e=>e.status===400);
|
||||
store.close();store=new StorageStore(dir);assert.equal(store.secret(saved.id).password,'Storage-secret-123');
|
||||
const record=store.beginArchive(saved.id,'job-1','admin','');assert.equal(record.status,'running');
|
||||
store.close();store=new StorageStore(dir);assert.equal(store.archives()[0].status,'interrupted');
|
||||
for(let index=0;index<101;index++)store.beginArchive(saved.id,'later-'+index,'admin','');
|
||||
assert.equal(store.finishArchive(record.id,'success',{filename:'old.pdf'}).status,'success');
|
||||
});
|
||||
|
||||
test('file area publishes real PDFs idempotently and preserves different same-name content',async t=>{
|
||||
const dir=await fixture(t),root=path.join(dir,'remote');await fs.mkdir(root);const area=new FileArea(root);
|
||||
await area.check();assert.deepEqual(await fs.readdir(root),[]);
|
||||
await area.mkdir('产业A');const file=path.join(dir,'source.pdf');await fs.writeFile(file,'%PDF-1.7\nfirst document\n%%EOF');
|
||||
const first=await area.archive(file,'订单.pdf','产业A');assert.equal(first.filename,'订单.pdf');assert.equal(first.bytes,29);
|
||||
assert.equal((await area.readPdf('产业A/订单.pdf')).bytes.toString(),'%PDF-1.7\nfirst document\n%%EOF');
|
||||
const again=await area.archive(file,'订单.pdf','产业A');assert.equal(again.relativePath,first.relativePath);
|
||||
await fs.writeFile(file,'%PDF-1.7\nsecond document\n%%EOF');
|
||||
const second=await area.archive(file,'订单.pdf','产业A');assert.notEqual(second.filename,first.filename);
|
||||
assert.equal((await fs.readdir(path.join(root,'产业A'))).length,2);
|
||||
assert.equal((await area.readPdf('产业A/订单.pdf')).bytes.toString(),'%PDF-1.7\nfirst document\n%%EOF');
|
||||
assert.deepEqual((await area.list('')).entries.map(e=>e.name),['产业A']);
|
||||
});
|
||||
|
||||
test('file area rejects parent paths, alternate streams, symlinks and non-PDF sources',async t=>{
|
||||
const dir=await fixture(t),root=path.join(dir,'remote'),outside=path.join(dir,'outside');await fs.mkdir(root);await fs.mkdir(outside);const area=new FileArea(root);
|
||||
for(const relative of ['../outside','C:\\secret','\\\\other\\share','a:stream','CON','folder./secret','a/../b'])await assert.rejects(area.list(relative),e=>e.status===400);
|
||||
await fs.symlink(outside,path.join(root,'escape'),'junction');await assert.rejects(area.mkdir('escape/nested'),e=>e.status===400);
|
||||
const file=path.join(dir,'not.pdf');await fs.writeFile(file,'not a PDF');await assert.rejects(area.archive(file,'file.pdf',''),e=>e.status===400);
|
||||
await assert.rejects(area.readPdf('not.txt'),e=>e.status===400);
|
||||
});
|
||||
|
||||
test('configured archive root cannot escape through an intermediate directory junction',async t=>{
|
||||
const dir=await fixture(t),share=path.join(dir,'share'),outside=path.join(dir,'outside');await fs.mkdir(share);await fs.mkdir(path.join(outside,'nested'),{recursive:true});await fs.symlink(outside,path.join(share,'redirect'),'junction');
|
||||
const area=new FileArea(path.join(share,'redirect','nested'),{boundary:share});
|
||||
await assert.rejects(area.list(''),e=>e.status===400);
|
||||
assert.deepEqual(await fs.readdir(path.join(outside,'nested')),[]);
|
||||
});
|
||||
Reference in new issue
Block a user