import test from 'node:test'; import assert from 'node:assert/strict'; import { ApiClient, allows, internalUrl } from '../src/core/network.ts'; const response=(data,status=200)=>new Response(JSON.stringify(data),{status,headers:{'Content-Type':'application/json'}}); test('only private network API/update endpoints; credentials and public hosts rejected',()=>{ for(const host of ['http://10.0.0.1/api','http://172.16.2.3','https://192.168.28.10/prod-api'])assert.equal(internalUrl(host),host); for(const host of ['https://example.com','http://192.168.1.1.evil.com','http://10.1.1.999','http://user:pass@192.168.1.1','http://192.168.1.1/?key=abc','file:///a','http://127.0.0.1'])assert.throws(()=>internalUrl(host)); assert.equal(internalUrl('http://127.0.0.1:8080',true),'http://127.0.0.1:8080'); }); test('AND between permission groups, OR within groups, only backend super wildcard bypasses',()=>{ assert.equal(allows(['warehouse:stock:out'],['warehouse:stock:out'],['project:inventory:use']),false); assert.equal(allows(['*:*:*'],['warehouse:stock:out'],['project:inventory:use']),true); assert.equal(allows(['admin'],['warehouse:stock:out']),false); }); test('auth header is scoped; anonymous login/captcha do not receive token; no cross-host redirects',async()=>{ const calls=[];const api=new ApiClient('http://192.168.1.1',()=>{},async(url,options)=>{calls.push({url,options});return response({code:200});}); api.authenticate('test-only');await api.request('/getInfo');await api.request('/captchaImage',{anonymous:true,query:{name:'电机 A',empty:''}}); assert.equal(calls[0].options.headers.Authorization,'Bearer test-only');assert.equal(calls[1].options.headers.Authorization,undefined); assert.equal(calls[0].options.redirect,'error');assert.match(calls[1].url,/name=/);assert.doesNotMatch(calls[1].url,/empty=/); await assert.rejects(api.request('//evil.com'),/无效/);await assert.rejects(api.request('/a/../b'),/无效/); }); test('account switch discards an old successful response',async()=>{ let finish;const api=new ApiClient('http://192.168.1.1',()=>{},()=>new Promise(resolve=>finish=resolve));api.authenticate('a'); const pending=api.request('/getInfo');api.authenticate('b');finish(response({code:200,user:'a'})); await assert.rejects(pending,error=>error.code===409); }); test('401 clears active session; stale 401 cannot log out a new account',async()=>{ let expired=0,finish;const api=new ApiClient('http://192.168.1.1',()=>expired++,()=>new Promise(r=>finish=r)); api.authenticate('a');const old=api.request('/getInfo');api.authenticate('b');finish(response({code:401}));await assert.rejects(old,e=>e.code===409);assert.equal(expired,0); const next=api.request('/getInfo');finish(response({code:401}));await assert.rejects(next,e=>e.code===401);assert.equal(expired,1); }); test('permissions errors are gentle but never interpreted as successful data',async()=>{ const api=new ApiClient('http://192.168.1.1',()=>{},async()=>response({code:403})); await assert.rejects(api.request('/getInfo'),e=>e.code===403&&e.message.includes('管理员协助')); }); test('network failures do not automatically retry mutations',async()=>{ let calls=0;const api=new ApiClient('http://192.168.1.1',()=>{},async()=>{calls++;throw Error('offline');}); await assert.rejects(api.request('/warehouse/stock/move',{method:'POST',body:{quantity:1}}),e=>e.code===503);assert.equal(calls,1); }); test('default transport preserves the native/browser fetch receiver',async()=>{ const previous=globalThis.fetch; globalThis.fetch=async function(){assert.equal(this,globalThis);return response({code:200});}; try{await new ApiClient('http://192.168.1.1',()=>{}).request('/captchaImage',{anonymous:true});}finally{globalThis.fetch=previous;} }); test('explicit cancellation is not reported as a server business failure',async()=>{ const ctl=new AbortController();const api=new ApiClient('http://192.168.1.1',()=>{},async(_,opt)=>{ if(opt.signal.aborted)throw Error('aborted');return response({code:200});});ctl.abort(); await assert.rejects(api.request('/getInfo',{signal:ctl.signal}),e=>e.code===499); }); test('HTTP upload rejections and HTML proxy errors are not mislabeled as an offline network',async()=>{ for(const [status,expected]of [[413,'大小限制'],[504,'超时'],[500,'处理未完成']]){const api=new ApiClient('http://192.168.1.1',()=>{},async()=>new Response('proxy response',{status}));await assert.rejects(api.request('/warehouse/purchase/arrival/photos/1',{method:'POST'}),e=>e.code===status&&e.message.includes(expected)&&!e.message.includes('公司网络'));} let expired=0;const api=new ApiClient('http://192.168.1.1',()=>expired++,async()=>new Response('',{status:401}));api.authenticate('fake');await assert.rejects(api.request('/getInfo'),e=>e.code===401);assert.equal(expired,1); }); test('arrival photo preview accepts up to 20MB while other private images retain their existing limit',async()=>{ const api=new ApiClient('http://192.168.1.1',()=>{},async()=>new Response(new Uint8Array([1,2,3]),{headers:{'Content-Type':'image/jpeg','Content-Length':String(12*1024*1024)}})); await assert.rejects(api.request('/image',{responseType:'image'}),e=>e.code===413); assert.equal(await api.request('/image',{responseType:'image',imageMaxBytes:20*1024*1024}),'data:image/jpeg;base64,AQID'); }); test('an unreadable success response preserves uncertain-mutation handling without blaming the network',async()=>{ let calls=0;const api=new ApiClient('http://192.168.1.1',()=>{},async()=>{calls++;return new Response('unexpected gateway page');}); await assert.rejects(api.request('/system/feedback',{method:'POST',body:{title:'test'}}),e=>e.code===503&&e.message.includes('核对处理状态')&&!e.message.includes('公司网络'));assert.equal(calls,1); });