chore(guard): add lane gate and fix taro h5 local white screen
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
a7c6c17c9e
commit
f40774ddd3
@ -256,6 +256,7 @@ pnpm build:admin
|
||||
pnpm build:admin-com # .com Web 运营台
|
||||
pnpm build:xhs # 小红书离线包 → apps/miniprogram/xhs/release
|
||||
pnpm typecheck
|
||||
pnpm guard:lanes # 分轨门禁(仅拦截新增跨轨域名引用)
|
||||
pnpm clean # 清 .next / dist
|
||||
```
|
||||
|
||||
|
||||
@ -79,9 +79,27 @@ export default defineConfig(async (merge) => {
|
||||
alias: {
|
||||
'@': path.resolve(__dirname, '..', 'src'),
|
||||
},
|
||||
modifyViteConfig(viteConfig: { publicDir?: string; appType?: string }) {
|
||||
modifyViteConfig(viteConfig: {
|
||||
publicDir?: string
|
||||
appType?: string
|
||||
server?: {
|
||||
host?: string
|
||||
port?: number
|
||||
open?: boolean
|
||||
proxy?: Record<string, unknown>
|
||||
}
|
||||
}) {
|
||||
viteConfig.publicDir = path.resolve(__dirname, '..', 'src', 'public')
|
||||
viteConfig.appType = 'spa'
|
||||
// Taro 4 + vite runner 在部分场景不会读取 h5.devServer.proxy,
|
||||
// 这里双写到 Vite server 配置,避免本地 /api/* 命中 404 导致白屏。
|
||||
viteConfig.server = {
|
||||
...(viteConfig.server || {}),
|
||||
host: '0.0.0.0',
|
||||
port: 10086,
|
||||
open: false,
|
||||
proxy: h5ViteProxy,
|
||||
}
|
||||
},
|
||||
h5: {
|
||||
publicPath: '/',
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import { Fragment, useEffect } from 'react'
|
||||
import type { PropsWithChildren } from 'react'
|
||||
import { Component, Fragment, useEffect } from 'react'
|
||||
import type { PropsWithChildren, ReactNode } from 'react'
|
||||
import Taro, { useDidHide, useDidShow, useLaunch } from '@tarojs/taro'
|
||||
import { flush, trackAppLaunch } from './utils/track'
|
||||
import {
|
||||
@ -17,6 +17,45 @@ import './styles/theme'
|
||||
import './styles/ebook.scss'
|
||||
import './app.scss'
|
||||
|
||||
class RuntimeGuard extends Component<
|
||||
{ children: ReactNode },
|
||||
{ hasError: boolean; message: string }
|
||||
> {
|
||||
constructor(props: { children: ReactNode }) {
|
||||
super(props)
|
||||
this.state = { hasError: false, message: '' }
|
||||
}
|
||||
|
||||
static getDerivedStateFromError(error: unknown) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
return { hasError: true, message }
|
||||
}
|
||||
|
||||
componentDidCatch(error: unknown) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('[RuntimeGuard]', error)
|
||||
}
|
||||
|
||||
render() {
|
||||
if (!this.state.hasError) return this.props.children
|
||||
return (
|
||||
<View
|
||||
style={{
|
||||
minHeight: '100vh',
|
||||
padding: '16px',
|
||||
background: '#140f19',
|
||||
color: '#ffb4b4',
|
||||
fontSize: '14px',
|
||||
lineHeight: '1.5',
|
||||
whiteSpace: 'pre-wrap',
|
||||
}}
|
||||
>
|
||||
<Text>页面运行异常(已拦截,避免白屏):{this.state.message}</Text>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function App({ children }: PropsWithChildren) {
|
||||
useLaunch((options) => {
|
||||
trackAppLaunch()
|
||||
@ -99,7 +138,7 @@ function App({ children }: PropsWithChildren) {
|
||||
// DebugFab 内部按 envVersion/NODE_ENV 自判;正式版 release 不渲染
|
||||
return (
|
||||
<Fragment>
|
||||
{children}
|
||||
<RuntimeGuard>{children}</RuntimeGuard>
|
||||
<DebugFab />
|
||||
</Fragment>
|
||||
)
|
||||
|
||||
@ -13,6 +13,7 @@ import {
|
||||
subscribeRemoteConfig,
|
||||
} from '@/services/remoteConfig'
|
||||
import type { NomadroRemoteConfig } from '@/data/remoteConfig.defaults'
|
||||
import { APP_TARGET } from '@/utils/config'
|
||||
import { applyH5Theme, useNomadroTheme } from '@/utils/h5Theme'
|
||||
import { goPage } from '@/utils/nav'
|
||||
import { usePageShare, markPageShare } from '@/utils/pageShare'
|
||||
@ -50,7 +51,10 @@ const INTERNAL_PORTALS: Record<PortalId, string> = {
|
||||
vip: '/pages/vip/index',
|
||||
}
|
||||
|
||||
const isH5 = process.env.TARO_ENV === 'h5'
|
||||
const isH5 =
|
||||
process.env.TARO_ENV === 'h5' ||
|
||||
APP_TARGET === 'h5' ||
|
||||
(typeof window !== 'undefined' && typeof document !== 'undefined')
|
||||
/** 开发快捷入口:默认隐藏 VIP;Admin/Config 仅 H5 开发态 */
|
||||
const showQuickNav = false
|
||||
const isDev = process.env.NODE_ENV === 'development'
|
||||
|
||||
@ -25,12 +25,13 @@ export function markPageShare<T extends object>(Page: T): T {
|
||||
* 页面须:markPageShare(export) + 本 hook。
|
||||
*/
|
||||
export function usePageShare(opts: PageShareOptions = {}) {
|
||||
const isWeapp = process.env.TARO_ENV === 'weapp'
|
||||
const title = opts.title || DEFAULT_TITLE
|
||||
const path = opts.path || '/pages/home/index'
|
||||
const query = opts.query || ''
|
||||
|
||||
useDidShow(() => {
|
||||
if (process.env.TARO_ENV !== 'weapp') return
|
||||
if (!isWeapp) return
|
||||
const opt = {
|
||||
withShareTicket: true,
|
||||
menus: ['shareAppMessage', 'shareTimeline'],
|
||||
@ -42,6 +43,8 @@ export function usePageShare(opts: PageShareOptions = {}) {
|
||||
)
|
||||
})
|
||||
|
||||
// H5/tt/xhs 不注册微信分享 hook,避免运行时兼容问题导致页面挂载失败。
|
||||
if (isWeapp) {
|
||||
useShareAppMessage(() => ({
|
||||
title,
|
||||
path: query ? `${path}?${query}` : path,
|
||||
@ -51,4 +54,5 @@ export function usePageShare(opts: PageShareOptions = {}) {
|
||||
title,
|
||||
query,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
@ -32,6 +32,8 @@
|
||||
"start": "next start",
|
||||
"lint": "eslint",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"guard:lanes": "python scripts/lane_guard.py",
|
||||
"guard:lanes:update": "python scripts/lane_guard.py --update-baseline",
|
||||
"clean": "node scripts/clean-artifacts.mjs",
|
||||
"mcp": "pnpm --filter @nomadro/mcp start",
|
||||
"dev:mcp": "pnpm --filter @nomadro/mcp start",
|
||||
|
||||
186
scripts/lane_guard.py
Normal file
186
scripts/lane_guard.py
Normal file
@ -0,0 +1,186 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Lane/domain guardrail with baseline support.
|
||||
|
||||
Purpose:
|
||||
- Keep .com/.cn/hackrobot lane references from drifting over time.
|
||||
- Do not force immediate cleanup of historical violations.
|
||||
- Block only *new* violations by default.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
BASELINE_PATH = ROOT / "scripts" / "lane_guard_baseline.json"
|
||||
|
||||
ALLOWED_SUFFIXES = {
|
||||
".ts",
|
||||
".tsx",
|
||||
".js",
|
||||
".jsx",
|
||||
".mjs",
|
||||
".cjs",
|
||||
".py",
|
||||
".sh",
|
||||
".ps1",
|
||||
".json",
|
||||
".yaml",
|
||||
".yml",
|
||||
".md",
|
||||
".conf",
|
||||
".env",
|
||||
".txt",
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Rule:
|
||||
scope_name: str
|
||||
path_prefixes: tuple[str, ...]
|
||||
forbidden_regexes: tuple[str, ...]
|
||||
|
||||
|
||||
RULES: tuple[Rule, ...] = (
|
||||
Rule(
|
||||
scope_name="com_scope_forbid_cn_domains",
|
||||
path_prefixes=("apps/com/",),
|
||||
forbidden_regexes=(
|
||||
r"\bnomadro\.cn\b",
|
||||
r"\bapi\.nomadro\.cn\b",
|
||||
r"\badmin\.nomadro\.cn\b",
|
||||
),
|
||||
),
|
||||
Rule(
|
||||
scope_name="cn_scope_forbid_com_domains",
|
||||
path_prefixes=("apps/miniprogram/", "apps/admin/"),
|
||||
forbidden_regexes=(
|
||||
r"\bnomadro\.com\b",
|
||||
r"\bapi\.nomadro\.com\b",
|
||||
r"\badmin\.nomadro\.com\b",
|
||||
),
|
||||
),
|
||||
Rule(
|
||||
scope_name="hackrobot_scope_forbid_nomadro_domains",
|
||||
path_prefixes=("apps/hackrobot/",),
|
||||
forbidden_regexes=(
|
||||
r"\bnomadro\.com\b",
|
||||
r"\bnomadro\.cn\b",
|
||||
r"\badmin\.nomadro\.com\b",
|
||||
r"\badmin\.nomadro\.cn\b",
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def git_tracked_files() -> list[str]:
|
||||
output = subprocess.check_output(
|
||||
["git", "ls-files"],
|
||||
cwd=ROOT,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
)
|
||||
return [line.strip() for line in output.splitlines() if line.strip()]
|
||||
|
||||
|
||||
def is_scannable(path: str) -> bool:
|
||||
suffix = Path(path).suffix.lower()
|
||||
if suffix and suffix not in ALLOWED_SUFFIXES:
|
||||
return False
|
||||
# Skip likely binaries/minified assets checked into repo.
|
||||
lowered = path.lower()
|
||||
if "/dist/" in lowered or "/.next/" in lowered:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def scan_violations() -> dict[str, list[str]]:
|
||||
files = git_tracked_files()
|
||||
violations: dict[str, list[str]] = {}
|
||||
|
||||
compiled_rules = [
|
||||
(
|
||||
rule,
|
||||
tuple(re.compile(pattern, flags=re.IGNORECASE) for pattern in rule.forbidden_regexes),
|
||||
)
|
||||
for rule in RULES
|
||||
]
|
||||
|
||||
for rel in files:
|
||||
if not is_scannable(rel):
|
||||
continue
|
||||
abs_path = ROOT / rel
|
||||
try:
|
||||
text = abs_path.read_text(encoding="utf-8", errors="ignore")
|
||||
except OSError:
|
||||
continue
|
||||
|
||||
for rule, patterns in compiled_rules:
|
||||
if not any(rel.startswith(prefix) for prefix in rule.path_prefixes):
|
||||
continue
|
||||
|
||||
for idx, line in enumerate(text.splitlines(), start=1):
|
||||
for pattern in patterns:
|
||||
if pattern.search(line):
|
||||
key = f"{rel}:{idx}:{rule.scope_name}"
|
||||
violations[key] = [line.strip(), pattern.pattern]
|
||||
|
||||
return violations
|
||||
|
||||
|
||||
def load_baseline() -> dict[str, list[str]]:
|
||||
if not BASELINE_PATH.exists():
|
||||
return {}
|
||||
data = json.loads(BASELINE_PATH.read_text(encoding="utf-8"))
|
||||
return data.get("violations", {})
|
||||
|
||||
|
||||
def write_baseline(violations: dict[str, list[str]]) -> None:
|
||||
payload = {
|
||||
"version": 1,
|
||||
"generatedBy": "scripts/lane_guard.py",
|
||||
"violations": dict(sorted(violations.items())),
|
||||
}
|
||||
BASELINE_PATH.write_text(
|
||||
json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
update = "--update-baseline" in sys.argv
|
||||
current = scan_violations()
|
||||
|
||||
if update:
|
||||
write_baseline(current)
|
||||
print(f"lane guard baseline updated: {len(current)} entries")
|
||||
return 0
|
||||
|
||||
baseline = load_baseline()
|
||||
new_keys = sorted(set(current) - set(baseline))
|
||||
|
||||
if not new_keys:
|
||||
print(f"lane guard passed (baseline={len(baseline)}, current={len(current)})")
|
||||
return 0
|
||||
|
||||
print("lane guard failed: new cross-lane references detected")
|
||||
for key in new_keys[:80]:
|
||||
line, pattern = current[key]
|
||||
print(f"- {key}")
|
||||
print(f" pattern: {pattern}")
|
||||
print(f" line: {line[:220]}")
|
||||
remaining = len(new_keys) - 80
|
||||
if remaining > 0:
|
||||
print(f"... and {remaining} more")
|
||||
print("\nIf intentional, run: python scripts/lane_guard.py --update-baseline")
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
1734
scripts/lane_guard_baseline.json
Normal file
1734
scripts/lane_guard_baseline.json
Normal file
File diff suppressed because one or more lines are too long
Loading…
Reference in New Issue
Block a user