import assert from 'node:assert/strict' import { readFile } from 'node:fs/promises' import test from 'node:test' import ts from '../node_modules/typescript/lib/typescript.js' import { compileScript, parse } from '../node_modules/@vue/compiler-sfc/dist/compiler-sfc.esm-browser.js' import { createSSRApp, defineComponent, h, nextTick } from '../node_modules/vue/index.mjs' import { renderToString } from '../node_modules/@vue/server-renderer/dist/server-renderer.esm-bundler.js' import { createPinia } from '../node_modules/pinia/dist/pinia.mjs' import '../node_modules/vue-router/dist/vue-router.mjs' // Execute the actual router, group store, SFC scripts and templates. Only I/O, // browser history and Element Plus presentation are replaced with isolated fixtures. const sourceRoot = new URL('../src/', import.meta.url) const vueUrl = new URL('../node_modules/vue/index.mjs', import.meta.url).href const piniaUrl = new URL('../node_modules/pinia/dist/pinia.mjs', import.meta.url).href const vueRouterUrl = new URL('../node_modules/vue-router/dist/vue-router.mjs', import.meta.url).href const iconsUrl = new URL('../node_modules/@element-plus/icons-vue/dist/index.js', import.meta.url).href const fixtureSymbol = Symbol.for('function-first-navigation-test') const fixtures = globalThis[fixtureSymbol] = {} const dataModule = (source) => `data:text/javascript;base64,${Buffer.from(source).toString('base64')}` const compile = (source) => ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 } }).outputText let sequence = 0 const company = (id, fields = {}) => ({ id, code: `company-${id}`, name: `公司${id}`, parent_id: 0, disable: 0, effective_disable: 0, is_directory_company: id === 1, structure_mode: id === 1 ? 'hospital' : 'group', permission_prefix: `company.company-${id}`, member_status: 1, can_login: 1, ...fields }) const menu = (id, fields = {}) => ({ id, pid: 20, type: 'C', name: `源菜单${id}`, paths: `/legacy/page-${id}`, component: 'system/depts', perms: 'dept.dept/lists', icon: '', sort: id, is_show: 1, disable: 0, ...fields }) const sourceMenus = () => [menu(20, { type: 'M', pid: 0, name: '原系统管理', paths: '', component: '', perms: '', children: [ menu(25, { name: '原部门入口', paths: '/legacy/departments' }), menu(26, { name: '原菜单入口', paths: '/legacy/menus', component: 'system/menus', perms: 'auth.menu/lists' }), menu(27, { name: '原账号入口', paths: '/legacy/users', component: 'system/users', perms: 'auth.admin/lists' }) ] })] const allPermissions = ['auth.dept/lists', 'dept.dept/lists', 'auth.menu/lists', 'auth.admin/lists', 'auth.dept/add', 'auth.dept/edit', 'auth.dept/delete', 'auth.menu/add', 'auth.menu/edit', 'auth.menu/delete'] async function harness({ enabled = true, permissions = allPermissions } = {}) { const key = `fixture-${++sequence}` const fixture = fixtures[key] = { calls: [], headers: [], mounted: [], errors: [], router: null, sampleRow: { id: 71, pid: 0, name: '隔离测试行', type: 'C', paths: '/fixture', perms: '', disable: 0 }, context: { group: { name: '测试集团' }, identity: { gid: 'gid_fixture', source_admin_id: 7 }, default_company_id: 1, is_group_admin: false, companies: [company(1), company(2, { is_directory_company: false }), company(3, { effective_disable: 1 }), company(4, { member_status: 0, can_login: 0 })], applications: [] }, user: { id: 7, name: '测试成员', account: 'fixture', is_root: false, role_id: [1], dept_id: [1], permissions: [...permissions], menus: sourceMenus(), data_mode: 'shared' } } const stub = (source) => dataModule(`const fixture = globalThis[Symbol.for('function-first-navigation-test')][${JSON.stringify(key)}]; ${source}`) const httpUrl = stub(` export class ApiError extends Error {} export const setCompanyContext = id => fixture.headers.push(id); export const get = async (url, params) => { fixture.calls.push({ method: 'get', url, params }); if (url === '/group/context') return fixture.context; if (url === '/auth/options') return { roles: [], depts: [], menus: [] }; return [fixture.sampleRow]; }; export const post = async (url, payload) => { fixture.calls.push({ method: 'post', url, payload }); }; export const reportError = error => { fixture.errors.push(error); }; `) const accessUrl = dataModule(compile(await readFile(new URL('services/access.ts', sourceRoot), 'utf8'))) const authUrl = stub('export const useAuthStore = () => fixture.auth;') const groupSource = await readFile(new URL('stores/group.ts', sourceRoot), 'utf8') const groupModule = await import(dataModule(compile(groupSource) .replace(/from ['"]vue['"]/g, `from '${vueUrl}'`) .replace(/from ['"]pinia['"]/g, `from '${piniaUrl}'`) .replace(/from ['"]\.\.\/services\/http['"]/g, `from '${httpUrl}'`) .replace(/from ['"]\.\.\/services\/access['"]/g, `from '${accessUrl}'`) .replace(/from ['"]\.\/auth['"]/g, `from '${authUrl}'`))) fixture.group = groupModule.useGroupStore(createPinia()) fixture.group.configure(enabled) if (enabled) await fixture.group.load() fixture.auth = { token: 'isolated-test-session', serviceInfo: { group_enabled: enabled }, get user() { return fixture.user }, get isShared() { return true }, get requiresPasswordChange() { return fixture.user?.requires_password_change === true }, get requiresWecomBinding() { return fixture.user?.requires_wecom_binding === true }, can(permission) { return fixture.user.permissions.includes('*') || fixture.user.permissions.includes(permission) }, async load() { fixture.calls.push({ method: 'get', url: '/auth.admin/mySelf' }); return fixture.user }, async loadServiceInfo() {}, clear() { fixture.user = null; fixture.group.reset() } } fixture.route = new Proxy({}, { get: (_, field) => fixture.router?.currentRoute.value[field] }) const groupUrl = stub('export const useGroupStore = () => fixture.group;') const routingUrl = stub(` export { createRouter, createMemoryHistory as createWebHistory } from '${vueRouterUrl}'; export const useRoute = () => fixture.route; export const useRouter = () => fixture.router; `) const lifecycleVueUrl = stub(`export * from '${vueUrl}'; export const onMounted = callback => fixture.mounted.push(callback);`) const uiUrl = stub('export const ElMessage = { success() {}, warning() {}, error() {} }; export const ElMessageBox = { confirm: async () => true };') const emptyComponent = dataModule('export default {};') const modules = new Map() async function resolveSource(base, specifier) { const candidate = new URL(specifier, base) if (/\.(ts|vue)$/.test(candidate.pathname)) return candidate const file = new URL(candidate.href + '.ts') try { await readFile(file); return file } catch { return new URL(candidate.href + '/index.ts') } } async function moduleUrl(url, mode = 'module', exposed = []) { const cacheKey = `${mode}:${exposed.join(',')}:${url.href}` if (modules.has(cacheKey)) return modules.get(cacheKey) const file = await readFile(url, 'utf8') let source = file if (url.pathname.endsWith('.vue')) { const { descriptor } = parse(file) source = mode === 'script' ? `${descriptor.scriptSetup.content}\nexport { ${exposed.join(', ')} };` : compileScript(descriptor, { id: key, inlineTemplate: true }).content } source = compile(source).replace(/import\(['"][^'"]+\.vue['"]\)/g, 'Promise.resolve({ default: {} })') for (const match of [...source.matchAll(/\bfrom\s+(['"])([^'"]+)\1/g)]) { const specifier = match[2] let replacement if (specifier === 'vue') replacement = mode === 'script' ? lifecycleVueUrl : vueUrl else if (specifier === 'vue-router') replacement = routingUrl else if (specifier === 'element-plus') replacement = uiUrl else if (specifier === '@element-plus/icons-vue') replacement = iconsUrl else if (specifier.startsWith('.')) { const dependency = await resolveSource(url, specifier) if (dependency.pathname.endsWith('/stores/auth.ts')) replacement = authUrl else if (dependency.pathname.endsWith('/stores/group.ts')) replacement = groupUrl else if (dependency.pathname.endsWith('/services/http.ts')) replacement = httpUrl else if (mode === 'script' && dependency.pathname.endsWith('.vue')) replacement = emptyComponent else replacement = await moduleUrl(dependency) } else throw new Error(`Unexpected fixture import: ${specifier}`) source = source.replace(match[0], `from '${replacement}'`) } const result = dataModule(`// ${key}:${mode}:${url.pathname}\n${source}`) modules.set(cacheKey, result) return result } globalThis.document ||= { title: '', querySelector: () => null } const routerModule = await import(await moduleUrl(new URL('router/index.ts', sourceRoot))) fixture.router = routerModule.default routerModule.syncDynamicRoutes(fixture.user) const loadScript = async (view, exposed = ['load', 'save', 'remove', 'formRef', 'form']) => import(await moduleUrl( new URL(view.endsWith('.vue') ? view : `views/${view}.vue`, sourceRoot), 'script', exposed )) async function renderView(view) { const component = (await import(await moduleUrl(new URL(`views/${view}.vue`, sourceRoot)))).default const app = createSSRApp(component) const file = await readFile(new URL(`views/${view}.vue`, sourceRoot), 'utf8') for (const name of new Set([...file.matchAll(/<(el-[a-z-]+)/g)].map((match) => match[1]))) { app.component(name, defineComponent({ props: ['modelValue', 'description', 'title'], setup(props, { attrs, slots }) { return () => name === 'el-dialog' && !props.modelValue ? null : h( name === 'el-button' ? 'button' : 'div', attrs, name === 'el-empty' ? props.description : slots.default?.({ row: fixture.sampleRow }) ) } })) } app.directive('loading', { getSSRProps: () => ({}) }) app.config.warnHandler = () => {} return renderToString(app) } return { fixture, module: routerModule, loadScript, renderView } } const flatten = (items) => items.flatMap((item) => [item, ...flatten(item.children || [])]) function grantCompanyStructure(fixture, ids) { const grants = ids.flatMap((companyId) => ['depts', 'menus'].map((resource, index) => menu(1_000_000_000 + companyId * 10 + index, { native: true, company_id: companyId, company_name: `公司${companyId}`, component: `system/${resource}`, perms: `company.company-${companyId}.${resource === 'depts' ? 'dept.dept' : 'auth.menu'}/lists`, paths: `/company/${companyId}/menu/${1_000_000_000 + companyId * 10 + index}` }))) fixture.user.native_menus = grants fixture.user.native_permissions = grants.map(item => item.perms) fixture.user.menus.push(...grants) } test('功能为一级,公司为直接子项,源菜单 ID/权限/路径不被导航改写', async () => { const { fixture, module } = await harness() const snapshot = structuredClone(fixture.user.menus) const navigation = module.navigationFromMenus(fixture.user.menus) for (const [title, path, sourceId, permission] of [ ['部门管理', '/system/depts', 25, 'dept.dept/lists'], ['菜单管理', '/system/menus', 26, 'auth.menu/lists'] ]) { const entry = navigation.find((item) => item.title === title) assert.ok(entry, `${title} must be a top-level item`) assert.deepEqual(entry.children.map((item) => item.title), ['公司1']) assert.equal(entry.children.every((item) => !item.children?.length), true) assert.deepEqual(entry.children.map((item) => item.path), [`${path}?company_id=1`]) const record = fixture.router.resolve(path) assert.equal(record.meta.menuId, sourceId) assert.equal(record.meta.permission, permission) } assert.equal(flatten(navigation).some((item) => item.title === '互联网医院'), false) assert.equal(navigation.some((item) => item.title === '原账号入口' && item.path === '/legacy/users'), true) assert.deepEqual(fixture.user.menus, snapshot) }) test('普通部门只读账号不会出现菜单模块,也不能通过菜单 URL 进入', async () => { const { fixture, module, renderView } = await harness({ permissions: ['auth.dept/lists', 'dept.dept/lists'] }) const navigation = module.navigationFromMenus(fixture.user.menus) assert.ok(navigation.find((item) => item.title === '部门管理')) assert.equal(navigation.some((item) => item.title === '菜单管理'), false) assert.equal(flatten(navigation).some((item) => item.path?.startsWith('/group/')), false) await fixture.router.push('/system/menus?company_id=1') assert.equal(fixture.router.currentRoute.value.name, 'forbidden') await fixture.router.push('/system/depts?company_id=1') assert.equal(fixture.router.currentRoute.value.meta.menuId, 25) assert.doesNotMatch(await renderView('Departments'), /新增部门|新增下级|>编辑<|>删除 { const { fixture, module } = await harness({ permissions: [] }) fixture.user.is_root = true fixture.user.menus = [] fixture.context.is_group_admin = true Object.assign(fixture.context.companies[1], { structure_mode: 'group', can_manage_structure: true, member_status: 0, can_login: 0 }) fixture.group.context = structuredClone(fixture.context) fixture.group.selectCompany(2) module.syncDynamicRoutes(fixture.user) const modules = module.navigationFromMenus([]).filter(item => ['部门管理', '菜单管理'].includes(item.title)) assert.equal(modules.length, 2) for (const entry of modules) assert.deepEqual(entry.children.map(item => item.title), ['公司2', '公司3', '公司4']) for (const path of ['/system/depts', '/system/menus']) { await fixture.router.push(`${path}?company_id=2`) assert.equal(fixture.router.currentRoute.value.path, path) assert.equal(fixture.router.currentRoute.value.meta.companyModule, path.endsWith('depts') ? 'departments' : 'menus') assert.equal(fixture.router.currentRoute.value.meta.menuId, undefined) assert.equal(fixture.group.directoryAvailable, false) assert.equal(fixture.group.structureAvailable, true) } await fixture.router.push('/system/users?company_id=2') assert.equal(fixture.router.currentRoute.value.name, 'forbidden') await fixture.router.push('/system/depts?company_id=1') assert.equal(fixture.router.currentRoute.value.name, 'forbidden') fixture.group.context = { ...structuredClone(fixture.context), is_group_admin: false } await fixture.router.push('/system/menus?company_id=2') assert.equal(fixture.router.currentRoute.value.name, 'forbidden') assert.equal(fixture.calls.some(call => /^\/auth\.(admin|role|dept|menu)\//.test(call.url)), false) }) test('功能重组仍尊重源读取权限、禁用祖先和仅隐藏导航的语义', async () => { const { fixture, module } = await harness() fixture.user.permissions = fixture.user.permissions.filter((permission) => permission !== 'dept.dept/lists') module.syncDynamicRoutes(fixture.user) assert.equal(module.navigationFromMenus(fixture.user.menus).some((item) => item.title === '部门管理'), false) await fixture.router.push('/system/depts?company_id=1') assert.equal(fixture.router.currentRoute.value.name, 'forbidden') fixture.user.permissions = [...allPermissions] fixture.user.menus[0].disable = 1 module.syncDynamicRoutes(fixture.user) assert.equal(module.navigationFromMenus(fixture.user.menus).some((item) => item.title === '部门管理' || item.title === '菜单管理'), false) fixture.user.menus[0].disable = 0 fixture.user.menus[0].children[0].is_show = 0 module.syncDynamicRoutes(fixture.user) assert.equal(module.navigationFromMenus(fixture.user.menus).some((item) => item.title === '部门管理'), false) await fixture.router.push('/system/depts?company_id=1') assert.equal(fixture.router.currentRoute.value.meta.menuId, 25) }) test('company_id 严格解析,显式非法或无权公司不回退,缺省按当前/默认/首公司选择', async () => { const { fixture, module } = await harness() const { companies } = fixture.context assert.equal(module.resolveCompanyId('2', companies, 1, 1), 2) for (const invalid of [null, 1, '', '0', '-1', '01', '+1', '1.0', '1e0', ' 1', '1 ', '1\n', ['1'], ['1', '2'], '9007199254740993', '999']) { assert.equal(module.resolveCompanyId(invalid, companies, 1, 1), null, JSON.stringify(invalid)) } assert.equal(module.resolveCompanyId(undefined, companies, 2, 1), 2) assert.equal(module.resolveCompanyId(undefined, companies, 999, 3), 3) assert.equal(module.resolveCompanyId(undefined, companies, null, 999), 1) assert.equal(module.resolveCompanyId(undefined, [], 1, 1), null) await fixture.router.push('/system/depts') assert.equal(fixture.router.currentRoute.value.query.company_id, '1') for (const value of ['bad', '999', '01', '1&company_id=2']) { const previousHeader = fixture.headers.at(-1) await fixture.router.push(`/system/depts?company_id=${value}`) assert.equal(fixture.router.currentRoute.value.name, 'forbidden', value) assert.equal(fixture.group.currentCompanyId, 1) assert.equal(fixture.headers.at(-1), previousHeader) } }) test('公司 URL 切换只保留角色获授页面,成员和登录资格不改变菜单,停用公司保留授权壳', async () => { const { fixture } = await harness() grantCompanyStructure(fixture, [2, 3, 4]) for (const id of [2, 3, 4, 1]) { await fixture.router.push(`/system/depts?company_id=${id}`) assert.equal(fixture.router.currentRoute.value.path, '/system/depts') assert.equal(fixture.router.currentRoute.value.meta.companyModule, 'departments') assert.equal(fixture.router.currentRoute.value.query.company_id, String(id)) assert.equal(fixture.group.currentCompanyId, id) assert.equal(fixture.headers.at(-1), id) assert.equal(fixture.group.directoryAvailable, id === 1) await fixture.router.push(`/system/menus?company_id=${id}`) assert.equal(fixture.router.currentRoute.value.meta.companyModule, 'menus') } assert.equal(fixture.calls.some((call) => /^\/auth\.(dept|menu)\//.test(call.url)), false) }) test('页内公司选择保留当前模块,并把选择同步到 URL 与公司请求头', async () => { const { fixture, loadScript } = await harness() grantCompanyStructure(fixture, [2]) const scope = await loadScript('components/CompanyScope.vue', ['switchCompany']) for (const path of ['/system/depts', '/system/menus']) { await fixture.router.push(`${path}?company_id=1&filter=retained`) await scope.switchCompany(2) assert.equal(fixture.router.currentRoute.value.path, path) assert.deepEqual(fixture.router.currentRoute.value.query, { company_id: '2', filter: 'retained' }) assert.equal(fixture.group.currentCompanyId, 2) assert.equal(fixture.headers.at(-1), 2) await scope.switchCompany(1) assert.equal(fixture.router.currentRoute.value.query.company_id, '1') assert.equal(fixture.group.directoryAvailable, true) } }) test('未获角色管理授权或停用公司不请求医院目录,不显示写入口,调用写方法也不发送请求', async () => { for (const id of [2, 3, 4]) { for (const view of ['Departments', 'Menus']) { const { fixture, loadScript, renderView } = await harness() fixture.group.selectCompany(id) const script = await loadScript(view) script.formRef.value = { validate: async () => true, clearValidate() {} } script.form.name = '隔离测试' for (const mounted of fixture.mounted) await mounted() await script.load() await script.save() await script.remove(fixture.sampleRow) await nextTick() assert.equal(fixture.calls.some((call) => /^\/auth\.(dept|menu)\//.test(call.url)), false, `${view}:${id}`) const html = await renderView(view) assert.doesNotMatch(html, /新增部门|新增菜单|新增下级|保存部门|保存菜单|>编辑<|>删除 { for (const [view, endpoint, label] of [['Departments', '/auth.dept/lists', '新增部门'], ['Menus', '/auth.menu/lists', '新增菜单']]) { const { fixture, loadScript, renderView } = await harness() const script = await loadScript(view) await script.load() assert.ok(fixture.calls.find((call) => call.url === endpoint)) assert.match(await renderView(view), new RegExp(label)) } }) test('standalone 保留源路径和源目录导航,不附加公司范围', async () => { const { fixture, module } = await harness({ enabled: false }) const navigation = module.navigationFromMenus(fixture.user.menus) assert.equal(navigation[0].title, '工作台') assert.equal(navigation.find((item) => item.title === '原系统管理')?.children[0].path, '/legacy/departments') assert.equal(flatten(navigation).some((item) => item.path?.includes('company_id')), false) await fixture.router.push('/legacy/departments') assert.equal(fixture.router.currentRoute.value.meta.menuId, 25) assert.equal(fixture.router.currentRoute.value.meta.permission, 'dept.dept/lists') assert.equal(fixture.group.currentCompanyId, null) }) const ssoApplication = (id, fields = {}) => ({ id, company_id: id === 'kefu' ? 2 : 1, name: id, entry_url: id === 'kefu' ? 'http://127.0.0.1:5666/auth/group-login' : 'http://127.0.0.1:8090/admin/group-login', ready: true, can_login: true, status_message: '', ...fields }) const authorizeRoute = (clientId) => ({ path: '/sso/authorize', force: true, query: { client_id: clientId, redirect_uri: ssoApplication(clientId).entry_url, state: 's'.repeat(43), code_challenge: 'c'.repeat(43), code_challenge_method: 'S256' } }) test('真实授权守卫允许无医院权限的客服账号,不授予医院或普通管理页面', async () => { const { fixture } = await harness({ permissions: [] }) fixture.group.context.applications = [ssoApplication('kefu'), ssoApplication('internet-hospital')] fixture.group.selectCompany(4) await fixture.router.push(authorizeRoute('kefu')) assert.equal(fixture.router.currentRoute.value.name, 'sso-authorize') assert.equal(fixture.router.currentRoute.value.query.client_id, 'kefu') assert.equal(fixture.group.currentCompanyId, 4) await fixture.router.push(authorizeRoute('internet-hospital')) assert.equal(fixture.router.currentRoute.value.name, 'forbidden') for (const path of ['/system/users', '/system/depts?company_id=1', '/group/companies']) { await fixture.router.push(path) assert.equal(fixture.router.currentRoute.value.name, 'forbidden', path) } fixture.group.context.applications = [ssoApplication('kefu'), ssoApplication('internet-hospital', { can_login: false })] await fixture.router.push(authorizeRoute('kefu')) assert.equal(fixture.router.currentRoute.value.name, 'sso-authorize') }) test('真实授权守卫保留医院资格,拒绝未知、重复和未登记客户端及不可用应用', async () => { const { fixture } = await harness() fixture.group.context.applications = [ssoApplication('kefu'), ssoApplication('internet-hospital'), ssoApplication('other')] await fixture.router.push(authorizeRoute('internet-hospital')) assert.equal(fixture.router.currentRoute.value.name, 'sso-authorize') for (const clientId of ['other', ['kefu', 'internet-hospital'], null, undefined]) { await fixture.router.push(authorizeRoute(clientId)) assert.equal(fixture.router.currentRoute.value.name, 'forbidden', JSON.stringify(clientId)) } for (const clientId of ['kefu', 'internet-hospital']) { for (const applications of [[], [ssoApplication(clientId, { ready: false })], [ssoApplication(clientId, { can_login: false })]]) { fixture.group.context.applications = applications await fixture.router.push(authorizeRoute(clientId)) assert.equal(fixture.router.currentRoute.value.name, 'forbidden', `${clientId}:${JSON.stringify(applications)}`) } } fixture.group.configure(false) await fixture.router.push(authorizeRoute('kefu')) assert.equal(fixture.router.currentRoute.value.name, 'forbidden') }) test('真实客服授权导航仍优先要求登录、首次改密和企业微信验证', async () => { const { fixture } = await harness({ permissions: [] }) fixture.group.context.applications = [ssoApplication('kefu')] fixture.auth.token = '' await fixture.router.push(authorizeRoute('kefu')) assert.equal(fixture.router.currentRoute.value.name, 'login') assert.match(fixture.router.currentRoute.value.query.redirect, /^\/sso\/authorize\?client_id=kefu&/) fixture.auth.token = 'isolated-test-session' fixture.user.requires_password_change = true fixture.user.requires_wecom_binding = true await fixture.router.push(authorizeRoute('kefu')) assert.equal(fixture.router.currentRoute.value.path, '/profile') fixture.user.requires_password_change = false await fixture.router.push(authorizeRoute('kefu')) assert.equal(fixture.router.currentRoute.value.path, '/account-required') fixture.user.requires_wecom_binding = false await fixture.router.push(authorizeRoute('kefu')) assert.equal(fixture.router.currentRoute.value.name, 'sso-authorize') })