"""``index.html`` 那份运行时注入要一直成立:注得进、逃得掉、换得动、坏得起。
前端 ``stores/app.ts`` 接得住 ``window.__APP_CONFIG__`` 就少一次往返——免登那一档
不用先问一遍 ``/settings/public`` 才知道该画哪一屏。这件事由 ``app/web_shell.py``
在生产里做,四个口径钉在这里:
1. **注得进**:脚本落在 ```` 之前,取出来就是接口那一份内容;
2. **逃得掉**:站点名是管理员自己填的,填个 ```` 也不能改写脚本的边界;
3. **换得动**:文件换了版本、配置改了值,缓存必须当场让路,不能抱着旧外壳不放;
4. **坏得起**:配置问不出来(库还没起来)就回 ``None``,让调用方按原样发文件——
首屏多问一次,总比整页打不开好。
只依赖标准库和项目自身的 app 包,跑在 backend 目录下::
python3 scripts/check_web_shell.py
"""
from __future__ import annotations
import json
import logging
import pathlib
import re
import sys
import tempfile
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
from app import public_config, web_shell # noqa: E402 (需要上面那行把 backend 目录放进 sys.path)
# 故意有两条走不通的路(配置问不出、文件不存在),别让它们的告警刷掉检查结论
logging.getLogger("app.web_shell").setLevel(logging.CRITICAL)
PAYLOAD = {
"site_name": "UnisOA 流程审批平台",
"hub": {"sso_only": True, "portal_url": "https://hub.example.com"},
"session": {"idle_minutes": 480},
}
def write_shell(root: pathlib.Path, html: str) -> pathlib.Path:
path = root / "index.html"
path.write_text(html, encoding="utf-8")
return path
def main() -> int:
problems: list[str] = []
def check(ok: bool, label: str) -> None:
print(f"[OK] {label}" if ok else f"[FAIL] {label}")
if not ok:
problems.append(label)
original = public_config.payload
public_config.payload = lambda: dict(PAYLOAD)
try:
with tempfile.TemporaryDirectory() as tmp:
root = pathlib.Path(tmp)
shell = write_shell(root, "\n\n
t\n \n \n\n")
# 1. 注得进
html = web_shell.shell_html(shell)
check(html is not None, "正常配置下要注出一份脚本")
if html:
scripts = re.findall(r"", html, re.S)
check(len(scripts) == 1, "注入的脚本有且只有一份,且落在 之前")
injected = json.loads(scripts[0]) if scripts else {}
check(injected == PAYLOAD, "注入的内容与接口 data 那一层逐项相同")
check(html.index("__APP_CONFIG__") < html.index(""), "脚本在 之前,画第一笔之前就到位")
check(web_shell.shell_html(shell) is html, "同一份文件同一份配置:第二次直接吃缓存")
# 3. 换得动(配置改了)
public_config.payload = lambda: {**PAYLOAD, "site_name": "改名了"}
changed = web_shell.shell_html(shell)
public_config.payload = lambda: dict(PAYLOAD)
check(changed is not None and "改名了" in changed, "改过配置立刻重新注一份,不抱着旧外壳")
# 3. 换得动(文件换了版本)
write_shell(root, "\n\n 新版本\n \n \n\n")
rebuilt = web_shell.shell_html(shell)
check(rebuilt is not None and "新版本" in rebuilt, "换了一版 index.html 也要重新注")
# 2. 逃得掉:值里同时塞进 与 U+2028(后者在 JSON 里合法、
# 在 JavaScript 的字符串字面量里却是行终止符,漏转义就把脚本剪断)
nasty = f"甲
{chr(0x2028)}乙"
public_config.payload = lambda: {"site_name": nasty, "hub": {}}
hostile = web_shell.shell_html(shell) or ""
head_part = hostile.split("")[0]
check(" 被转义,没能提前关掉脚本")
check(chr(0x2028) not in head_part, "值里的行分隔符也被转义,脚本没被剪断")
check("\\u003c" in hostile and "\\u2028" in hostile, "两处都以 \\u00xx 的形式写进脚本")
back = json.loads(re.search(r"__APP_CONFIG__=(\{.*?\});", hostile, re.S).group(1))
check(back["site_name"] == nasty, "转义过也还原得回来")
# 4. 坏得起
public_config.payload = lambda: (_ for _ in ()).throw(RuntimeError("库还没起来"))
check(web_shell.shell_html(shell) is None, "配置问不出来就回 None,交给调用方按原样发")
public_config.payload = lambda: dict(PAYLOAD)
# 头都找不着的文件不硬注
odd = write_shell(root, "没有 head")
check(web_shell.shell_html(odd) is None, "找不到 就不动它")
# 已经注过的产物别叠第二份
doubled = write_shell(root, "")
check(web_shell.shell_html(doubled) == doubled.read_text(encoding="utf-8"),
"已经注过一份就不再叠第二份")
# 文件不存在
check(web_shell.shell_html(root / "nope.html") is None, "文件读不到一样是回 None")
finally:
public_config.payload = original
if problems:
print(f"共 {len(problems)} 条不对")
return 1
print("通过:注入这一层注得进、逃得掉、换得动、坏得起")
return 0
if __name__ == "__main__":
sys.exit(main())