diff --git a/admin/live-readonly/Identity.vue b/admin/live-readonly/Identity.vue index a8a340505..6c0785b64 100644 --- a/admin/live-readonly/Identity.vue +++ b/admin/live-readonly/Identity.vue @@ -1,6 +1,74 @@ - + +const user = useUserStore(), + route = useRoute(), + router = useRouter() +function leave() { + user.forget() + location.replace('/admin/login') +} +async function refresh() { + const current = route.name === 'live-menu' ? String(route.params.menuId) : null + try { + await user.syncMenu() + useTabsStore().resetState() + const id = current && user.entries[current] ? current : user.firstId + await router.replace( + id + ? { + name: 'live-menu', + params: { menuId: id }, + query: user.entries[id].query || {}, + force: true + } + : { name: 'live-unavailable', force: true } + ) + ElMessage.success('已按正式账号重新加载菜单') + } catch { + await router.replace('/login') + } +} + + diff --git a/admin/live-readonly/NoAccess.vue b/admin/live-readonly/NoAccess.vue index f000d72d8..f35a09650 100644 --- a/admin/live-readonly/NoAccess.vue +++ b/admin/live-readonly/NoAccess.vue @@ -1 +1,15 @@ - + diff --git a/admin/live-readonly/OnlineBreadcrumb.vue b/admin/live-readonly/OnlineBreadcrumb.vue new file mode 100644 index 000000000..0ddf2a86c --- /dev/null +++ b/admin/live-readonly/OnlineBreadcrumb.vue @@ -0,0 +1,21 @@ + + diff --git a/admin/live-readonly/OnlinePage.vue b/admin/live-readonly/OnlinePage.vue new file mode 100644 index 000000000..41cfc49e5 --- /dev/null +++ b/admin/live-readonly/OnlinePage.vue @@ -0,0 +1,63 @@ + + + diff --git a/admin/live-readonly/README.md b/admin/live-readonly/README.md index 78ea51717..8536d8780 100644 --- a/admin/live-readonly/README.md +++ b/admin/live-readonly/README.md @@ -1,6 +1,6 @@ # 正式数据查询 · 仅本机登录 -**入口:。** 5178 是单独的合成数据预览。5179 使用本分支的真实后台登录表单、布局和业务组件;不包含演示记录、不导入原聚合快照。这里不配置 SQL,也不与本机预览服务交换密码或令牌。用户亲自在浏览器内登录,浏览器直接向 `https://admin.zhenyangtang.com.cn/adminapi/` 发 HTTPS 请求,使用服务器原账号权限。只支持本站原生账号密码;扫码/统一登录、首次改密、强制绑定等在正式站点完成。未授权的页面保持关闭。 +**入口:。** 旧书签 5178 只跳转到 5179;合成数据演示只能在显式启动的 5180 访问。5179 使用本分支的真实后台登录表单、布局和业务组件;不包含演示记录、不导入原聚合快照。这里不配置 SQL,也不与本机预览服务交换密码或令牌。用户亲自在浏览器内登录,浏览器直接向 `https://admin.zhenyangtang.com.cn/adminapi/` 发 HTTPS 请求,使用服务器原账号权限。只支持本站原生账号密码;扫码/统一登录、首次改密、强制绑定等在正式站点完成。未授权的页面保持关闭。 `server.mjs` 是只绑定 IPv4 回环的静态 HTTP 服务。它不收登录 POST,也没有后端转发;CSP 只允许所列正式查询/登录路径,不加载外部脚本。不将访问参数、账号、令牌或业务响应写日志。除了正常账号认证的 POST,适配层只允许事先审查的 GET 路径、固定参数和页数。同步账单、导出、调账、修改排班、订单详情(原接口会写查看记录)等均不开放。 @@ -15,3 +15,7 @@ node live-readonly/build.mjs && node live-readonly/server.mjs 验证(不使用真实账号):`node --test live-readonly/resources.test.mjs live-readonly/transport.test.mjs`;`browser_contract.py --chrome --out <截图目录>` 使用全新的浏览器,拦截整个正式域名并只返回测试响应。只有正式账号本人登录后,才能确认该账号实际可见的实时数据。 本机运行任务:`launchctl print gui/$(id -u)/local.zyt.live-readonly.bfc2`。退出服务:`launchctl remove local.zyt.live-readonly.bfc2`。未安装开机启动项。 + +## 左栏的数据来源 + +登录和「刷新线上菜单」均读取本次账号 `/auth.admin/mySelf` 返回的 `data.menu`。可见目录、层级、同名项、显示名称、图标与顺序由正式服务器决定;隐藏、禁用和按钮权限项不挤进侧栏。已审过的页面使用本地新版只读组件;其余真实菜单保留,点击会说明可否进入正式页面。仅用户再次明确选择才新开正式站或菜单指定的外部站点,不向目标传递本地令牌。正式站沿用其原有登录与操作权限。无返回菜单时不补演示菜单。可运行 `browser_menu_contract.py --help` 查看多层级、同名项及权限变更的离线验收。 diff --git a/admin/live-readonly/browser_menu_contract.py b/admin/live-readonly/browser_menu_contract.py new file mode 100644 index 000000000..67d799366 --- /dev/null +++ b/admin/live-readonly/browser_menu_contract.py @@ -0,0 +1,230 @@ +"""Black-box menu contract. Run against the local static build; no real network or account.""" +import argparse +import json +import re +from pathlib import Path +from urllib.parse import parse_qs, urlsplit + +from playwright.sync_api import expect, sync_playwright + +HOST = "admin.zhenyangtang.com.cn" +LOGIN = "/adminapi/login/account" +SELF = "/adminapi/auth.admin/mySelf" +ORDERS = "/adminapi/order.order/lists" +ACCOUNT, PASSWORD, TOKEN = "offline-menu-qa", "offline-only-password", "offline-only-session" +ROW, FILTERED = "OFFLINE-ROW-001", "OFFLINE-MATCH-002" + + +def node(id_, name, path, children=None, component="", perms="", **flags): + entry = dict(id=id_, name=name, paths=path, type="M" if children is not None else "C", + component=component, perms=perms, is_show=1, is_disable=0) + entry.update(flags) + if children is not None: + entry["children"] = children + return entry + + +def profile(phase): + first_group = node(91, "收费事务", "payments", [ + node(83, "对账事务", "settlement", [ + node(72, "处方收款明细", "receipts", component="order/index", perms="order.order/lists"), + node(35, "业务台账", "ledger", component="settle/ledger", perms="settle.ledger/lists"), + node(36, "隐藏的测试入口", "hidden", component="unused/index", is_show=0), + node(37, "停用的测试入口", "disabled", component="unused/index", is_disable=1), + ]), + node(18, "阶段汇总", "summary", component="settle/summary", perms="settle.summary/lists"), + node(19, "隐藏的目录", "secret", [node(20, "隐藏目录的子项", "child")], is_show=0), + ]) + second_group = node(12, "门诊事务", "clinic", [ + node(31, "业务台账", "ledger", component="clinic/ledger", perms="clinic.ledger/lists"), + # The visible menu alone is not a grant for this locally supported screen. + node(40, "就诊人资料", "people", component="consumer/lists/index", perms="user.user/lists"), + node(32, "操作按钮", "edit", type="A", perms="clinic.ledger/edit"), + ]) + menus = {"initial": [first_group, second_group], "empty": [], "clinic": [second_group]} + grants = {"initial": ["order.order/lists", "settle.ledger/lists", "settle.summary/lists", + "clinic.ledger/lists", "clinic.ledger/edit"], + "empty": [], "clinic": ["clinic.ledger/lists"]} + return {"user": {"id":991, "name":"菜单验收角色", "disable":0, "is_paw":1, + "need_bind_work_wechat":False, "root":0}, + "permissions":grants[phase], "menu":menus[phase]} + + +class Offline: + def __init__(self, base): + self.base = base + self.phase = "initial" + self.calls = [] + self.bad = [] + self.documents = [] + self.explicit = False + + def route(self, route): + req = route.request + url = urlsplit(req.url) + key = (req.method, url.path) + + def deny(reason): + self.bad.append((reason, *key)) + route.abort() + + if (url.scheme, url.netloc) == ("http", urlsplit(self.base).netloc): + if req.method == "GET" and (url.path.startswith("/admin/assets/") or + (req.resource_type == "document" and url.path.startswith("/admin/"))): + return route.continue_() + return deny("unexpected local request") + if (url.scheme, url.netloc) != ("https", HOST): + return deny("non-fixture origin") + if req.resource_type == "document": + if (not self.explicit or req.method != "GET" or url.path.startswith("/adminapi") or + any(s in req.url for s in (ACCOUNT, PASSWORD, TOKEN)) or + any(req.headers.get(h) for h in ("cookie", "token", "authorization"))): + return deny("unexpected official navigation") + self.documents.append(url.path) + return route.fulfill(content_type="text/html", body="Offline official-site fixture") + if url.path not in (LOGIN, SELF, ORDERS): + return deny("non-fixture API") + cors = {"Access-Control-Allow-Origin":self.base, "Access-Control-Allow-Methods":"GET,POST,OPTIONS", + "Access-Control-Allow-Headers":"token,version,content-type,accept", "Cache-Control":"no-store"} + if req.method == "OPTIONS": + return route.fulfill(status=204, headers=cors) + self.calls.append(key) + if req.headers.get("cookie"): + return deny("unexpected cookie") + if key == ("POST", LOGIN): + if req.post_data_json != {"account":ACCOUNT, "password":PASSWORD, "terminal":1}: + return deny("unexpected sign-in payload") + data = {"token":TOKEN, "is_paw":1, "need_bind_work_wechat":False} + elif req.headers.get("token") != TOKEN: + return deny("missing fixture token") + elif key == ("GET", SELF): + data = profile(self.phase) + elif key == ("GET", ORDERS) and self.phase == "initial": + number = FILTERED if parse_qs(url.query).get("order_no") == [FILTERED] else ROW + data = {"lists":[{"id":111, "order_no":number, "order_type":1, "status":2, "amount":"2.00", + "is_exempt":0, "creator":{"name":"演示"}, "prescription_orders":[]}], + "count":1, "extend":{}} + else: + return deny("method or permission mismatch") + route.fulfill(headers=cors, json={"code":1, "show":0, "msg":"", "data":data}) + + +def exact(label): + return re.compile("^" + re.escape(label) + "$") + + +def open_group(parent, name): + title = parent.locator(".el-sub-menu__title").filter(has_text=exact(name)) + expect(title).to_be_visible() + group = title.locator("..") + if "is-opened" not in (group.get_attribute("class") or "").split(): + title.click() + expect(group).to_have_class(re.compile(r"\bis-opened\b")) + return group + + +def visit(page, parent, name, base, id_): + item = parent.locator(".el-menu-item").filter(has_text=exact(name)) + item.click() + expect(page).to_have_url(re.compile("^" + re.escape(f"{base}/admin/nav/m-{id_}") + r"(?:\?|$)")) + + +def check(pw, args): + base = f"http://127.0.0.1:{args.port}" + mock, errors = Offline(base), [] + with pw.chromium.launch(executable_path=args.chrome, args=[ + "--disable-background-networking", "--disable-quic", "--no-proxy-server", + "--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1", + ]) as browser: + context = browser.new_context(service_workers="block", viewport={"width":1440,"height":950}) + context.route("**/*", mock.route) + context.route_web_socket("**/*", lambda socket: (mock.bad.append(("websocket",)), socket.close())) + context.on("page", lambda p: p.on("pageerror", lambda error: errors.append(str(error)))) + page = context.new_page() + page.goto(base + "/admin/login") + page.get_by_placeholder("请输入账号").fill(ACCOUNT) + page.get_by_placeholder("请输入密码").fill(PASSWORD) + assert not mock.calls, mock.calls + page.get_by_role("button", name="登录", exact=True).click() + + menu = page.locator(".menu:visible") + refresh = page.locator("[data-refresh-online-menu]:visible") + roots = menu.locator(".el-menu").first + expect(roots.locator(":scope > .el-sub-menu > .el-sub-menu__title")).to_have_text(["收费事务","门诊事务"]) + finance = open_group(menu, "收费事务") + settlement = open_group(finance, "对账事务") + expect(finance.locator(".el-sub-menu__title, .el-menu-item")).to_have_text( + ["收费事务","对账事务","处方收款明细","业务台账","阶段汇总"]) + visit(page, settlement, "处方收款明细", base, 72) + table = page.locator("main .el-table") + expect(table.get_by_text(ROW, exact=True)).to_be_visible() + page.get_by_placeholder("请输入订单号").fill(FILTERED) + page.get_by_role("button", name="查询", exact=True).click() + expect(table.get_by_text(FILTERED, exact=True)).to_be_visible() + expect(table.get_by_text(ROW, exact=True)).to_have_count(0) + page.screenshot(path=str(args.out/"menu-orders.png")) + + calls = list(mock.calls) + visit(page, settlement, "业务台账", base, 35) + main = page.locator("main") + expect(main.get_by_text("业务台账", exact=True)).to_be_visible() + expect(main).to_contain_text("正式后台") + clinic = open_group(menu, "门诊事务") + expect(clinic.locator(".el-menu-item")).to_have_text(["业务台账","就诊人资料"]) + visit(page, clinic, "就诊人资料", base, 40) + expect(main).to_contain_text("正式后台") + expect(main.locator(".el-table")).to_have_count(0) + visit(page, clinic, "业务台账", base, 31) + expect(main.get_by_text("业务台账", exact=True)).to_be_visible() + expect(main).to_contain_text("正式后台") + page.wait_for_load_state("networkidle") + assert mock.calls == calls and not mock.documents, (mock.calls, mock.documents) + page.screenshot(path=str(args.out/"menu-official-only.png")) + + # Revoke while the real local table is mounted: old rows and navigation must disappear. + settlement = open_group(open_group(menu, "收费事务"), "对账事务") + visit(page, settlement, "处方收款明细", base, 72) + expect(table).to_be_visible() + page.wait_for_load_state("networkidle") + before = list(mock.calls) + mock.phase = "empty" + refresh.click() + expect(menu.locator(".el-menu-item, .el-sub-menu__title")).to_have_count(0) + expect(main.locator(".el-table")).to_have_count(0) + expect(main).not_to_contain_text("OFFLINE-") + page.wait_for_load_state("networkidle") + assert mock.calls[len(before):] == [("GET", SELF)], mock.calls + page.screenshot(path=str(args.out/"menu-empty.png")) + + # Same session receives a new, unadapted-only tree; never silently open the official site. + mock.phase = "clinic" + refresh.click() + clinic = open_group(menu, "门诊事务") + visit(page, clinic, "业务台账", base, 31) + expect(menu.locator(".el-sub-menu__title")).to_have_text(["门诊事务"]) + expect(main).to_contain_text("正式后台") + page.wait_for_load_state("networkidle") + assert mock.calls[len(before):] == [("GET", SELF), ("GET", SELF)] and not mock.documents + link = main.get_by_role("link", name=re.compile("正式后台")).or_( + main.get_by_role("button", name=re.compile("正式后台"))) + expect(link).to_be_visible() + mock.explicit = True + with context.expect_event("requestfinished", predicate=lambda r: + urlsplit(r.url).netloc == HOST and r.resource_type == "document"): + link.click() + assert mock.documents == ["/admin/clinic/ledger"], mock.documents + assert mock.calls[len(before):] == [("GET", SELF), ("GET", SELF)] and not mock.bad and not errors, ( + mock.calls, mock.bad, errors) + return {"offline_menu_contract":"PASS", "intercepted_api_calls":mock.calls, + "intercepted_official_navigation":mock.documents, "unexpected":mock.bad, "page_errors":errors} + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--chrome", required=True) + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--port", type=int, default=5179) + args = parser.parse_args() + args.out.mkdir(parents=True, exist_ok=True) + with sync_playwright() as pw: + print(json.dumps(check(pw, args), ensure_ascii=False)) diff --git a/admin/live-readonly/build.mjs b/admin/live-readonly/build.mjs index 9b8652c0b..34189d30a 100644 --- a/admin/live-readonly/build.mjs +++ b/admin/live-readonly/build.mjs @@ -17,7 +17,7 @@ await mkdir(outDir, {recursive:true}) await build({ root, mode:'live-readonly', configFile:false, envFile:false, envPrefix:'ZYT_LOCAL_NO_EXPOSE_', publicDir:false, base:'/admin/', cacheDir:path.join(root,'node_modules/.zyt-live-read/cache'), define:{'import.meta.env.VITE_APP_BASE_URL':JSON.stringify('')}, - resolve:{alias:[{find:/^@\/utils\/request(?:\/index)?$/,replacement:path.join(here,'transport.ts')},{find:/^@\/stores\/modules\/user$/,replacement:path.join(here,'user.ts')},{find:/^@\/router$/,replacement:path.join(here,'router.ts')},{find:/^\.\/user-drop-down\.vue$/,replacement:path.join(here,'Identity.vue')},{find:'@',replacement:path.join(root,'src')}]}, + resolve:{alias:[{find:/^@\/utils\/request(?:\/index)?$/,replacement:path.join(here,'transport.ts')},{find:/^@\/stores\/modules\/user$/,replacement:path.join(here,'user.ts')},{find:/^@\/router$/,replacement:path.join(here,'router.ts')},{find:/^\.\/breadcrumb\.vue$/,replacement:path.join(here,'OnlineBreadcrumb.vue')},{find:/^\.\/user-drop-down\.vue$/,replacement:path.join(here,'Identity.vue')},{find:'@',replacement:path.join(root,'src')}]}, plugins:[vue(),vueJsx(),createSvgIconsPlugin({iconDirs:[path.join(root,'src/assets/icons')],symbolId:'local-icon-[dir]-[name]'}),AutoImport({imports:['vue','vue-router'],resolvers:[ElementPlusResolver({importStyle:false})],dts:false}),Components({dirs:[path.join(root,'src/components')],directoryAsNamespace:true,dts:false}),vueSetupExtend()], build:{outDir,emptyOutDir:true,sourcemap:false,reportCompressedSize:false,rollupOptions:{input:path.join(here,'index.html')}}, css:{preprocessorOptions:{scss:{api:'modern-compiler'}}} diff --git a/admin/live-readonly/navigation.mjs b/admin/live-readonly/navigation.mjs new file mode 100644 index 000000000..1a4db5507 --- /dev/null +++ b/admin/live-readonly/navigation.mjs @@ -0,0 +1,141 @@ +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 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 } +} diff --git a/admin/live-readonly/navigation.test.mjs b/admin/live-readonly/navigation.test.mjs new file mode 100644 index 000000000..4a9186bf3 --- /dev/null +++ b/admin/live-readonly/navigation.test.mjs @@ -0,0 +1,139 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { buildNavigation } from './navigation.mjs' +import { projectResources } from './resources.mjs' +import { OFFICIAL_ORIGIN } from './policy.mjs' + +const base = OFFICIAL_ORIGIN + '/admin/' +const leaf = (id, name, paths, more = {}) => ({ type: 'C', id, name, paths, + component: 'order/index', perms: 'order.order/lists', is_show: 1, is_disable: 0, ...more }) +const group = (id, name, paths, children, more) => ({ ...leaf(id, name, paths), type: 'M', children, ...more }) +const shape = tree => tree.map(node => [node.id, node.title, node.children ? shape(node.children) : null]) + +test('preserves server order, real titles/icons, nested and duplicate menu placements independent of live support', () => { + const menu = [ + group(100, '诊疗管理', '/clinics/', [ + leaf(200, '随访', '/follow/up/', { component: 'other/follow', perms: 'other.follow/lists', sort: 30 }), + group(101, '组内管理', 'team', [leaf(9, '台账', 'bills', { icon: 'local-icon-qianbao' })]) + ], { icon: 'el-icon-Lock' }), + group(20, '运营管理', 'ops', [ + leaf(8, '台账', 'order', { icon: 'el-icon-Tickets' }), + leaf(7, '订单回访', 'revisit', { component: '/order/index/' }) + ], { sort: 999 }) + ] + const { tree, entries, firstId } = buildNavigation(menu, ['orders']) + assert.deepEqual(shape(tree), [ + ['m-100', '诊疗管理', [['m-200', '随访', null], ['m-101', '组内管理', [['m-9', '台账', null]]]]], + ['m-20', '运营管理', [['m-8', '台账', null], ['m-7', '订单回访', null]]] + ]) + assert.deepEqual(entries.map(e => [e.id, e.liveKey, e.officialHref]), [ + ['m-200', null, base + 'clinics/follow/up'], ['m-9', 'orders', base + 'clinics/team/bills'], + ['m-8', 'orders', base + 'ops/order'], ['m-7', 'orders', base + 'ops/revisit'] + ]) + assert.equal(firstId, 'm-9') + assert.deepEqual(entries[1].breadcrumbs, ['诊疗管理', '组内管理', '台账']) + assert.equal(tree[0].icon, 'el-icon-Lock') + assert.equal(entries[1].icon, 'local-icon-qianbao') + assert.equal(entries[2].icon, 'el-icon-Tickets') +}) + +test('prunes whole disabled/hidden/button branches; menu with visible children is a group; empty visible directory remains', () => { + const m = leaf(1, '订单', 'order') + const menu = [ + group(4, '隐藏', 'hide', [m], { is_show: '0' }), group(5, '停用', 'stop', [m], { is_disable: '1' }), + group(6, '按钮', 'action', [m], { type: 'A' }), + leaf(7, '目录页面', 'page', { children: [leaf(8, '订单查询', 'orders', { is_show: '1', is_disable: '0' })] }), + group(9, '权限管理', 'acl', [leaf(10, '不可见', 'hidden', { is_show: false })]), + leaf(11, '禁用', 'notHere', { is_disable: true }), leaf(12, '隐藏', 'hidden', { is_show: 0 }) + ] + const { tree, entries } = buildNavigation(menu, ['orders']) + assert.deepEqual(shape(tree), [['m-7', '目录页面', [['m-8', '订单查询', null]]], ['m-9', '权限管理', null]]) + assert.deepEqual(entries.map(e => [e.id, e.liveKey]), [['m-8', 'orders'], ['m-9', null]]) + assert.equal(entries[1].officialHref, base + 'acl') +}) + +test('navigation never expands keys; exact component, per-instance permission and authorized key all required', () => { + const m = leaf(1, '订单', 'order') + const menu = [m, { ...m, id: 2, perms: 'order.order/edit' }, { ...m, id: 3, component: 'alt/order/index' }, + { ...m, id: 4, component: 'https://example.invalid/file.vue' }, + { ...m, id: 5, paths: 'https://example.invalid/order' }] + const self = { user: { id: 64 }, menu, permissions: ['order.order/lists'] } + const { keys } = projectResources(self) + assert.deepEqual(keys, ['orders']) + assert.deepEqual(buildNavigation(menu, keys).entries.map(x => x.liveKey), ['orders', null, null, null, null]) + for (const keys of [[], ['*'], ['ORDER'], undefined]) { + const n = buildNavigation(menu, keys) + assert.deepEqual(n.entries.map(x => x.liveKey), [null, null, null, null, null]) + assert.equal(n.firstId, 'm-1') + } + assert.ok(!JSON.stringify(buildNavigation(menu, keys)).includes('file.vue')) +}) + +test('safe dedicated params field accepts both official syntaxes without passing redirects/credentials/second queries', () => { + const menu = [ + leaf(1, '订单一', '/order', { params: '{"id":42,"type":"分类","name":"张 三","token":"SECRET","redirect":"https://evil.invalid"}' }), + leaf(2, '订单二', 'other', { params: 'tab=pending&next=evil&password=SECRET&status=1&__proto__=x&date=2026-12-01' }), + leaf(3, '详情', 'detail', { params: '{"id":"-1","name":{},"type":"//evil.invalid","token":"SECRET"}' }), + leaf(4, '异常', 'bad', { params: '{"tab":' }), + leaf(5, '双重编码', 'polluted', { params: 'tab=ok%26token%3DSECRET&type=%252f%252fother.invalid' }) + ] + const n = buildNavigation(menu, ['orders']) + assert.deepEqual(n.entries[0].query, { id: '42', type: '分类', name: '张 三' }) + assert.deepEqual(n.tree[0].query, n.entries[0].query) + const directory = buildNavigation([group(900, '目录', 'dir', [menu[0]], { params: 'tab=all&token=SECRET' })], []) + assert.deepEqual(directory.tree[0].query, { tab: 'all' }) + assert.deepEqual(directory.tree[0].children[0].query, n.entries[0].query) + assert.deepEqual(Object.fromEntries(new URL(n.entries[0].officialHref).searchParams), n.entries[0].query) + assert.deepEqual(n.entries[1].query, { tab: 'pending', status: '1', date: '2026-12-01' }) + assert.equal(n.entries[2].officialHref, base + 'detail') + assert.equal(n.entries[3].query, undefined) + assert.equal(n.entries[4].query, undefined) + assert.ok(!JSON.stringify(n).includes('SECRET')) +}) + +test('invalid paths remain visible but inert, including descendants; explicit web links are distinct from local screens', () => { + const paths = ['../x', '%2e%2e/x', '/x//else', 'javascript:alert(1)', 'data:text/html,body', + 'file:///tmp/none', 'mailto:name@example.invalid', '//elsewhere.invalid/path', 'https:///bad.example', + 'https://user:secret@example.invalid', '\\evil', 'x?next=z', 'x#section', '\u0000path', '/%2felse'] + const bad = paths.map((p, i) => leaf(i + 20, '未开放', p)) + const menu = [...bad, group(1, '无效父', '../unsafe', [leaf(2, '子菜单', 'order')]), + leaf(3, '说明', 'https://docs.example.invalid/start?tab=first&token=SECRET#info'), + leaf(4, '帮助', 'http://docs.example.invalid/help', { params: 'type=admin' })] + const n = buildNavigation(menu, ['orders']) + assert.equal(n.entries.length, bad.length + 3) + for (const e of n.entries.slice(0, -2)) { + assert.equal(e.officialHref, null); assert.equal(e.liveKey, null) + } + assert.deepEqual(n.entries.slice(-2).map(x => [x.external, x.officialHref, x.liveKey]), [ + [true, 'https://docs.example.invalid/start?tab=first#info', null], + [true, 'http://docs.example.invalid/help?type=admin', null] + ]) + assert.ok(!JSON.stringify(n).includes('SECRET')) +}) + +test('DB ids stable across reordering, missing ids path-derived, repeated paths distinct, empty inputs deterministic', () => { + const some = [leaf(null, '', 'first'), leaf('5', '二', 'second'), leaf(null, '三', 'third')] + const ids = rows => new Map(buildNavigation(rows, []).entries.map(e => [e.title, e.id])) + assert.deepEqual(ids(some), ids(some.toReversed())) + assert.match(ids(some).get('first'), /^p-[a-z0-9]+$/) + assert.equal(ids(some).get('二'), 'm-5') + const duplicated = [some[1], some[1], some[0], some[0]] + const e = buildNavigation(duplicated, []).entries + assert.equal(new Set(e.map(x => x.id)).size, 4) + for (const menu of [undefined, {}, [], [null, { type: 'A' }]]) { + assert.deepEqual(buildNavigation(menu, []), { tree: [], entries: [], firstId: null }) + } +}) + +test('only registered Element icons or local SVG fragments reach the production dynamic icon component', () => { + const icons = ['el-icon-RouterView', 'el-icon-Iframe', 'local-icon-x#url', 'https://example.invalid/art.svg', + 'el-icon-User', 'local-icon-set_pay', 'el-icon-house', 'el-icon-arrow-down', 'el-icon-arrowDown'] + assert.deepEqual(buildNavigation(icons.map((icon, i) => leaf(i + 1, '名称', 'icon', { icon })), []).entries.map(e => e.icon), + ['', '', '', '', 'el-icon-User', 'local-icon-set_pay', 'el-icon-House', 'el-icon-ArrowDown', 'el-icon-ArrowDown']) +}) + + +test('an upstream absolute API action remains visible but never becomes a clickable handoff', () => { + const {entries}=buildNavigation([leaf(37,'同步配置',OFFICIAL_ORIGIN+'/adminapi/operation/run')],['orders']) + assert.equal(entries[0].title,'同步配置');assert.equal(entries[0].officialHref,null);assert.equal(entries[0].liveKey,null) +}) diff --git a/admin/live-readonly/resources.mjs b/admin/live-readonly/resources.mjs index a0ceb2ae8..52e820254 100644 --- a/admin/live-readonly/resources.mjs +++ b/admin/live-readonly/resources.mjs @@ -13,6 +13,13 @@ const pages = [ requires: ['dept.dept/all'], rootOnly: true } ] const byComponent = new Map(pages.map(page => [page.component, page])) +// A rendering match is not a permission grant: callers must also intersect the +// result with the independently authorized resource keys from mySelf. +export function reviewedMenuKey(item) { + if (item?.type !== 'C' || typeof item.component !== 'string') return null + const page = byComponent.get(item.component.replace(/^\/+|\/+$/g, '')) + return page && item.perms === page.permission ? page.key : null +} const on = value => value === true || value === 1 || value === '1' const off = value => value === false || value === 0 || value === '0' const validId = value => (typeof value === 'number' || typeof value === 'string') && diff --git a/admin/live-readonly/router.ts b/admin/live-readonly/router.ts index 8d0d04cc5..c9e4d6e71 100644 --- a/admin/live-readonly/router.ts +++ b/admin/live-readonly/router.ts @@ -1,18 +1,87 @@ -import {createRouter,createWebHistory} from 'vue-router' +import { createRouter, createWebHistory } from 'vue-router' import Layout from '@/layout/default/index.vue' import useUserStore from './user' -import {routes} from './screens' -const router=createRouter({history:createWebHistory('/admin/'),routes:[ - {path:'/login',component:()=>import('@/views/account/login.vue')}, - {path:'/',component:Layout,children:[{path:'',name:'live-home',component:()=>import('./NoAccess.vue')},...routes,{path:'/unavailable',name:'live-unavailable',component:()=>import('./NoAccess.vue')}]}, - {path:'/:pathMatch(.*)*',redirect:'/'}]}) -router.beforeEach(to=>{ - const user=useUserStore() - if(to.path==='/login')return user.ready?'/':true - if(!user.ready)return '/login' - if(to.path==='/')return user.routes[0]?.path || '/unavailable' - if(to.meta.key && !user.keys.includes(String(to.meta.key)))return '/unavailable' - return true +import { screens } from './screens' + +const router = createRouter({ + history: createWebHistory('/admin/'), + routes: [ + { path: '/login', component: () => import('@/views/account/login.vue') }, + { + path: '/', + component: Layout, + children: [ + { + path: '', + name: 'live-home', + component: () => import('./NoAccess.vue'), + meta: { hideTab: true } + }, + { + path: '/nav/:menuId', + name: 'live-menu', + component: () => import('./OnlinePage.vue') + }, + // Keep the reviewed hidden drill-down separate from the visible menu. + { + path: '/members/detail', + name: 'live-member-detail', + component: () => import('@/views/consumer/lists/detail.vue'), + meta: { title: '用户详情', key: 'memberDetail' } + }, + ...screens + .filter((s) => !s.hidden) + .map((s) => ({ + path: s.path, + redirect: () => { + const e = Object.values(useUserStore().entries).find( + (e) => e.liveKey === s.key + ) + return e + ? { + name: 'live-menu', + params: { menuId: e.id }, + query: e.query || {} + } + : '/unavailable' + } + })), + { + path: '/unavailable', + name: 'live-unavailable', + component: () => import('./NoAccess.vue'), + meta: { hideTab: true } + } + ] + }, + { path: '/:notfound(.*)*', redirect: '/' } + ] }) -export const getRoutePath=(perm:string)=>perm==='user.user/detail' && useUserStore().keys.includes('memberDetail')?'/members/detail':'' +router.beforeEach((to) => { + const user = useUserStore() + if (to.path === '/login') return user.ready ? '/' : true + if (!user.ready) return '/login' + if (to.name === 'live-home') { + const first = user.firstId && user.entries[user.firstId] + return first + ? { name: 'live-menu', params: { menuId: first.id }, query: first.query || {} } + : '/unavailable' + } + if (to.name === 'live-menu') { + const id = String(to.params.menuId) + if (!Object.hasOwn(user.entries, id)) return '/unavailable' + const e = user.entries[id] + to.meta.title = e.title + to.meta.activeMenu = `/nav/${e.id}` + } else if (to.meta.key) { + if (!user.keys.includes(String(to.meta.key))) return '/unavailable' + const parent = Object.values(user.entries).find((e) => e.liveKey === 'members') + if (parent) to.meta.activeMenu = `/nav/${parent.id}` + } + return true +}) +export const getRoutePath = (perm: string) => + perm === 'user.user/detail' && useUserStore().keys.includes('memberDetail') + ? '/members/detail' + : '' export default router diff --git a/admin/live-readonly/screens.ts b/admin/live-readonly/screens.ts index 0297acb2e..e7d6d24ce 100644 --- a/admin/live-readonly/screens.ts +++ b/admin/live-readonly/screens.ts @@ -1,11 +1,26 @@ -import type { RouteRecordRaw } from 'vue-router' // No synthetic ledger, arbitrary remote component paths, or workspace-wide dynamic route loader. export const screens = [ - {key:'workbench',path:'/workbench',title:'数据工作台',icon:'DataAnalysis',component:()=>import('@/views/workbench/index.vue')}, - {key:'orders',path:'/order',title:'订单列表',icon:'Tickets',component:()=>import('@/views/order/index.vue')}, - {key:'members',path:'/members',title:'用户列表',icon:'User',component:()=>import('@/views/consumer/lists/index.vue')}, - {key:'memberDetail',path:'/members/detail',title:'用户详情',icon:'User',hidden:true,component:()=>import('@/views/consumer/lists/detail.vue')}, - {key:'roster',path:'/roster',title:'医生排班',icon:'Clock',component:()=>import('@/views/doctor/roster.vue')}, - {key:'deptStats',path:'/dept-stats',title:'部门预约统计',icon:'PieChart',component:()=>import('@/views/doctor/dept-tongji.vue')} + { + key: 'workbench', + path: '/workbench', + component: () => import('@/views/workbench/index.vue') + }, + { key: 'orders', path: '/order', component: () => import('@/views/order/index.vue') }, + { + key: 'members', + path: '/members', + component: () => import('@/views/consumer/lists/index.vue') + }, + { + key: 'memberDetail', + path: '/members/detail', + hidden: true, + component: () => import('@/views/consumer/lists/detail.vue') + }, + { key: 'roster', path: '/roster', component: () => import('@/views/doctor/roster.vue') }, + { + key: 'deptStats', + path: '/dept-stats', + component: () => import('@/views/doctor/dept-tongji.vue') + } ] -export const routes:RouteRecordRaw[] = screens.map(s=>({path:s.path,name:'live-'+s.key,component:s.component,meta:{title:s.title,icon:'el-icon-'+s.icon,hidden:!!s.hidden,activeMenu:s.hidden?'/members':undefined,key:s.key,keepAlive:false}})) diff --git a/admin/live-readonly/server.mjs b/admin/live-readonly/server.mjs index fec128805..62d035ab9 100644 --- a/admin/live-readonly/server.mjs +++ b/admin/live-readonly/server.mjs @@ -19,7 +19,7 @@ http.createServer(async(req,res)=>{ if(!req.url?.startsWith('/') || req.url.startsWith('//'))return send(400,'text/plain','Invalid path') try { const {pathname}=new URL(req.url,self) - if(pages.has(pathname))return send(200,'text/html; charset=utf-8',await readFile(entry)) + if(pages.has(pathname) || /^\/admin\/nav\/[A-Za-z0-9_-]+$/.test(pathname))return send(200,'text/html; charset=utf-8',await readFile(entry)) const asset=pathname.match(/^\/admin\/assets\/([a-zA-Z0-9_.-]+)$/) if(asset && mime[path.extname(asset[1])])return send(200,mime[path.extname(asset[1])],await readFile(path.join(dist,'assets',asset[1]))) }catch { /* Return a non-descriptive 404. No URL, headers or body logging. */ } diff --git a/admin/live-readonly/user.ts b/admin/live-readonly/user.ts index 2458b0e81..00eb336fb 100644 --- a/admin/live-readonly/user.ts +++ b/admin/live-readonly/user.ts @@ -2,24 +2,105 @@ import { defineStore } from 'pinia' import type { RouteRecordRaw } from 'vue-router' import request, { clearSession, getSessionMeta, setAllowedResources } from './transport' import { projectResources } from './resources.mjs' -import { routes } from './screens' -// The actual bearer stays private to the direct HTTPS transport. No account data is persisted. +import { buildNavigation } from './navigation.mjs' + +interface MenuNode { + id: string + title: string + icon: string + children?: MenuNode[] +} +interface MenuEntry extends MenuNode { + breadcrumbs: string[] + officialHref: string | null + liveKey: string | null + external?: boolean + query?: Record +} +function asSidebar(node: MenuNode, entries: Record): RouteRecordRaw { + return { + path: `/nav/${node.id}`, + name: node.id, + meta: { + title: node.title, + icon: node.icon, + query: JSON.stringify(entries[node.id]?.query || {}) + }, + ...(node.children?.length + ? { children: node.children.map((n) => asSidebar(n, entries)) } + : {}) + } as RouteRecordRaw +} +// The sidebar is the account's actual tree. Only the independent capability set can enable API calls. export default defineStore('liveReadUser', { - state:()=>({ready:false, token:'', userInfo:{} as Record,perms:[] as string[],keys:[] as string[],routes:[] as RouteRecordRaw[]}), - actions:{ - forget(){this.$reset();clearSession()}, - async login(form:{account:string,password:string}) { - this.forget() - try { - await request.post({url:'/login/account',params:{account:form.account,password:form.password,terminal:1}}) - const self=await request.get({url:'/auth.admin/mySelf'}) - if(!getSessionMeta().authenticated || !self?.user || Number(self.user.is_paw)===0 || self.user.need_bind_work_wechat===true || Number(self.user.need_bind_work_wechat)===1)throw Error('请先在正式后台完成账号验证。') - const {keys,perms}=projectResources(self) - setAllowedResources(keys) - this.userInfo={name:String(self.user.name || '当前账号')};this.perms=perms;this.keys=keys - this.routes=routes.filter(r=>keys.includes(String(r.meta?.key))&&!r.meta?.hidden).map(r=>({path:r.path,name:r.name,meta:r.meta} as RouteRecordRaw));this.ready=true - return {is_paw:1,need_bind_work_wechat:false} - }catch(e){this.forget();throw e} + state: () => ({ + ready: false, + syncing: false, + token: '', + userInfo: {} as Record, + perms: [] as string[], + keys: [] as string[], + routes: [] as RouteRecordRaw[], + entries: {} as Record, + firstId: null as string | null, + menuVersion: 0 + }), + actions: { + forget() { + this.$reset() + clearSession() + }, + async syncMenu() { + if (this.syncing) return + this.syncing = true + try { + const self = await request.get({ url: '/auth.admin/mySelf' }) + if ( + !getSessionMeta().authenticated || + !self?.user || + !/^[1-9]\d*$/.test(String(self.user.id)) || + ![0, '0', false].includes(self.user.disable) || + String(self.user.is_paw) !== '1' || + ![0, '0', false].includes(self.user.need_bind_work_wechat) || + !Array.isArray(self.menu) || + !Array.isArray(self.permissions) + ) + throw Error('请先在正式后台完成账号验证。') + const { keys, perms } = projectResources(self) + const nav = buildNavigation(self.menu, keys) + setAllowedResources(keys) + const entries = Object.fromEntries(nav.entries.map((e: MenuEntry) => [e.id, e])) + this.$patch({ + userInfo: { name: String(self.user.name || '当前账号') }, + perms, + keys, + routes: nav.tree.map((n: MenuNode) => asSidebar(n, entries)), + firstId: nav.firstId, + ready: true, + menuVersion: this.menuVersion + 1 + }) + // Replace, never merge: revoked menu IDs must disappear on refresh. + this.entries = entries + } catch (e) { + this.forget() + throw e + } finally { + this.syncing = false + } + }, + async login(form: { account: string; password: string }) { + this.forget() + try { + await request.post({ + url: '/login/account', + params: { account: form.account, password: form.password, terminal: 1 } + }) + await this.syncMenu() + return { is_paw: 1, need_bind_work_wechat: false } + } catch (e) { + this.forget() + throw e + } + } } - } }) diff --git a/admin/local-preview/README.md b/admin/local-preview/README.md index 2573fb611..23be29d2f 100644 --- a/admin/local-preview/README.md +++ b/admin/local-preview/README.md @@ -1,20 +1,24 @@ -# 甄养堂管理后台:本地主题预览 +# 甄养堂管理后台:合成数据演示(5180) + +需要查询真实业务数据?请打开 **[正式数据只读登录(5179)](http://127.0.0.1:5179/admin/login)**,使用自己的后台账号。旧书签(5178)仅将页面导航跳到 5179 首页,不登录、不代理接口、不转发旧查询参数,也不返回演示数据。5179 未运行时请参照 [只读服务说明](../live-readonly/README.md),旧入口不会退回到演示版。 + +## 单独打开演示版 使用真实后台导航和工作台、订单、用户列表/详情、医生排班、部门统计等业务组件。新增的预约明细是预览专用只读台账,不替代线上接诊、通话或处方流程。独立 HTML、只读预览身份与本机合成数据替代登录、通知轮询和生产账户操作。只允许列明的预览页面;不读业务数据库,无代理,不执行生产发布脚本或同步发布目录。构建复用本项目已安装的前端依赖,不需要后端或数据库凭据。 在 admin 目录执行: ```sh -node local-preview/build.mjs && node local-preview/server.mjs 5178 +node local-preview/build.mjs && node local-preview/server.mjs 5180 ``` -打开 `http://127.0.0.1:5178/admin/workbench`,左栏可访问 6 个入口(另有用户详情页)。初次默认新版,顶栏切换可比较经典版。订单数据是虚构的,可筛选、翻页、看详情,不支持写入。停止前台服务按 Ctrl+C。改代码后重新构建即可,刷新页面获取新版本。 +打开 `http://127.0.0.1:5180/admin/workbench`,左栏可访问 6 个入口(另有用户详情页)。初次默认新版,顶栏切换可比较经典版。订单数据是虚构的,可筛选、翻页、看详情,不支持写入。停止前台服务按 Ctrl+C。改代码后重新构建即可,刷新页面获取新版本。 独立构建输出仅在本 worktree 的 `admin/node_modules/.zyt-ui-preview/dist`。本地服务器只绑定 IPv4 回环,校验 Host / Origin;只提供构建静态资源和显式模拟的查询端点(唯一允许的 POST 是查看订单详情)。未识别的请求不会转发。浏览器 CSP 限制接口、静态资源和图片加载。常规生产入口不使用预览路由或合成数据。 -本机若用 macOS 会话任务启动本分支的预览,可用 `launchctl list local.zyt.theme-preview.bfc2` 查看、`launchctl remove local.zyt.theme-preview.bfc2` 停止;停止预览不影响其他应用。未安装开机启动项。 +只有显式传入 `5180` 才会启动演示服务。旧入口可用 `node local-preview/server.mjs 5178`(或不传参数)启动,不需要构建产物,不加载合成数据;它不会自动启动 5179 或 5180。已有旧入口进程需要由运行方重新启动后才会使用新逻辑。 -验证:`node --test local-preview/fixtures.test.mjs local-preview/modules/*.test.mjs` 检查模拟数据;服务运行后 `node local-preview/verify-http.mjs` 复核写入、代理、跨域等均被拒绝。可选的 `browser_smoke.py` 使用 Python Playwright 和本地 Chromium,只允许本机请求。 +验证:`node --test local-preview/server.test.mjs local-preview/fixtures.test.mjs local-preview/modules/*.test.mjs` 离线检查入口分流和模拟数据;5180 演示服务运行后 `node local-preview/verify-http.mjs` 复核写入、代理、跨域等均被拒绝。可选的 `browser_smoke.py` 使用 Python Playwright 和本地 Chromium,只允许本机请求。 `verify-art-parameters.py --chrome --out <截图目录>` 对照固定的 Art Design Pro 默认参数,测量实际渲染的亮色、暗色和经典外观,并保存对应截图和 computed.json。该验收同样只访问回环地址。 diff --git a/admin/local-preview/browser_modules.py b/admin/local-preview/browser_modules.py index 3fb407571..592f26346 100644 --- a/admin/local-preview/browser_modules.py +++ b/admin/local-preview/browser_modules.py @@ -8,7 +8,7 @@ p.add_argument('--chrome', required=True) p.add_argument('--out', required=True, type=Path) args = p.parse_args() args.out.mkdir(exist_ok=True, parents=True) -base = 'http://127.0.0.1:5178' +base = 'http://127.0.0.1:5180' errors = [] foreign = [] failed = [] diff --git a/admin/local-preview/browser_smoke.py b/admin/local-preview/browser_smoke.py index c5b9fdd91..c0253a419 100644 --- a/admin/local-preview/browser_smoke.py +++ b/admin/local-preview/browser_smoke.py @@ -10,7 +10,7 @@ args = argparse.ArgumentParser() args.add_argument('--screens', type=Path, required=True) args.add_argument('--chrome', help='Path to an installed Chromium/Chrome executable') a = args.parse_args(); a.screens.mkdir(exist_ok=True, parents=True) -origin = 'http://127.0.0.1:5178' +origin = 'http://127.0.0.1:5180' errors, external, failed = [], [], [] with sync_playwright() as p: browser = p.chromium.launch(executable_path=a.chrome, args=['--disable-background-networking','--no-proxy-server','--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1']) diff --git a/admin/local-preview/server.mjs b/admin/local-preview/server.mjs index 530a39b6b..5584edbac 100644 --- a/admin/local-preview/server.mjs +++ b/admin/local-preview/server.mjs @@ -3,21 +3,49 @@ import http from 'node:http' import { readFile } from 'node:fs/promises' import { fileURLToPath } from 'node:url' import path from 'node:path' -import { resolveFixture } from './fixtures.mjs' const dist = fileURLToPath(new URL('../node_modules/.zyt-ui-preview/dist/', import.meta.url)) -const port = Number(process.argv[2] ?? 5178), host = '127.0.0.1' -const origin = `http://${host}:${port}` +const host = '127.0.0.1' +const demoPort = 5180, entryPort = 5178 +const demoOrigin = `http://${host}:${demoPort}`, entryAuthority = `${host}:${entryPort}` +const entryDestination = 'http://127.0.0.1:5179/admin/#' + +// This listener serves no bytes from disk and has no transport to 5179. +// An explicit empty fragment prevents browsers carrying an old fragment into 5179. +export function serveOldEntry(req, res) { + res.setHeader('Cache-Control', 'no-store') + res.setHeader('Referrer-Policy', 'no-referrer') + res.setHeader('Content-Security-Policy', "default-src 'none'; frame-ancestors 'none'; base-uri 'none'") + const end = (status, headers) => { res.writeHead(status, headers); res.end() } + const h = req.headers + if (h.host !== entryAuthority || (h.origin && h.origin !== 'http://' + entryAuthority) || h['sec-fetch-site'] === 'cross-site') return end(403) + if (req.method !== 'GET') return end(405, {Allow:'GET'}) + if ((h['sec-fetch-mode'] && h['sec-fetch-mode'] !== 'navigate') || + (h['sec-fetch-dest'] && h['sec-fetch-dest'] !== 'document') || + (h.accept && !/(?:^|,)\s*(?:text\/html|\*\/\*)(?:[;,]|$)/i.test(h.accept)) || + h.authorization || h.token) return end(403) + const pathname = req.url?.split('?', 1)[0] + if (pathname !== '/' && !/^\/admin(?:\/[a-zA-Z0-9_-]+)*\/?$/.test(pathname)) return end(404) + if (/(?:^|\/)(?:assets|static|adminapi|api|api-proxy|proxy)(?:\/|$)/i.test(pathname)) return end(404) + return end(302, {Location:entryDestination}) +} + +// The fixture module is deliberately loaded only on explicit demo startup. +async function createDemoHandler() { + const { resolveFixture } = await import('./fixtures.mjs') + await readFile(path.join(dist,'local-preview/index.html')) + return async (req, res) => serveDemo(resolveFixture, req, res) +} const csp = "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data: blob:; font-src 'self' data:; media-src 'none'; frame-src 'none'; worker-src 'none'; form-action 'none'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'" const types = {'.js':'application/javascript','.css':'text/css','.svg':'image/svg+xml','.woff2':'font/woff2','.woff':'font/woff','.png':'image/png','.jpg':'image/jpeg','.webp':'image/webp','.gif':'image/gif','.ttf':'font/ttf'} const routes = new Set(['/','/admin','/admin/','/admin/workbench','/admin/order','/admin/members','/admin/members/detail','/admin/appointments','/admin/roster','/admin/dept-stats']) -async function serve(req,res) { +async function serveDemo(resolveFixture,req,res) { res.setHeader('Content-Security-Policy',csp); res.setHeader('Cache-Control','no-store'); res.setHeader('X-Content-Type-Options','nosniff'); res.setHeader('Referrer-Policy','no-referrer') const send=(status,type,body)=>{ res.writeHead(status,{'Content-Type':type}); res.end(req.method==='HEAD' ? undefined : body) } const json=(status,obj)=>send(status,'application/json; charset=utf-8',JSON.stringify(obj)) const deny=(status)=>json(status,{code:0,show:1,msg:'本地只读预览:此操作未开放',data:null}) - if(req.headers.host !== `${host}:${port}` || (req.headers.origin && req.headers.origin !== origin) || req.headers['sec-fetch-site']==='cross-site') return deny(403) + if(req.headers.host !== `${host}:${demoPort}` || (req.headers.origin && req.headers.origin !== demoOrigin) || req.headers['sec-fetch-site']==='cross-site') return deny(403) if(!req.url?.startsWith('/') || req.url.startsWith('//')) return deny(400) - const {pathname,searchParams}=new URL(req.url,origin) + const {pathname,searchParams}=new URL(req.url,demoOrigin) if(pathname.startsWith('/adminapi/')) { let params=Object.fromEntries(searchParams) if(pathname==='/adminapi/order.order/detail') { @@ -36,5 +64,21 @@ async function serve(req,res) { } return deny(404) } -await readFile(path.join(dist,'local-preview/index.html')) -http.createServer((req,res)=>serve(req,res).catch(()=>{if(!res.headersSent)res.writeHead(500); res.end()})).listen(port,host,()=>console.log(`本地只读预览:${origin}/admin/workbench(合成数据,无转发)`)) +function selectPort(args) { + if (args.length === 0 || (args.length === 1 && args[0] === String(entryPort))) return entryPort + if (args.length === 1 && args[0] === String(demoPort)) return demoPort + throw new Error('端口仅支持 5178(旧入口跳转)或 5180(合成数据演示)') +} +export async function createLocalListener(args) { + const port = selectPort(args) + const handler = port === demoPort ? await createDemoHandler() : serveOldEntry + return {port, handler} +} +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const {port, handler} = await createLocalListener(process.argv.slice(2)) + const label = port === demoPort ? `合成数据演示:${demoOrigin}/admin/workbench` : `旧入口仅跳转到正式数据查询:${entryDestination}` + http.createServer(async (req, res) => { + try { await handler(req, res) } + catch { if (!res.headersSent) res.writeHead(500); res.end() } + }).listen(port, host, () => console.log(label)) +} diff --git a/admin/local-preview/server.test.mjs b/admin/local-preview/server.test.mjs new file mode 100644 index 000000000..755dc73bb --- /dev/null +++ b/admin/local-preview/server.test.mjs @@ -0,0 +1,75 @@ +import assert from 'node:assert/strict' +import { copyFile, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import path from 'node:path' +import { test } from 'node:test' +import { pathToFileURL } from 'node:url' + +const host = '127.0.0.1:5178' +const destination = 'http://127.0.0.1:5179/admin/#' +async function request(handler, url, headers = {}, method = 'GET') { + const res = { + headers: {}, + setHeader(name, value) { this.headers[name] = value }, + writeHead(status, headers) { this.status = status; Object.assign(this.headers, headers) }, + end(body) { this.body = body } + } + await handler({method, url, headers: {host, ...headers}}, res) + return res +} + +test('无构建和模拟数据时默认/显式 5178 仍可导航;5180 才依赖演示文件', async (t) => { + const root = await mkdtemp(path.join(tmpdir(), 'zyt-preview-entry-')) + t.after(() => rm(root, {recursive: true, force: true})) + const dir = path.join(root, 'local-preview') + await mkdir(dir) + const file = path.join(dir, 'server.mjs') + await copyFile(new URL('./server.mjs', import.meta.url), file) + const {createLocalListener} = await import(pathToFileURL(file).href) + for (const args of [[], ['5178']]) { + const {port, handler} = await createLocalListener(args) + assert.equal(port, 5178) + for (const url of ['/', '/admin', '/admin/', '/admin/workbench', '/admin/login?redirect=//dummy.invalid', '/admin/members/detail?id=123&token=dummy']) { + const res = await request(handler, url, {'sec-fetch-mode':'navigate', 'sec-fetch-dest':'document', accept:'text/html,application/xhtml+xml'}) + assert.equal(res.status, 302, url) + assert.equal(res.headers.Location, destination, url) + assert.equal(res.headers['Cache-Control'], 'no-store') + assert.equal(res.headers['Referrer-Policy'], 'no-referrer') + assert.equal(res.body, undefined) + } + } + await assert.rejects(createLocalListener(['5180']), {code:'ERR_MODULE_NOT_FOUND'}) + for (const args of [['5179'], ['0'], [''], ['5178','5180']]) { + await assert.rejects(createLocalListener(args), /端口仅支持/) + } + // A miniature, local-only demo build verifies that the explicit mode still serves a page and a fixture. + const dist = path.join(root, 'node_modules/.zyt-ui-preview/dist/local-preview') + await mkdir(dist, {recursive:true}) + await writeFile(path.join(dist, 'index.html'), '

offline demo

') + await writeFile(path.join(dir, 'fixtures.mjs'), 'export const resolveFixture = () => ({data:"demo"})') + const {port, handler} = await createLocalListener(['5180']) + const headers = {host:'127.0.0.1:5180'} + assert.equal(port, 5180) + assert.equal(String((await request(handler, '/admin/workbench', headers)).body), '

offline demo

') + assert.deepEqual(JSON.parse((await request(handler, '/adminapi/order.order/lists', headers)).body), {data:'demo'}) +}) + +test('5178 拒绝接口、资源、非导航请求和账号提交,不返回 Location 或数据', async () => { + const {createLocalListener} = await import('./server.mjs') + const {handler} = await createLocalListener([]) + const cases = [ + ...['/adminapi/order.order/lists', '/api-proxy/adminapi/order.order/lists', '/admin/assets/js', + '/admin/assets/style.css', '/admin/static/logo', '/admin/api/list', '/admin/favicon.ico', '/.env', + '//dummy.invalid/admin', '/admin/../admin', '/admin/%2f%2fdummy.invalid'].map(url => [url, {}, 'GET', 404]), + ...['POST','PUT','DELETE','OPTIONS','HEAD'].map(method => ['/admin/login', {}, method, 405]), + ...[{host:'dummy.invalid'}, {origin:'https://dummy.invalid'}, {'sec-fetch-site':'cross-site'}, + {'sec-fetch-mode':'cors'}, {'sec-fetch-dest':'script'}, {accept:'application/json'}, + {authorization:'test'}, {token:'test'}].map(headers => ['/admin/', headers, 'GET', 403]) + ] + for (const [url, headers, method, status] of cases) { + const res = await request(handler, url, headers, method) + assert.equal(res.status, status, method + ' ' + url) + assert.equal(res.headers.Location, undefined) + assert.equal(res.body, undefined) + } +}) diff --git a/admin/local-preview/verify-art-parameters.py b/admin/local-preview/verify-art-parameters.py index a59bbd6bb..6ea6a12ee 100644 --- a/admin/local-preview/verify-art-parameters.py +++ b/admin/local-preview/verify-art-parameters.py @@ -11,7 +11,7 @@ parser.add_argument('--chrome', required=True) parser.add_argument('--record-only', action='store_true', help='record the pre-correction build without asserting parity') a = parser.parse_args() a.out.mkdir(exist_ok=True, parents=True) -origin = 'http://127.0.0.1:5178/' +origin = 'http://127.0.0.1:5180/' read_colors = """() => { const style = (sel) => getComputedStyle(document.querySelector(sel)); const sample = (sel, key) => { diff --git a/admin/local-preview/verify-http.mjs b/admin/local-preview/verify-http.mjs index 24d0acbe1..6bea541a4 100644 --- a/admin/local-preview/verify-http.mjs +++ b/admin/local-preview/verify-http.mjs @@ -1,6 +1,6 @@ // Check the running local preview only; do not follow redirects, and do not use credentials. import assert from 'node:assert/strict' -const origin='http://127.0.0.1:5178' +const origin='http://127.0.0.1:5180' async function check(method,p,status,opts={}) { const r=await fetch(origin+p,{...opts,method,redirect:'error'}); assert.equal(r.status,status,`${method} ${p}`); console.log(`${method} ${p} -> ${r.status}`); return r } diff --git a/admin/src/layout/default/components/sidebar/menu-item.vue b/admin/src/layout/default/components/sidebar/menu-item.vue index 85fce91ed..a295b6ecf 100755 --- a/admin/src/layout/default/components/sidebar/menu-item.vue +++ b/admin/src/layout/default/components/sidebar/menu-item.vue @@ -58,6 +58,9 @@ const routeMeta = computed(() => { }) const resolvePath = (path: string) => { + // The online preview uses generated absolute item IDs to preserve arbitrary + // server menu nesting without ever routing by untrusted component strings. + if (import.meta.env.MODE === 'live-readonly' && path.startsWith('/nav/')) return path if (isExternal(path)) { return path }