Files
zyt/admin/live-readonly/transport.test.mjs
T

169 lines
9.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// No integration credentials or network. The hardcoded production URL is inspected only in a fetch stub.
import assert from 'node:assert/strict'
import {test, beforeEach, afterEach, mock} from 'node:test'
import request, {clearSession, getSessionMeta, setAllowedResources, OFFICIAL_ORIGIN} from './transport.ts'
const memberList = '/user.user/lists', detail = '/user.user/detail', doctorList = '/auth.admin/lists', rosterList = '/doctor.roster/lists'
const dept = '/doctor.statistics/deptLists', wb = '/order.order/orderStats', orders = '/order.order/lists'
const get = (url,params) => request.get({url,params})
const login = () => request.post({url:'/login/account', params:{account:' example.test ',password:'example?name&value',terminal:1}})
const rows = lists => ({lists, count: lists.length})
const perms = ['*']
const menu = [
['workbench/index','workbench/index'],['consumer/lists/index','user.user/lists'],['consumer/lists/detail','user.user/detail'],
['order/index','order.order/lists'],['doctor/roster','doctor.roster/lists'],['doctor/dept-tongji','doctor.statistics/deptLists']
].map(([component,perms]) => ({component,perms,is_show:1,paths:'page',type:'C'}))
const keys = ['workbench','members','memberDetail','orders','roster','deptStats']
const guards = {is_paw:1, need_bind_work_wechat:false}
const identity = (permissions=perms,root=1) => ({user:{id:23,root,disable:0,name:'测试用户',private_sample:'omit',...guards},permissions,menu})
let stubs, calls
const ok = data => new Response(JSON.stringify({code:1,data}),{headers:{'Content-Type':'application/json'}})
beforeEach(() => {
clearSession()
stubs=[]; calls=[]
mock.method(globalThis,'fetch', async (url,init) => {
calls.push({url,init})
const next=stubs.shift()
if (!next) throw Error('unexpected test request')
return typeof next === 'function' ? await next() : next
})
})
afterEach(() => {clearSession();mock.restoreAll()})
async function enter(profile=identity()) {
stubs.push(ok({token:'test.local.sample',...guards}),ok(profile))
await login()
const result=await get('/auth.admin/mySelf')
setAllowedResources(keys)
return result
}
async function denyWithoutNetwork(action) {
const count=calls.length
await assert.rejects(action)
assert.equal(calls.length,count)
}
test('password is sent once via the fixed HTTPS JSON POST, never in the URL, cookie or returned data',async()=>{
stubs.push(ok({token:'test.local.sample',...guards,other:'secret-field'}))
const result=await login()
assert.deepEqual(result,{authenticated:true,...guards})
const [{url,init}]=calls
assert.equal(url,OFFICIAL_ORIGIN+'/adminapi/login/account')
assert.equal(init.method,'POST')
assert.deepEqual(JSON.parse(init.body),{account:'example.test',password:'example?name&value',terminal:1})
assert.deepEqual([init.credentials,init.cache,init.redirect,init.referrerPolicy,init.mode],['omit','no-store','error','no-referrer','cors'])
assert.equal(init.headers.token,undefined)
assert.deepEqual(getSessionMeta(),{authenticated:true})
setAllowedResources(keys)
await denyWithoutNetwork(()=>get(memberList))
stubs.push(ok(identity()))
await get('/auth.admin/mySelf')
assert.equal(calls[1].init.headers.token,'test.local.sample')
assert.equal(calls[1].init.body,undefined)
await denyWithoutNetwork(()=>get(memberList))
})
test('only projected upstream grants can be selected, plus role-sensitive auxiliary gates',async()=>{
const info=await enter(identity(['order.order/lists','order.order/todayRevenue'],0))
assert.equal(info.user.private_sample,undefined)
for (const path of [memberList,wb,dept,'/dept.dept/all','/order.order/todayRevenue','/tcm.diagnosis/getAssistants']) {
await denyWithoutNetwork(()=>get(path))
}
stubs.push(ok(rows([{id:4,patient:{patient_name:'示例',medical:'unused'},creator:{name:'测试',login_ip:'unused'},pay_qrcode:'unused'}])))
const data=await get(orders,{patient_keyword:'a & b',page_no:1,page_size:1000})
const url=new URL(calls.at(-1).url)
assert.equal(url.searchParams.get('patient_keyword'),'a & b')
assert.equal(url.searchParams.get('page_size'),'100')
assert.equal(data.lists[0].patient.patient_name,'示例')
assert.equal(JSON.stringify(data).includes('unused'),false)
setAllowedResources(['members'])
await denyWithoutNetwork(()=>get(orders))
})
test('literal read whitelist rejects alternate hosts, legacy redirects, exports, mutations, logs and invalid queries before fetch',async()=>{
await enter()
for (const path of ['https://example.invalid/order.order/lists','//example.invalid','/../order.order/lists',
'/order.order/lists?export=2','/adminapi/order.order/lists','/workbench/index','/order.order/pay','/order.order/refund',
'/order.order/syncWechatWorkBills','/order.order/detail','/order.order/export','/order.order/actionLogStats',
'/order.order/actionLogs','/tcm.diagnosis/generateMiniProgramQrcode','/login/workWechatConfig','/auth.admin/bindWorkWechat',
'/auth.admin/detail','/login/changeFirstPassword','/iam/exchange','/login/logout']) {
await denyWithoutNetwork(()=>get(path))
await denyWithoutNetwork(()=>request.post({url:path,params:{}}))
}
for (const q of [{export:1},{export:2},{token:''},{'page_size[]':'10'},{page_size:-1},{page_type:0},{page_no:0},{keyword:['x']},{channel:99}]) {
await denyWithoutNetwork(()=>get(memberList,q))
}
for (const query of [{role_id:2,exclude_disabled:1},{role_id:1},{role_id:1,exclude_disabled:1,apply_data_scope:0}]) {
await denyWithoutNetwork(()=>get(doctorList,query))
}
await denyWithoutNetwork(()=>request.post({url:'/login/account',params:{account:'x',password:'x',terminal:6}}))
})
test('detail ID must occur in this session’s bounded member list, not a caller-supplied route ID',async()=>{
await enter()
await denyWithoutNetwork(()=>get(detail,{id:10}))
stubs.push(ok(rows([{id:10}])),ok({id:10}))
await get(memberList)
assert.equal((await get(detail,{id:10})).id,10)
await denyWithoutNetwork(()=>get(detail,{id:9}))
setAllowedResources(['members'])
await denyWithoutNetwork(()=>get(detail,{id:10}))
setAllowedResources(keys)
await denyWithoutNetwork(()=>get(detail,{id:10}))
await enter()
await denyWithoutNetwork(()=>get(detail,{id:10}))
})
test('doctor dictionary is server scoped, strips IP/phones, rejects non-doctors and binds doctor-week requests',async()=>{
await enter()
const interval={start_date:'2026-05-01',end_date:'2026-05-07'}
await denyWithoutNetwork(()=>get(rosterList,{...interval,doctor_id:51}))
stubs.push(ok(rows([
{id:51,role_id:['1'],disable:0,name:'医生',dept_name:'门诊',phone:'unused'},
{id:52,role_id:[2],disable:0,name:'其他'},
{id:53,role_id:[1],disable:1}
])))
const options=await get(doctorList,{role_id:1,exclude_disabled:1,page_size:1000})
assert.equal(new URL(calls.at(-1).url).searchParams.get('apply_data_scope'),'1')
assert.deepEqual(options.lists,[{id:51,name:'医生',dept_name:'门诊'}])
for (const q of [{...interval,doctor_id:52},{...interval,doctor_id:53},{...interval},{doctor_id:51},
{...interval,doctor_id:51,end_date:'2026-05-08'},{...interval,doctor_id:51,end_date:'2026-04-30'}]) {
await denyWithoutNetwork(()=>get(rosterList,q))
}
stubs.push(ok(rows([])))
await get(rosterList,{...interval,doctor_id:51})
})
test('first-login and WeCom requirements discard tokens, including requirements discovered in mySelf',async()=>{
for(const [change,message] of [[{is_paw:'0'},/改密/],[{need_bind_work_wechat:true},/绑定/]]) {
stubs.push(ok({token:'never-used',...guards,...change}))
await assert.rejects(login,message)
assert.deepEqual(getSessionMeta(),{authenticated:false})
await denyWithoutNetwork(()=>get('/auth.admin/mySelf'))
}
const profile=identity()
profile.user.need_bind_work_wechat=1
stubs.push(ok({token:'ephemeral',...guards}),ok(profile))
await login()
await assert.rejects(()=>get('/auth.admin/mySelf'),/绑定/)
assert.deepEqual(getSessionMeta(),{authenticated:false})
await denyWithoutNetwork(()=>get('/auth.admin/mySelf'))
})
test('invalid session response resets all grants, and never propagates server error text or redirect URLs',async()=>{
await enter()
stubs.push(new Response(JSON.stringify({code:2,msg:'secret.example',data:{url:'https://example.invalid'}}),
{headers:{'content-type':'application/json'}}))
await assert.rejects(()=>get(memberList),error=>!String(error).includes('secret.example'))
for (const mode of ['expired','binding','401']) {
await enter()
stubs.push(mode==='401' ? new Response('private error',{status:401}) :
new Response(JSON.stringify({code:mode==='expired'?-1:10}),{headers:{'content-type':'application/json'}}))
await assert.rejects(()=>get(memberList),/(重新登录|企业微信绑定)/)
assert.deepEqual(getSessionMeta(),{authenticated:false})
await denyWithoutNetwork(()=>get(memberList))
}
})
test('pending response from a cleared session cannot reestablish credentials or reveal data',async()=>{
let resolve
stubs.push(()=>new Promise(r=>{resolve=r}))
const pending=login()
clearSession()
resolve(ok({token:'stale',...guards}))
await assert.rejects(pending,/会话已结束/)
assert.deepEqual(getSessionMeta(),{authenticated:false})
})