142 lines
7.2 KiB
JavaScript
142 lines
7.2 KiB
JavaScript
import * as elementIcons from '@element-plus/icons-vue'
|
|
import { OFFICIAL_ORIGIN } from './policy.mjs'
|
|
import { reviewedMenuKey } from './resources.mjs'
|
|
|
|
// This is presentation data, not a grant list. MenuLogic::getMenuByAdminId
|
|
// already orders each role's assigned tree by sort DESC, id ASC. Never flatten,
|
|
// re-sort by component, or infer a grant from a path, title or menu id.
|
|
const on = value => value === 1 || value === '1' || value === true
|
|
const off = value => value === 0 || value === '0' || value === false
|
|
const control = /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/u
|
|
const segment = /^[\p{L}\p{N}_-][\p{L}\p{N}_.-]*$/u
|
|
const adminBase = OFFICIAL_ORIGIN + '/admin/'
|
|
|
|
function menuIcon(value) {
|
|
if (typeof value !== 'string') return ''
|
|
if (/^local-icon-[\w-]+$/.test(value)) return value // same-document SVG fragment
|
|
// The original <icon> resolves the suffix as a Vue component; only actual
|
|
// registered icon names may use this branch (never e.g. el-icon-RouterView).
|
|
if (/^el-icon-[a-z][\w-]*$/i.test(value) && value.startsWith('el-icon-')) {
|
|
// resolveComponent tries both the supplied name and its PascalCase
|
|
// variant. Older menu rows use e.g. el-icon-arrow-down or el-icon-house.
|
|
const camel = value.slice(8).replace(/-(\w)/g, (_, c) => c.toUpperCase())
|
|
const name = camel[0].toUpperCase() + camel.slice(1)
|
|
if (Object.hasOwn(elementIcons, name)) return 'el-icon-' + name
|
|
}
|
|
return ''
|
|
}
|
|
|
|
// Keep ordinary menu defaults (the official editor accepts JSON or k=v).
|
|
// URLs are not a credential transport or a second way to issue a request.
|
|
// In particular, do not pass through redirect, tokens, blobs, arbitrary keys
|
|
// or nested objects. Business requests still have their own transport policy.
|
|
const queryKeys = new Set(('id name type tab status category channel source order_type time_type ' +
|
|
'date start_date end_date doctor_id dept_id assistant_id page page_no page_size').split(' '))
|
|
const intKey = /^(?:id|.*_id|page|page_no|page_size)$/
|
|
function menuQuery(input) {
|
|
if (typeof input !== 'string' || !input || input.length > 2048) return {}
|
|
let pairs
|
|
if (input.trimStart().startsWith('{')) {
|
|
try { pairs = Object.entries(JSON.parse(input)) } catch { return {} }
|
|
} else {
|
|
if (!input.includes('=')) return {}
|
|
pairs = new URLSearchParams(input)
|
|
}
|
|
const query = {}
|
|
for (const [key, value] of pairs) {
|
|
if (!queryKeys.has(key) || (typeof value !== 'string' && typeof value !== 'number')) continue
|
|
const str = String(value)
|
|
if (intKey.test(key) ? !/^[1-9]\d{0,14}$/.test(str) :
|
|
!/^[\p{L}\p{N} _-]{1,80}$/u.test(str)) continue
|
|
query[key] = str
|
|
}
|
|
return query
|
|
}
|
|
|
|
// Resolve relative to the authorized parent's actual route, never to a local
|
|
// alias. Only simple path segments can be joined under the fixed admin base.
|
|
// A bad path remains a visible menu node with no action; it is not repaired
|
|
// into a guessed destination. An explicit http(s) URL is always a handoff.
|
|
function destination(raw, parent) {
|
|
if (typeof raw !== 'string' || !raw || raw !== raw.trim() || raw.length > 2048 ||
|
|
raw.includes('\\') || control.test(raw)) return null
|
|
if (/^https?:\/\/[^/]/i.test(raw)) {
|
|
try {
|
|
const url = new URL(raw)
|
|
if (url.username || url.password || !url.hostname) return null
|
|
// A menu may link to a public site, but never hand off a production
|
|
// API/action URL (even a GET can initiate a business write).
|
|
if (url.hostname === new URL(OFFICIAL_ORIGIN).hostname &&
|
|
(url.origin !== OFFICIAL_ORIGIN || !/^\/admin(?:\/|$)/.test(url.pathname))) return null
|
|
const query = menuQuery(url.search)
|
|
url.search = ''
|
|
// A fragment can itself contain tokens or a second query string.
|
|
if (url.hash && !/^#[\w-]+$/.test(url.hash)) url.hash = ''
|
|
return { href: url.href, external: true, query }
|
|
} catch { return null }
|
|
}
|
|
if (!parent || parent.external || raw.includes('//')) return null
|
|
const path = raw.replace(/^\/|\/$/g, '')
|
|
if (!path || !path.split('/').every(s => segment.test(s))) return null
|
|
const href = parent.href.replace(/\/$/, '') + '/' + path.split('/').map(encodeURIComponent).join('/')
|
|
return { href, external: false }
|
|
}
|
|
|
|
function stableId(item, parentId, used) {
|
|
let base
|
|
if ((typeof item.id === 'number' || typeof item.id === 'string') && /^[1-9]\d*$/.test(String(item.id)) &&
|
|
Number.isSafeInteger(Number(item.id))) {
|
|
base = 'm-' + item.id
|
|
} else {
|
|
// Older fixtures need not have DB ids. Do not put raw upstream input in
|
|
// a local URL or make all sibling links change when one is added.
|
|
const seed = parentId + '/' + (typeof item.paths === 'string' ? item.paths : '')
|
|
let hash = 2166136261
|
|
for (let i = 0; i < seed.length; i++) hash = Math.imul(hash ^ seed.charCodeAt(i), 16777619)
|
|
base = 'p-' + (hash >>> 0).toString(36)
|
|
}
|
|
let id = base
|
|
for (let n = 2; used.has(id); n++) id = base + '-' + n
|
|
used.add(id)
|
|
return id
|
|
}
|
|
|
|
export function buildNavigation(menu, keys) {
|
|
const allowed = new Set(Array.isArray(keys) ? keys : [])
|
|
const entries = [], used = new Set(), ancestors = new Set()
|
|
|
|
function visit(rows, parent, parentId, parents) {
|
|
const nodes = []
|
|
for (const item of Array.isArray(rows) ? rows : []) {
|
|
if (!item || (item.type !== 'M' && item.type !== 'C') || ancestors.has(item) ||
|
|
!on(item.is_show) || (item.is_disable !== undefined && !off(item.is_disable))) continue
|
|
const id = stableId(item, parentId, used)
|
|
const target = destination(item.paths, parent)
|
|
const query = { ...target?.query, ...menuQuery(item.params) }
|
|
const fallback = typeof item.paths === 'string' && segment.test(item.paths) ? item.paths : id
|
|
const title = typeof item.name === 'string' && item.name.trim() && !control.test(item.name) ? item.name : fallback
|
|
const node = { id, title, icon: menuIcon(item.icon), ...(target && Object.keys(query).length ? { query } : {}) }
|
|
const breadcrumbs = [...parents, title]
|
|
ancestors.add(item)
|
|
const children = visit(item.children, target, id, breadcrumbs)
|
|
ancestors.delete(item)
|
|
if (children.length) {
|
|
node.children = children
|
|
} else {
|
|
// Official sidebar renders a folder with no visible children as
|
|
// a leaf. It is not a reviewed local component.
|
|
const candidate = target && !target.external ? reviewedMenuKey(item) : null
|
|
const liveKey = allowed.has(candidate) ? candidate : null
|
|
const url = target ? new URL(target.href) : null
|
|
if (url) url.search = new URLSearchParams(query).toString()
|
|
entries.push({ ...node, breadcrumbs, liveKey, officialHref: url?.href ?? null,
|
|
external: target?.external ?? false })
|
|
}
|
|
nodes.push(node)
|
|
}
|
|
return nodes
|
|
}
|
|
const tree = visit(menu, { href: adminBase, external: false }, '', [])
|
|
return { tree, entries, firstId: entries.find(e => e.liveKey)?.id ?? entries[0]?.id ?? null }
|
|
}
|