diff --git a/admin/live-native/README.md b/admin/live-native/README.md new file mode 100644 index 000000000..857af0832 --- /dev/null +++ b/admin/live-native/README.md @@ -0,0 +1,19 @@ +# 本机完整后台(正式 API) + +入口:。旧 5178 书签跳到此处。这个入口使用 `src/main.ts`、正式项目前端的路由守卫、用户 Store、完整视图目录、权限指令及请求客户端;不加载 `live-readonly` 的菜单投影、只读请求列表、替代顶栏或 `local-preview` 的合成数据。 + +菜单、业务数据和操作权限从正式服务取得。顶栏保留全屏、本人账号下拉和设置;界面新旧切换位于设置的「界面样式」。例如「数据统计 → 自录数据统计 → 自录转化统计」直接渲染业务 Vue,可按日期重新查询。空 `paths` 是目录的默认子页,不是无效地址。 + +登录页读取正式站的公开品牌和登录开关。账号密码登录在本机界面内完成,浏览器使用原生客户端直接请求正式 HTTPS API,依原版在当前浏览器保存会话并执行首次改密、企业微信绑定、菜单/按钮权限等校验。本机静态服务不接收表单/令牌,不连接数据库。企业微信扫码与统一账号快捷登录使用已登记的正式回调,成功后停留在正式域名,不将票据或会话从正式站转送到本地。在本机新版看实时数据请使用账号密码方式。 + +**这是正式业务,不是只读演示。** 账号获授权的保存、修改、删除、导出等操作会按正式后端的业务规则执行,可能影响线上数据。不要向他人提供密码或 token。 + +从 `admin` 目录启动(不执行 `release.mjs`、不写发布目录): + +```sh +node live-native/build.mjs && node live-native/server.mjs +``` + +构建输出仅在本工作树 `admin/node_modules/.zyt-live-native/dist`。本机会话任务为 `local.zyt.live-native.bfc2`,可用 `launchctl remove local.zyt.live-native.bfc2` 停止,不设开机启动项。可选 `server.mjs --qa` 使用 5181 供隔离验收。 + +黑盒检查:`python3 live-native/browser_contract.py --host 127.0.0.1:5179 --chrome --out <本地截图目录>`。测试拦截所有非本机请求,仅用虚构登录/统计数据检查真实组件;不验证真实用户凭据或线上写入。 diff --git a/admin/live-native/browser_contract.py b/admin/live-native/browser_contract.py new file mode 100644 index 000000000..dba44a8b8 --- /dev/null +++ b/admin/live-native/browser_contract.py @@ -0,0 +1,234 @@ +"""Native admin browser contract. Only loopback static assets leave the test interceptor.""" +import argparse +import json +import re +from pathlib import Path +from urllib.parse import parse_qs, quote, urlsplit + +from playwright.sync_api import expect, sync_playwright + + +OFFICIAL = "https://admin.zhenyangtang.com.cn" +WX, IAM = "/login/workWechatConfig", "/iam/config" +OVERVIEW, COST = "/stats.self_input/overview", "/stats.personal_account_cost/lists" +LOGIN, SELF, CONFIG = "/login/account", "/auth.admin/mySelf", "/config/getConfig" +ACCOUNT, PASS, TOKEN, USER = "offline-native", "offline-only-password", "fixture-session", "离线验收员" +PROJECTIONS = ["正式数据 · 只读", "刷新线上菜单", "退出预览", "切回旧版"] +BRAND = "data:image/svg+xml," + quote('') + + +def loopback(value): + if not re.fullmatch(r"127\.0\.0\.1:[1-9]\d{0,4}", value) or int(value.split(":")[1]) > 65535: + raise argparse.ArgumentTypeError("expected 127.0.0.1:PORT") + return value + + +def menu(id_, name, path, *, children=None, component="", perm=""): + item = dict(id=id_, type="M" if children else "C", name=name, paths=path, component=component, + perms=perm, params="", icon="", selected="", is_show=1, is_disable=0, is_cache=0) + if children: + item["children"] = children + return item + + +def profile(): + # The empty path is intentional: it is the index child in add_self_input_stats_menu.sql. + overview = menu(303, "自录转化统计", "", component="stats/self_input/index", perm=OVERVIEW[1:]) + cost = menu(304, "账户消耗录入", "/account_cost?via=sidebar", + component="stats/self_input/account_cost", perm=COST[1:]) + return {"user": {"id": 931, "name": USER, "is_paw": 1, "root": 0, "need_bind_work_wechat": False}, + "permissions": [OVERVIEW[1:], COST[1:], "stats.personal_account_cost/add"], + "menu": [menu(301, "数据统计", "/stats", children=[ + menu(302, "自录数据统计", "self_input", children=[overview, cost])])]} + + +class Fixture: + def __init__(self, host, wx, iam): + self.host, self.base = host, f"http://{host}" + self.public = {CONFIG: {"web_name": "后台登录", "version": "fixture", "login_image": BRAND, + "web_logo": BRAND, "copyright_config": []}, + WX: {"enabled": wx, "corp_id": "offline-corp" if wx else "", "agent_id": "11" if wx else ""}, + IAM: {"enabled": iam, "loginUrl": OFFICIAL + "/adminapi/iam/start" if iam else ""}} + self.reads = {SELF: profile(), "/chat/notifications": [], "/tcm.revisitDue/pending": {"items": [], "summary": {}}, + "/tcm.prescription/esignConfig": {"enabled": False}, "/dept.dept/all": [], + "/stats.self_input/mediaSourceOptions": [], COST: {"lists": [], "count": 0, "extend": {}}} + self.calls, self.errors = [], [] + self.allowed_handoff, self.documents = set(), [] + + def route(self, route): + req, url = route.request, urlsplit(route.request.url) + + def deny(reason): + # Never print headers, credentials or the query string. + self.errors.append([reason, req.method, url.path]) + route.abort() + + if (url.scheme, url.netloc) == ("http", self.host): + if req.method == "GET" and (url.path.startswith("/admin/assets/") or + (req.resource_type == "document" and url.path.startswith("/admin/")) or + url.path in ("/favicon.ico", "/admin/favicon.ico")): + return route.continue_() + return deny("unexpected local request") + if f"{url.scheme}://{url.netloc}" != OFFICIAL: + return deny("unexpected origin") + if req.resource_type == "document": + if req.method != "GET" or url.path not in self.allowed_handoff or url.query or url.fragment: + return deny("unexpected navigation") + self.allowed_handoff.clear() + self.documents.append(url.path) + return route.fulfill(content_type="text/html", body="Offline official site") + if not url.path.startswith("/adminapi/"): + return deny("unexpected official resource") + path = url.path.removeprefix("/adminapi") + cors = {"Access-Control-Allow-Origin": self.base, "Access-Control-Allow-Methods": "GET,POST,OPTIONS", + "Access-Control-Allow-Headers": "accept,token,version,content-type", "Cache-Control": "no-store"} + if req.method == "OPTIONS": + return route.fulfill(status=204, headers=cors) + self.calls.append([req.method, path]) + if req.method == "POST" and path == LOGIN: + if req.post_data_json != {"account": ACCOUNT, "password": PASS, "terminal": 1}: + return deny("unexpected sign-in body") + data = {"token": TOKEN, "is_paw": 1, "need_bind_work_wechat": False} + elif req.method != "GET": + return deny("unexpected mutation") + elif path in self.public: + data = self.public[path] + elif req.headers.get("token") != TOKEN: + return deny("missing fixture session") + elif path == OVERVIEW: + period = parse_qs(url.query).get("time_type", [""])[0] + if period not in ("today", "week"): + return deny("unexpected time range") + data = {"lists": [{"id": 1, "yeji_date": "2026-01-01", "media_source": "OFFLINE-" + period}], + "count": 1, "extend": {"date_range": ["2026-01-01", "2026-01-07"], + "summary": {"add_fans_count": 17 if period == "today" else 31}}} + elif path in self.reads: + data = self.reads[path] + else: + return deny("unknown API") + return route.fulfill(headers=cors, json={"code": 1, "show": 0, "msg": "", "data": data}) + + +def open_group(parent, name): + label = parent.locator(".el-sub-menu__title").filter(has_text=re.compile("^" + re.escape(name) + "$")) + expect(label).to_be_visible() + group = label.locator("..") + if "is-opened" not in (group.get_attribute("class") or "").split(): + label.click() + return group + + +def check_app(page, fixture, out): + page.get_by_placeholder("请输入账号").fill(ACCOUNT) + page.get_by_placeholder("请输入密码").fill(PASS) + page.get_by_role("button", name="登录", exact=True).click() + member = page.locator(".app-header").get_by_text(USER, exact=True) + expect(member).to_be_visible(timeout=15000) + expect(page.locator(".app-header [data-admin-ui-toggle]")).to_have_count(0) + for label in PROJECTIONS: + expect(page.locator(".app-header")).not_to_contain_text(label) + member.hover() + for label in ("个人设置", "切换账号", "退出登录"): + expect(page.get_by_text(label, exact=True)).to_be_visible() + page.mouse.move(1, 1) + + aside = page.locator(".app-aside .menu:visible") + def entry(name): + parent = open_group(open_group(aside, "数据统计"), "自录数据统计") + return parent.get_by_role("menuitem", name=name, exact=True) + + # First visit the sibling; the empty child below must be selected by click, not just by initial redirect. + entry("账户消耗录入").click() + expect(page.locator("main .personal-account-cost-page")).to_be_visible() + expect(page.locator("main .personal-account-cost-page").get_by_role("button", name="新增", exact=True)).to_be_visible() # Authorized control is present; never submit any business write. + assert parse_qs(urlsplit(page.url).query).get("via") == ["sidebar"], page.url + entry("自录转化统计").click() + stats = page.locator("main .self-input-stats-page") + expect(stats.get_by_text("业绩明细", exact=True)).to_be_visible() + expect(stats.locator(".el-table").get_by_text("OFFLINE-today", exact=True)).to_be_visible() + expect(stats.locator(".stats-kpi-card").filter(has_text="加粉数")).to_contain_text("17") + stats.get_by_text("最近7天", exact=True).click() + expect(stats.locator(".el-table").get_by_text("OFFLINE-week", exact=True)).to_be_visible() + expect(stats.locator(".stats-kpi-card").filter(has_text="加粉数")).to_contain_text("31") + # Native SPA history fallback and dynamic route re-registration must also work on a direct refresh. + page.reload() + expect(stats.locator(".el-table").get_by_text("OFFLINE-today", exact=True)).to_be_visible() + if out: + page.screenshot(path=str(out / "native-self-input.png")) + assert ["GET", COST] in fixture.calls and ["GET", OVERVIEW] in fixture.calls + assert [p for m, p in fixture.calls if m == "POST"] == [LOGIN] + + +def scenario(browser, args, wx, iam): + fixture = Fixture(args.host, wx, iam) + with browser.new_context(service_workers="block", viewport={"width": 1460, "height": 950}) as context: + context.set_default_timeout(8000) + context.route("**/*", fixture.route) + context.route_web_socket("**/*", lambda ws: (fixture.errors.append("unexpected WebSocket"), ws.close())) + context.on("page", lambda p: p.on("pageerror", lambda err: fixture.errors.append(str(err)))) + page = context.new_page() + try: + page.goto(fixture.base + "/admin/login", wait_until="networkidle") + assert {p for _, p in fixture.calls} == {CONFIG, WX, IAM}, fixture.calls + form = page.locator(".login-card .login-form") + expect(form.get_by_text("后台登录", exact=True)).to_be_visible() + brand = page.locator(".login-card img").filter(visible=True) + expect(brand).to_have_attribute("src", BRAND) + assert brand.evaluate("img => img.complete && img.naturalWidth > 0") + expect(form.get_by_placeholder("请输入账号")).to_be_visible() + expect(form.get_by_placeholder("请输入密码")).to_be_visible() + expect(form.get_by_role("button", name="登录", exact=True)).to_be_visible() + wx_tab = form.get_by_text("企业微信", exact=True) + iam_entry = form.get_by_role("button", name="统一账号快捷登录") + if wx: + expect(wx_tab).to_be_visible() + expect(form.get_by_text("账号登录", exact=True)).to_be_visible() + wx_tab.click() + scan = form.get_by_role("link", name=re.compile("企业微信扫码登录")) + expect(scan).to_be_visible() + dest = urlsplit(scan.get_attribute("href")) + query = parse_qs(dest.query) + assert (dest.scheme, dest.netloc, dest.path) == ("https", "open.work.weixin.qq.com", "/wwopen/sso/qrConnect") + assert query.get("redirect_uri") == [OFFICIAL + "/admin/login"] + assert query.get("appid") == ["offline-corp"] and query.get("agentid") == ["11"] + assert "noopener" in (scan.get_attribute("rel") or "").split() + assert not page.locator("iframe").count() and not fixture.documents + form.get_by_text("账号登录", exact=True).click() + else: + expect(wx_tab).to_be_hidden() + if iam: + expect(iam_entry).to_be_visible() + else: + expect(iam_entry).to_be_hidden() + if wx and iam: + if args.out: + page.screenshot(path=str(args.out / "native-login.png")) + check_app(page, fixture, args.out) + elif iam: + # No real navigation. The interceptor substitutes HTML for the user-initiated GET. + fixture.allowed_handoff.add("/adminapi/iam/start") + with context.expect_event("requestfinished", predicate=lambda r: + r.resource_type == "document" and r.url == OFFICIAL + "/adminapi/iam/start"): + iam_entry.click() + assert fixture.documents == ["/adminapi/iam/start"] + assert not fixture.errors, fixture.errors + except Exception: + print("Failed case:", wx, iam, "mocked:", fixture.calls, "errors:", fixture.errors, flush=True) + raise + return {"wx": wx, "iam": iam, "mocked": fixture.calls} + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--host", type=loopback, default="127.0.0.1:5179") + parser.add_argument("--chrome", required=True) + parser.add_argument("--out", type=Path, help="Optional directory for offline screenshots") + args = parser.parse_args() + if args.out: + args.out.mkdir(parents=True, exist_ok=True) + with sync_playwright() as pw, 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: + results = [scenario(browser, args, wx, iam) for wx in (False, True) for iam in (False, True)] + print(json.dumps({"native_browser_contract": "PASS", "real_api_calls": 0, "cases": results}, ensure_ascii=False)) diff --git a/admin/live-native/build.mjs b/admin/live-native/build.mjs new file mode 100644 index 000000000..914a105bd --- /dev/null +++ b/admin/live-native/build.mjs @@ -0,0 +1,12 @@ +// Build the actual admin entry/router/permission store, not a projected preview. +// Output remains in the worktree; do not run scripts/release.mjs. +import {build} from 'vite' +import path from 'node:path' +import {fileURLToPath} from 'node:url' +const here=path.dirname(fileURLToPath(import.meta.url)), root=path.dirname(here) +process.chdir(root) +await build({root,mode:'live-native',configFile:path.join(root,'vite.config.ts'),envFile:false, + define:{'import.meta.env.VITE_APP_BASE_URL':JSON.stringify('https://admin.zhenyangtang.com.cn')}, + cacheDir:path.join(root,'node_modules/.zyt-live-native/cache'), + build:{outDir:path.join(root,'node_modules/.zyt-live-native/dist'),emptyOutDir:true,sourcemap:false,reportCompressedSize:false, + rollupOptions:{input:path.join(here,'index.html')}}}) diff --git a/admin/live-native/index.html b/admin/live-native/index.html new file mode 100644 index 000000000..02d85d77c --- /dev/null +++ b/admin/live-native/index.html @@ -0,0 +1,2 @@ + +甄养堂管理后台
diff --git a/admin/live-native/server.mjs b/admin/live-native/server.mjs new file mode 100644 index 000000000..84ccc48c6 --- /dev/null +++ b/admin/live-native/server.mjs @@ -0,0 +1,29 @@ +// Loopback static site for the native browser application; never forward logins, tokens or business APIs. +import http from 'node:http' +import path from 'node:path' +import {fileURLToPath} from 'node:url' +import {readFile} from 'node:fs/promises' +const host='127.0.0.1',port=process.argv[2]==='--qa'?5181:5179,self=`http://${host}:${port}`,official='https://admin.zhenyangtang.com.cn' +const dist=fileURLToPath(new URL('../node_modules/.zyt-live-native/dist/',import.meta.url)), entry=path.join(dist,'live-native/index.html') +const types={js:'text/javascript',css:'text/css',svg:'image/svg+xml',png:'image/png',jpg:'image/jpeg',jpeg:'image/jpeg',webp:'image/webp',gif:'image/gif',ico:'image/x-icon',woff:'font/woff',woff2:'font/woff2',ttf:'font/ttf',otf:'font/otf',mp3:'audio/mpeg',mp4:'video/mp4',json:'application/json',wasm:'application/wasm'} +// Same-origin program assets. API authorization, including write permissions, belongs to the official backend. +// Media may be served by the storage provider configured by the business; never proxy it through localhost. +const csp=`default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline' https://web.sdk.qcloud.com; connect-src 'self' ${official} https://*.myqcloud.com https://*.aliyuncs.com https://*.tencentcloudapi.com https://*.rtc.qq.com https://*.my-imcloud.com wss://*.rtc.qq.com wss://*.my-imcloud.com; img-src 'self' https: data: blob:; font-src 'self' data:; media-src 'self' https: blob:; frame-src 'self' ${official} https://*.zhenyangtang.com.cn https://open.work.weixin.qq.com; form-action 'self' ${official}; frame-ancestors 'none'; base-uri 'none'; worker-src 'self' blob:; object-src 'none'` +await readFile(entry) +http.createServer(async(req,res)=>{ + res.setHeader('Referrer-Policy','no-referrer');res.setHeader('Cache-Control','no-store');res.setHeader('Content-Security-Policy',csp);res.setHeader('X-Content-Type-Options','nosniff') + const send=(s,t,b)=>{res.writeHead(s,{'Content-Type':t});res.end(req.method==='HEAD'?undefined:b)} + if(req.headers.host!==`${host}:${port}` || (req.headers.origin && req.headers.origin!==self))return send(403,'text/plain','Forbidden') + if(!['GET','HEAD'].includes(req.method))return send(405,'text/plain','Static site only') + if(!req.url?.startsWith('/') || req.url.startsWith('//'))return send(400,'text/plain','Invalid path') + try{ + const url=new URL(req.url,self),name=decodeURIComponent(url.pathname) + if(name==='/' || name==='/admin' || /^\/admin\/nav\/(?:m-\d+|p-[a-z0-9]+)(?:-\d+)?\/?$/.test(name)){res.writeHead(302,{Location:'/admin/'});return res.end()} + if(!name.startsWith('/admin/') || /[\\\x00-\x1f]/.test(name))return send(404,'text/plain','Not found') + const suffix=name.slice(7),parts=suffix.split('/');if(parts.some(p=>p==='..'||p.startsWith('.')))return send(404,'text/plain','Not found') + const ext=path.extname(name).slice(1).toLowerCase() + if(ext && Object.hasOwn(types,ext))return send(200,types[ext],await readFile(path.join(dist,suffix))) + if(parts[0]==='assets' || /\.(?:map|env|php|ini|sh|pem|log|sql)$/i.test(name))return send(404,'text/plain','Not found') + return send(200,'text/html; charset=utf-8',await readFile(entry)) + }catch{return send(404,'text/plain','Not found')} +}).listen(port,host,()=>console.log(`甄养堂管理后台 ${self}/admin/login`)) diff --git a/admin/live-readonly/README.md b/admin/live-readonly/README.md index 8536d8780..72ea4d11e 100644 --- a/admin/live-readonly/README.md +++ b/admin/live-readonly/README.md @@ -1,3 +1,5 @@ +> 历史模式,已由 [本机完整后台](../live-native/README.md) 取代。当前 5179 不运行此目录的只读壳;以下是早期版本说明。 + # 正式数据查询 · 仅本机登录 **入口:。** 旧书签 5178 只跳转到 5179;合成数据演示只能在显式启动的 5180 访问。5179 使用本分支的真实后台登录表单、布局和业务组件;不包含演示记录、不导入原聚合快照。这里不配置 SQL,也不与本机预览服务交换密码或令牌。用户亲自在浏览器内登录,浏览器直接向 `https://admin.zhenyangtang.com.cn/adminapi/` 发 HTTPS 请求,使用服务器原账号权限。只支持本站原生账号密码;扫码/统一登录、首次改密、强制绑定等在正式站点完成。未授权的页面保持关闭。 diff --git a/admin/local-preview/README.md b/admin/local-preview/README.md index 23be29d2f..3b036b5e4 100644 --- a/admin/local-preview/README.md +++ b/admin/local-preview/README.md @@ -1,6 +1,6 @@ # 甄养堂管理后台:合成数据演示(5180) -需要查询真实业务数据?请打开 **[正式数据只读登录(5179)](http://127.0.0.1:5179/admin/login)**,使用自己的后台账号。旧书签(5178)仅将页面导航跳到 5179 首页,不登录、不代理接口、不转发旧查询参数,也不返回演示数据。5179 未运行时请参照 [只读服务说明](../live-readonly/README.md),旧入口不会退回到演示版。 +需要查询真实业务数据?请打开 **[正式账号登录(5179)](http://127.0.0.1:5179/admin/login)**,使用自己的后台账号。旧书签(5178)仅将页面导航跳到 5179 首页,不登录、不代理接口、不转发旧查询参数,也不返回演示数据。5179 未运行时请参照 [完整后台说明](../live-native/README.md),旧入口不会退回到演示版。 ## 单独打开演示版 diff --git a/admin/src/layout/default/components/header/index.vue b/admin/src/layout/default/components/header/index.vue index 9b789923a..af84a8135 100755 --- a/admin/src/layout/default/components/header/index.vue +++ b/admin/src/layout/default/components/header/index.vue @@ -23,6 +23,7 @@