feat: 统一门户免登落地优化,消除首屏闪屏

- 免登换会话提前到应用启动时并行发起,路由守卫等待结果后直接跳转
- 新增首屏骨架屏,避免免登落地时闪现登录界面
- 公开配置随 index.html 注入,减少一次接口请求
- 调整免登相关接口的 401 处理逻辑,避免触发静默续期
main
kangwenjing 2026-11-06 09:24:21 +08:00
parent 22beadf4db
commit 698207b172
23 changed files with 925 additions and 166 deletions

View File

@ -31,6 +31,8 @@ unisoa/
│ │ ├── permissions.py # 权限码目录、内置角色、数据范围展开
│ │ ├── query.py # 查询参数归一化(三态布尔)
│ │ ├── envelope.py # 统一响应与异常
│ │ ├── public_config.py # 登录页与首屏共用的那份公开配置(接口与 index.html 注入同一个口径)
│ │ ├── web_shell.py # 发 index.html 时把它注进头里:画第一笔之前就知道该画哪一屏
│ │ ├── seed.py # 组织/人员/分类/表单/流程种子 + 一次性数据修复
│ │ ├── engine/
│ │ │ ├── engine.py # 流程引擎:流转、签核、退回、加签、转办、撤回、催办…
@ -56,6 +58,7 @@ unisoa/
│ ├── scripts/gen_portal_covers.py # 重新生成首页信息封面素材
│ ├── scripts/apply_portal_covers.py # 给已初始化过的库挂上封面
│ ├── scripts/check_route_guards.py # 扫路由表:有没有接口漏掉了登录/权限校验
│ ├── scripts/check_web_shell.py # 首屏那份注入:注得进、值里带 </script> 也逃得掉、换了就换缓存、问不出配置照样发页面
│ ├── scripts/check_db_dsn.py # 拼 DSN 的对账:口令带 @ : / # % 空格时还连得上库吗
│ ├── scripts/check_binding.py # 取数内核与候选来源:写法解析、源健康判据、前后端措辞对账
│ ├── scripts/check_fetch_url_args.py # 取数地址带参数:地址模板替换与 URL 编码、空入参不外呼、缓存键认地址
@ -2283,8 +2286,12 @@ sqlite 上(55 项:谁按得动、窗口怎么算、留痕与通知、终止
取后端配置元数据,底部只提交改动过的项;右边状态面板给下一次执行/轮询与倒计时、往后
3 次、当前口径、被什么挡住、近 30 天次数、增量游标与落后条数、立即执行入口),
数据源 `api/hub.ts` 的 `getSchedule()`;
免登两页:`views/auth/SsoCallbackView.vue`(`/sso` 落地页:票据换会话、`history.replaceState`
抹掉地址栏票据、失败不重试只送回门户)与 `views/auth/LoginView.vue`(Hub 开启时显示 Hub
免登两页:`utils/ssoLanding.ts`(`/sso` 落地那一样凭证在这里换会话——`main.ts` 一进来就
发出去,与语言包、路由块并行下载,路由守卫等它回来直接送人进站,所以从企微卡片点进来
不会再闪一屏「正在确认你的统一门户身份」;一个凭证只兑一次、兑完 `history.replaceState`
抹掉地址栏、失败不重试)与 `views/auth/SsoCallbackView.vue`(只剩失败态:照稳定原因码说
一句人话 + 送回门户,等待态是 `index.html` 里那幅进站骨架,320ms 之内不出现);
`views/auth/LoginView.vue`(Hub 开启时显示 Hub
下发的验证码、登录失败自动换一张;`hub.sso_only` 时不渲染账号密码,只留「前往统一门户」,
`?local=1` 保留应急本地口令入口);`utils/portal.ts` 是唯一的「整页跳去统一门户」出口,
`utils/sessionIdle.ts` 挂空闲心跳与本地超时计时(后端没配 `OA_SESSION_IDLE_MINUTES` 时什么都不做);
@ -2314,6 +2321,7 @@ sqlite 上(55 项:谁按得动、窗口怎么算、留痕与通知、终止
cd backend
python3 scripts/check_globals.py # 后端源码里的未定义引用
python3 scripts/check_route_guards.py # 每个接口要么挂权限点、要么要求登录、要么在匿名白名单里
python3 scripts/check_web_shell.py # 发 index.html 时那份公开配置注入(不连库:配置这一口是假的,只验注入这一层)
python3 scripts/check_binding.py # 取值写法 / 多源合并 / 数据源健康判据,顺带对一遍前后端共用的那几句措辞
python3 scripts/check_fetch_url_args.py # 取数地址上带参数:模板替换与 URL 编码、路径段同样生效、空入参不外呼、缓存键认地址(内存库,不连上游)
python3 scripts/check_embed.py # 表单嵌外部页面:参数白名单、接口取链接那道来源闸、给哪一条地址(含源上另登记的那几条与顺手带回的那几个值)、能否被嵌、免登短码、CSP、留痕不含参数值、回写档位与出口匹名、说明书与代码同源

View File

@ -16,12 +16,10 @@ from fastapi.responses import Response
from sqlalchemy import distinct, func, literal, or_, select
from sqlalchemy.orm import Session
from .. import hubconfig
from .. import config as config_module
from .. import cache
from .. import models, parallel, permissions, schemas, serializers, storage
from .. import models, parallel, permissions, public_config, schemas, serializers, storage
from ..config import settings
from ..security import session_idle_minutes
from ..db import get_db, ping
from ..deps import CurrentUser, actor_of, client_ip, current_user, require_permission
from ..envelope import bad_request, not_found, ok
@ -669,34 +667,11 @@ def public_settings() -> dict:
站点信息存在库里(``config:site``),系统设置页改完保存,这里下一次调用就是
新值,不用重启后端;库里还没有的项回落到 ``backend/config.toml`` 的 ``[site]`` 段。
同一份内容也会被打进 ``index.html``(见 :mod:`app.web_shell`),两条出口共用
:func:`app.public_config.payload`,口径只有一处。
"""
cfg = hubconfig.get()
return ok(
{
"site_name": settings.site_name,
"site_logo": settings.site_logo,
"site_description": settings.site_description,
"register_enabled": settings.register_enabled,
# 登录页据此决定要不要取验证码、要不要提示"账号由统一身份平台管理",
# 以及"只允许免登"时要不要把用户送回统一门户
"hub": {
"login_enabled": cfg.login_on,
"login_mode": cfg.hub_login_mode,
"auto_provision": cfg.hub_auto_provision,
# sso_enabled:能走免登(地址+应用编码+应用密钥齐了);
# sso_only:本系统不再收账号密码,登录页只留"去统一门户"。
# 应用密钥本身从不出接口,这里只说"配齐没有"。
"sso_enabled": cfg.sso_on,
"sso_configured": cfg.sso_ready,
"sso_only": cfg.sso_only,
"portal_url": cfg.portal_url,
"state_required": cfg.hub_sso_state_required,
},
# 本地会话生命周期归本系统管(对接指南第 8 节:Hub 登出不回收下游会话),
# 前端据此决定要不要跑心跳与空闲计时;0 表示没开
"session": {"idle_minutes": session_idle_minutes()},
}
)
return ok(public_config.payload())
@router.get("/system/info")

View File

@ -9,7 +9,7 @@ import time
from pathlib import Path
from fastapi import FastAPI, Request, status
from fastapi.responses import FileResponse, JSONResponse
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
from starlette.datastructures import MutableHeaders
from .api import (
@ -27,6 +27,7 @@ from .db import (SchemaCreationRefused, SessionLocal, advisory_lock, connection_
create_schema, ensure_database, list_stray_schemas, ping)
from .envelope import install_exception_handlers, ok
from . import storage as storage_module
from . import web_shell
from .engine import engine as engine_module
from .service import channels, embed, embed_session, events, external_check, hub_sync, leader, openauth, outbox, wake
from .seed import run as run_seed
@ -596,8 +597,22 @@ if _dist is not None:
return JSONResponse({"code": 404, "message": "接口不存在", "data": None}, status_code=404)
candidate = (_dist / full_path).resolve() if full_path else None
if candidate and candidate.is_file() and candidate.is_relative_to(_dist.resolve()):
return FileResponse(str(candidate), headers=_SHELL_HEADERS)
return FileResponse(str(_dist / "index.html"), headers=_SHELL_HEADERS)
if candidate.name != "index.html":
return FileResponse(str(candidate), headers=_SHELL_HEADERS)
return _shell_response(candidate)
return _shell_response(_dist / "index.html")
def _shell_response(path: Path):
"""发 ``index.html``:顺手把公开配置注进头里,前端因此少一次往返。
画第一笔之前浏览器就知道"这一档是免登还是账号密码"、门户地址是什么,
不必先转一圈 ``/settings/public`` 再决定画哪一屏(见 :mod:`app.web_shell`)。
配置问不出来就按原样发文件,页面宁可多问一次也不该打不开。
"""
html = web_shell.shell_html(path)
if html is None:
return FileResponse(str(path), headers=_SHELL_HEADERS)
return HTMLResponse(html, headers=_SHELL_HEADERS)
else:
@app.get("/", include_in_schema=False)

View File

@ -0,0 +1,46 @@
"""登录页与首屏共用的那份公开配置。
两个出口共用同一个口径,别各写一份:
* ``GET /api/v1/settings/public``(``app/api/support.py``)——前端挂载之后问的那一次;
* ``index.html`` 里注进 ``window.__APP_CONFIG__`` 的那一份(:mod:`app.web_shell`)——
画第一笔之前就送到浏览器手里的那一次。
里面只有匿名可读的东西:站点名与图标、免登这一档怎么画、空闲超时开没开。
应用密钥、Hub 令牌、任何人的个人信息,一概不出这扇门。
"""
from __future__ import annotations
from . import hubconfig
from .config import settings
from .security import session_idle_minutes
def payload() -> dict:
"""当前生效的公开配置(接口 ``data`` 那一层原样)。"""
cfg = hubconfig.get()
return {
"site_name": settings.site_name,
"site_logo": settings.site_logo,
"site_description": settings.site_description,
"register_enabled": settings.register_enabled,
# 登录页据此决定要不要取验证码、要不要提示"账号由统一身份平台管理",
# 以及"只允许免登"时要不要把用户送回统一门户
"hub": {
"login_enabled": cfg.login_on,
"login_mode": cfg.hub_login_mode,
"auto_provision": cfg.hub_auto_provision,
# sso_enabled:能走免登(地址+应用编码+应用密钥齐了);
# sso_only:本系统不再收账号密码,登录页只留"去统一门户"。
# 应用密钥本身从不出接口,这里只说"配齐没有"。
"sso_enabled": cfg.sso_on,
"sso_configured": cfg.sso_ready,
"sso_only": cfg.sso_only,
"portal_url": cfg.portal_url,
"state_required": cfg.hub_sso_state_required,
},
# 本地会话生命周期归本系统管(对接指南第 8 节:Hub 登出不回收下游会话),
# 前端据此决定要不要跑心跳与空闲计时;0 表示不启用
"session": {"idle_minutes": session_idle_minutes()},
}

View File

@ -0,0 +1,72 @@
"""把 ``index.html`` 发出去之前,先把公开配置注进 ``</head>`` 之前。
前端认 ``window.__APP_CONFIG__``(``frontend/src/stores/app.ts:initFromInjectedConfig``):
接得住就没有"先转一圈问 ``/settings/public``、再决定画哪一屏"那一次往返——登录页要问它
才知道该画免登那一屏还是账号密码表单,免登落地失败那一屏也要画「回到统一门户」那颗按钮。
开发模式下 vite 的 ``inject-public-settings`` 插件做同一件事,生产这一份就补在这里
(以前只有那句"与生产一致"的注释,没有对应的实现)。
三条口径:
* 配置直接取 :func:`app.public_config.payload`,与接口共用一份,不另写;
* 站点名这些是管理员自己填的,尖括号一律转义——``</script>`` 能改写脚本的边界;
* 注入只是"锦上添花":库还没起来、配置问不出、文件读不到,一律回 ``None``,
让调用方按原样把文件发出去,页面宁可多问一次也不该打不开。
"""
from __future__ import annotations
import hashlib
import json
import logging
from pathlib import Path
from . import public_config
logger = logging.getLogger(__name__)
#: 前端那一口约定的变量名,也是"这一份已经注过了"的记号
MARKER = "window.__APP_CONFIG__"
#: 只留最近这一版:index.html 一次部署换一次,留多了是白占内存
_cache: dict[str, str] = {}
def _script(payload: dict) -> str:
"""配置 -> 一段脚本。尖括号与行分隔符转义掉,别让管理员填的站点名改写脚本边界。"""
raw = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
raw = raw.replace("<", "\\u003c").replace(">", "\\u003e")
# 这两位在 JSON 里是合法字符,在 JavaScript 的字符串字面量里却是行终止符
raw = raw.replace(chr(0x2028), "\\u2028").replace(chr(0x2029), "\\u2029")
return f"<script>{MARKER}={raw};</script>"
def shell_html(path: Path) -> str | None:
"""注入好的 ``index.html`` 全文;任何一步问不出来就回 ``None``,调用方原样发文件。"""
try:
stat = path.stat()
payload = public_config.payload()
except Exception: # noqa: BLE001 - 库还没起来是常事,不该因此拦着发页面
logger.warning("首屏配置取不到,index.html 按原样发出", exc_info=True)
return None
# 缓存键 = 文件指纹 + 配置指纹:换版本、改站点名、动免登开关,都会当场绕开这一份
digest = hashlib.sha256(
json.dumps(payload, sort_keys=True, ensure_ascii=False, default=str).encode("utf-8")
).hexdigest()
key = f"{stat.st_mtime_ns}:{stat.st_size}:{digest}"
if _cache.get("key") == key and _cache.get("html"):
return _cache["html"]
try:
html = path.read_text(encoding="utf-8")
except OSError:
logger.warning("读不到 %s,交给调用方按原样发", path, exc_info=True)
return None
if "</head>" not in html:
return None
# 已经注过一份(比如有人把注好的产物又拷了回来)就别叠第二份
if MARKER in html:
return html
injected = html.replace("</head>", f"{_script(payload)}\n </head>", 1)
_cache.clear()
_cache.update({"key": key, "html": injected})
return injected

View File

@ -0,0 +1,122 @@
"""``index.html`` 那份运行时注入要一直成立:注得进、逃得掉、换得动、坏得起。
前端 ``stores/app.ts`` 接得住 ``window.__APP_CONFIG__`` 就少一次往返——免登那一档
不用先问一遍 ``/settings/public`` 才知道该画哪一屏。这件事由 ``app/web_shell.py``
在生产里做,四个口径钉在这里:
1. **注得进**:脚本落在 ``</head>`` 之前,取出来就是接口那一份内容;
2. **逃得掉**:站点名是管理员自己填的,填个 ``</script>`` 也不能改写脚本的边界;
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, "<!doctype html>\n<html>\n <head><title>t</title>\n </head>\n <body></body>\n</html>\n")
# 1. 注得进
html = web_shell.shell_html(shell)
check(html is not None, "正常配置下要注出一份脚本")
if html:
scripts = re.findall(r"<script>window\.__APP_CONFIG__=(\{.*?\});</script>", html, re.S)
check(len(scripts) == 1, "注入的脚本有且只有一份,且落在 </head> 之前")
injected = json.loads(scripts[0]) if scripts else {}
check(injected == PAYLOAD, "注入的内容与接口 data 那一层逐项相同")
check(html.index("__APP_CONFIG__") < html.index("</head>"), "脚本在 </head> 之前,画第一笔之前就到位")
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, "<!doctype html>\n<html>\n <head><title>新版本</title>\n </head>\n <body></body>\n</html>\n")
rebuilt = web_shell.shell_html(shell)
check(rebuilt is not None and "新版本" in rebuilt, "换了一版 index.html 也要重新注")
# 2. 逃得掉:值里同时塞进 </script> 与 U+2028(后者在 JSON 里合法、
# 在 JavaScript 的字符串字面量里却是行终止符,漏转义就把脚本剪断)
nasty = f"甲</script><img src=x onerror=alert(1)>{chr(0x2028)}乙"
public_config.payload = lambda: {"site_name": nasty, "hub": {}}
hostile = web_shell.shell_html(shell) or ""
head_part = hostile.split("</head>")[0]
check("<script>window.__APP_CONFIG__=" in hostile, "带尖括号的站点名照样注得进去")
check("<img src=x" not in head_part, "值里的 </script> 被转义,没能提前关掉脚本")
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, "<html><body>没有 head</body></html>")
check(web_shell.shell_html(odd) is None, "找不到 </head> 就不动它")
# 已经注过的产物别叠第二份
doubled = write_shell(root, "<html><head><script>window.__APP_CONFIG__={};</script></head></html>")
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())

View File

@ -12,7 +12,7 @@ MinIO / 统一身份那套真值都在镜像里,**集群里一份配置都不
| --- | --- |
| 仓库 | `docker.oa.unissense.tech/public/unis_oa`(Harbor,`public` 项目,匿名可拉) |
| 架构 | `linux/amd64` |
| tag | 时间戳(当前 `202611051545`)+ `latest` |
| tag | 时间戳(当前 `202611051738`)+ `latest` |
| 大小 | 压缩后约 96 MB |
| 端口 | `8000`(后端 API 与前端静态页同源,一个容器全包) |
| 配置 | 自带 `config.toml` + `config.prod.toml`(含密钥),不挂配置也能起 |

View File

@ -832,7 +832,7 @@ spec:
# 「服务器内部错误,请稍后重试(编号 xxxxxxxx)」)
# 202610261047 起:镜像自带 backend/config.prod.toml(含密钥),且修了口令带 @ 时
# DSN 被撕成两个主机名的坑(backend/scripts/check_db_dsn.py 盯着)
image: docker.oa.unissense.tech/public/unis_oa:202611051545
image: docker.oa.unissense.tech/public/unis_oa:202611051738
imagePullPolicy: IfNotPresent
ports:
- name: http

View File

@ -546,7 +546,7 @@ GET /notification/unread/count
GET /statistics/workbench 工作台卡片与最近待办
GET /statistics/overview 管理端总览
GET /statistics/process/{id} 单流程统计
GET /settings/public 免鉴权:站点名与 logo
GET /settings/public 免鉴权:站点名与 logo(同一份也注进 index.html,见 app/web_shell.py)
GET /config 全部 6 组运行配置:值 + 中文说明 + 范围 + 来源
GET /config/{group} 读一组 PUT /config/{group} 保存一组(存库即生效)
POST /config/reload 丢掉进程内快照立刻重读

View File

@ -421,8 +421,9 @@ Hub 侧要先做的三件事:注册应用拿到 `code` 与密钥明文、`laun
- 登录页 `frontend/src/views/auth/LoginView.vue`:`GET /api/v1/settings/public` 的
`hub.sso_only` 为真时不再渲染账号密码表单,也**不摆一屏等人点按钮**:挂载完立刻让后端写好
`state` 再整页跳去统一门户。这一屏从头到尾不会出现一张没人填的表单 —— 公开配置还没回来时
转圈配「正在确认你的统一门户身份」,人已经送出去时转圈配「正在前往统一门户」。
`state` 再整页跳去统一门户。这一屏从头到尾不会出现一张没人填的表单 —— 公开配置还没到手时
转圈配「正在确认你的统一门户身份」(这一档通常不会发生:配置随 `index.html` 一起到位,
见本节末那两扇门),人已经送出去时转圈配「正在前往统一门户」。
想留本地口令那扇门就访问 `/login?local=1` —— 那一档 `sso_only` 在页面上就当不成立,
自动跳转根本不启动,应急用的内置超管不会被抢在门外。
只有门户连着把人原样退回来(自动跳的预算用完,见下条)才停在这一屏,把「前往统一门户」
@ -443,6 +444,29 @@ Hub 侧要先做的三件事:注册应用拿到 `code` 与密钥明文、`laun
`?ticket=`(前端落地口径,交给 `POST /auth/sso/login`)、`#code=`(后端回调口径,交给
`POST /auth/sso/exchange`)、`?error=`(后端已经拒了,只照原因码说一句话,一次请求都不再发)——
然后用 `history.replaceState` 把它从地址栏抹掉、进站。
- **落地不再先闪一屏「正在确认你的统一门户身份」**(企微卡片点开的那一路最扎眼):
换会话这一步从落地页的 `onMounted` 提到了 `frontend/src/utils/ssoLanding.ts`,
`main.ts:bootstrap` 一进来就把请求发出去,与语言包、路由块并行下载——以前它排在
这三四个资源往返之后,浏览器必然先画一屏登录版面再走人。路由守卫(`router.beforeEach`
里那一条 `ssoLandingTarget`)等这一趟回来:换到会话就直接送去目标页,`sso-callback`
这条路由连确认都不会确认,它的懒加载块也就压根不下载;只有兑失败或地址上压根没凭证,
才把落地页交出来那句能看懂的话加「回到统一门户」。这一屏因此只剩失败态,
等待态换成了 `index.html` 里那幅进站骨架(320ms 之内不出现,出现也不是登录卡)。
一个凭证只兑一次由 `ssoLanding` 认凭证原文兜住(bootstrap、守卫、落地页三处调的是
同一个 promise),红线照旧:**绝不重试**、落地后立刻 `history.replaceState` 抹掉凭证。
单测:`utils/ssoLanding.spec.ts`(只兑一次、来路顺位、抹地址栏)、
`router/ssoGuard.spec.ts`(成功时这一屏不激活)。
前端拿公开配置有两扇门,两扇共用 `app/public_config.py` 那一处口径:
* **随文档一起来**:发 `index.html` 时后端把同一份内容注成 `window.__APP_CONFIG__`
(`app/web_shell.py`,开发模式由 vite 的 `inject-public-settings` 插件做同样的事)。
画第一笔之前浏览器就知道这一档是免登还是账号密码、门户地址是什么,不必先转一圈
`GET /api/v1/settings/public` 再决定画哪一屏。站点名里带 `</script>` 也不会改写脚本边界;
问不出配置(库还没起来)就按原样发文件,页面宁可多问一次也不该打不开。
自检:`python3 scripts/check_web_shell.py`。
* **挂载之后问一次**:`GET /api/v1/settings/public`,接口与注入不一致时以接口为准
(服务工作者只在断网时拿缓存的外壳,联网时导航永远先走网络,见 `sw.template.js`)。
后端几条硬规定(对应代码在 `app/api/auth.py:sso_login` 与 `app/service/sso_state.py`):
@ -450,6 +474,10 @@ Hub 侧要先做的三件事:注册应用拿到 `code` 与密钥明文、`laun
`POST /api/v1/auth/tickets/verify`,浏览器不参与校验;密钥不出接口、不进日志。
- **绝不重试**:票据是"先查即删"的一次性票(对接指南 4.4),重试只会把一次正常登录变成
"票据已被使用"。落地页失败之后不会再自动调第二次,页面上也只给「回到统一门户」。
同理,前端落地那条(``POST /auth/sso/login`` / ``POST /auth/sso/exchange``)回的 **401 是
业务结果**,不是"会话过期":这两条写在 ``frontend/src/api/client.ts:AUTH_ENDPOINTS`` 里,
不走静默续期。少了这一条,落地那一刻浏览器里压根没有会话可续,续期失败会把人从
「回到统一门户重新点一次」那一屏抢去登录页,而 ``sso`` 档的登录页又会当场自动跳回门户。
- **业务失败看 `data.active` 与 `reason`**:`ticket_invalid` / `ticket_expired` /
`ticket_audience_mismatch` 拒登并提示回门户重新点;`user_inactive` 除了拒登,还把本地
账号置为停用并清掉它的刷新令牌,绝不回落到旧会话(对接指南 1.4 / 4.3)。
@ -1456,6 +1484,7 @@ Hub 用 Go 写时间,`sent_at` 没赋值时回的是零值 `0001-01-01T00:00:0
`401001` 说明密钥没问题、推送那条是路不通;它连这个都回裸 `error`,才轮到怀疑密钥与站点。
投递记录里这两种的话分开写着,裸 `error` 那一档会把推送路径一起念出来。
真机验收清单(企微里点一次就知道):卡片点开不出现登录页 → 一屏「正在打开 …」→
落到该单的审批页;点开别人的单据能看不能批;`redirect` 被改成 `//evil.example.com`
时落默认页不出站;落地页刷新不会把用户卡在 `ticket_invalid`(票据只能用一次)。
真机验收清单(企微里点一次就知道):卡片点开不出现登录页、中途也不闪一屏「正在确认你的
统一门户身份」→ 一屏「正在打开 …」→ 落到该单的审批页;点开别人的单据能看不能批;
`redirect` 被改成 `//evil.example.com` 时落默认页不出站;落地页刷新不会把用户卡在
`ticket_invalid`(票据只能用一次)。

View File

@ -13,9 +13,97 @@
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-title" content="UnisOA" />
<title>UnisOA 流程审批平台</title>
<!-- 深色档在画第一笔之前就得定下来:这条原来写在 main.ts 里,而那是一份模块脚本,
等它跑起来这页已经白了一瞬。样式与骨架屏同理,都不能等 Tailwind 下载完。 -->
<script>
(function () {
try {
var saved = localStorage.getItem('theme')
var dark = saved === 'dark' || (!saved && window.matchMedia('(prefers-color-scheme: dark)').matches)
document.documentElement.classList.toggle('dark', dark)
} catch (e) {
/* 隐私模式里 localStorage 会抛:照着浅色画就是 */
}
})()
</script>
<style>
/* 首屏骨架:免登落地要先拿一次性票据换会话,这段等待不该让人看见一张登录页。
320ms 之内能进站就压根不画它(靠 animation-delay 撑着),网络慢时才替上那片空白。
类名同时给 views/auth/SsoCallbackView.vue 的等待态用,两处是同一幅样子。 */
.boot-shell {
display: flex;
min-height: 100vh;
flex-direction: column;
background: #f9fafb;
opacity: 0;
animation: boot-reveal 1ms linear 320ms forwards;
}
.dark .boot-shell { background: #020617; }
.boot-bar,
.boot-tabs {
display: flex;
flex-shrink: 0;
align-items: center;
gap: 12px;
padding: 14px 16px;
background: rgba(255, 255, 255, 0.9);
}
.boot-bar { border-bottom: 1px solid #e5e7eb; }
.boot-tabs { display: none; justify-content: space-around; border-top: 1px solid #e5e7eb; }
@media (max-width: 1023px) {
.boot-tabs { display: flex; }
}
.boot-main { flex: 1; padding: 16px; }
.boot-card { margin-bottom: 12px; padding: 16px; border-radius: 12px; background: #fff; }
.dark .boot-bar,
.dark .boot-tabs { background: rgba(30, 41, 59, 0.7); }
.dark .boot-bar { border-color: #1e293b; }
.dark .boot-tabs { border-color: #1e293b; }
.dark .boot-card { background: #1e293b; }
.boot-bar, .boot-card, .boot-tabs, .boot-block {
background-image: linear-gradient(90deg, transparent 0%, rgba(13, 148, 136, 0.08) 50%, transparent 100%);
background-size: 200% 100%;
background-repeat: no-repeat;
animation: boot-shimmer 1.6s linear infinite;
}
.boot-pill, .boot-line, .boot-block, .boot-tabs i {
display: block;
border-radius: 6px;
background: #e5e7eb;
}
.dark .boot-pill, .dark .boot-line, .dark .boot-block, .dark .boot-tabs i { background: #334155; }
.boot-pill { height: 20px; }
.boot-line { height: 12px; margin-bottom: 10px; }
.boot-block { width: 100%; height: 76px; }
.boot-tabs i { width: 24px; height: 24px; border-radius: 8px; }
.boot-w-xs { width: 48px; }
.boot-w-sm { width: 96px; }
.boot-w-md { width: 60%; }
.boot-w-lg { width: 40%; }
@keyframes boot-reveal { to { opacity: 1; } }
@keyframes boot-shimmer { from { background-position: 200% 0; } to { background-position: -200% 0; } }
@media (prefers-reduced-motion: reduce) {
.boot-bar, .boot-card, .boot-tabs, .boot-block { animation: none; }
}
</style>
</head>
<body>
<div id="app"></div>
<div id="app">
<!-- 这一份是挂载前的占位,app.mount() 会把它整块换掉。
画的是"进站的壳子"而不是登录页:从企业微信卡片点进来的人不该先撞见一张登录卡。 -->
<div class="boot-shell" aria-hidden="true">
<div class="boot-bar">
<span class="boot-pill boot-w-sm"></span>
<span class="boot-pill boot-w-xs" style="margin-left: auto"></span>
</div>
<div class="boot-main">
<div class="boot-card"><span class="boot-line boot-w-lg"></span><span class="boot-line boot-w-md"></span></div>
<div class="boot-card"><span class="boot-block"></span></div>
<div class="boot-card"><span class="boot-line boot-w-md"></span><span class="boot-line boot-w-sm"></span></div>
</div>
<div class="boot-tabs"><i></i><i></i><i></i><i></i></div>
</div>
</div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

View File

@ -0,0 +1,27 @@
// @vitest-environment jsdom
/**
* 撞 401 之后该干什么,分两种:**"这张票不行"** 与 **"你的会话过期了"**。
*
* 免登落地那一刻浏览器里还没有会话,`/auth/sso/login`、`/auth/sso/exchange` 回的 401
* 说的都是前者(票据过期、用过、state 对不上)。要是也走一遍静默续期,续不上就被送去
* 登录页——那句「回到统一门户重新点一次」根本没机会被看见,只允许免登的那一档
* 还会当场自动跳回门户,人在两个系统之间看着像打转。
*/
import { describe, expect, it } from 'vitest'
import { isAuthEndpoint } from '@/api/client'
describe('免登那两条的 401 是业务结果', () => {
it('换会话的接口自己回 401,不触发续期', () => {
expect(isAuthEndpoint('/auth/sso/login')).toBe(true)
expect(isAuthEndpoint('/api/v1/auth/sso/login')).toBe(true)
expect(isAuthEndpoint('/auth/sso/exchange')).toBe(true)
expect(isAuthEndpoint('/auth/login')).toBe(true)
expect(isAuthEndpoint('/auth/refresh')).toBe(true)
})
it('别的接口撞 401 照旧先试一次静默续期', () => {
expect(isAuthEndpoint('/auth/me')).toBe(false)
expect(isAuthEndpoint('/work/todo')).toBe(false)
expect(isAuthEndpoint(undefined)).toBe(false)
})
})

View File

@ -147,10 +147,21 @@ export function onUnauthorized(handler: SessionRecovery | null): void {
sessionRecovery = handler
}
/** 登录、验证码、刷新这几个接口自己回 401 是业务结果,不该触发续期,也不该重试。 */
const AUTH_ENDPOINTS = ['/auth/login', '/auth/captcha', '/auth/refresh']
/**
* 自己回 401 就是业务结果的几个接口:不该触发静默续期,更不该被送去登录页。
*
* 免登那两条(``/auth/sso/login``、``/auth/sso/exchange``)必须点名在这里:票据过期、
* 用过、state 对不上,后端回的都是 401,而落地那一刻浏览器里压根没有会话可续,
* 走一遍续期就等于把人从「回到统一门户重新点一次」那一屏抢走,送去登录页 ——
* 只允许免登的那一档还会当场自动跳回门户,看着像在两个系统之间打转。
* 别指望 ``/auth/login`` 这条顺带把它们盖住:``/auth/sso/login`` 里不含那一段。
*/
const AUTH_ENDPOINTS = [
'/auth/login', '/auth/captcha', '/auth/refresh',
'/auth/sso/login', '/auth/sso/exchange'
]
function isAuthEndpoint(url: unknown): boolean {
export function isAuthEndpoint(url: unknown): boolean {
return AUTH_ENDPOINTS.some((path) => String(url || '').includes(path))
}

View File

@ -290,7 +290,6 @@ export default {
captchaRefresh: 'Click to refresh',
captchaRequired: 'Captcha is required',
ssoSubtitle: 'Confirming your unified portal identity',
ssoWorking: 'Verifying the sign-in ticket with the unified portal, one moment',
ssoRetryHint: 'Each ticket works once. If it expired, was already used or does not match this system, go back to the portal and open this app again instead of reloading',
ssoNoTicket: 'No sign-in ticket came from the unified portal',
ssoBackToPortal: 'Back to the portal',
@ -300,7 +299,6 @@ export default {
ssoAutoJump: 'If you were not sent over on your own, use this button to reach the unified portal, no account needed here',
ssoJumping: 'Taking you to the unified portal, no account needed on this page',
ssoLocalOnlyHint: 'Everyone else signs in through the unified portal; this form is only for the break-glass local admin accounts',
ssoWorkingCode: 'The unified portal has confirmed your identity, opening your local session',
ssoErrDisabled: 'Unified portal sign-in is not enabled yet; ask an administrator to check the Hub URL, app code and integration key',
ssoErrTicket: 'The sign-in ticket from the unified portal is invalid or already used; go back to the portal and open this app again',
ssoErrExpired: 'The sign-in ticket from the unified portal has expired; go back to the portal and open this app again',

View File

@ -286,7 +286,6 @@ export default {
captchaRefresh: '点击刷新验证码',
captchaRequired: '请输入验证码',
ssoSubtitle: '正在确认你的统一门户身份',
ssoWorking: '正在向统一门户校验这次跳转带来的登录票据,请稍候',
ssoRetryHint: '登录票据只用一次。过期、用过或与本系统不匹配时,请回到统一门户重新点击本系统,不要刷新这一页',
ssoNoTicket: '没有收到统一门户带来的登录票据',
ssoBackToPortal: '回到统一门户',
@ -296,7 +295,6 @@ export default {
ssoAutoJump: '没有自动跳过去时,点上面这个按钮前往统一门户,无需在本页输入账号密码',
ssoJumping: '正在前往统一门户,无需在本页输入账号密码',
ssoLocalOnlyHint: '普通用户请从统一门户免登进入;这一栏只给应急用的本地管理员账号',
ssoWorkingCode: '统一门户已经验过身份,正在为你建立本地会话,请稍候',
ssoErrDisabled: '统一门户免登还没有启用,请联系管理员检查 Hub 站点地址、应用编码与免登应用密钥',
ssoErrTicket: '统一门户带来的登录票据无效或已经被使用,请回到统一门户重新点击本系统',
ssoErrExpired: '统一门户带来的登录票据已经过期,请回到统一门户重新点击本系统',

View File

@ -9,19 +9,13 @@ import { useAuthStore } from '@/stores/auth'
import { updateFavicon } from '@/utils/branding'
import { bindSessionIdle } from '@/utils/sessionIdle'
import { bindSessionRecovery } from '@/utils/sessionRecovery'
import { startSsoLanding } from '@/utils/ssoLanding'
import { initPwa } from '@/composables/usePwa'
import './style.css'
function initThemeClass() {
const savedTheme = localStorage.getItem('theme')
const shouldUseDark =
savedTheme === 'dark' || (!savedTheme && window.matchMedia('(prefers-color-scheme: dark)').matches)
document.documentElement.classList.toggle('dark', shouldUseDark)
}
async function bootstrap() {
initThemeClass()
// 深色档与首屏骨架都在 index.html 里画第一笔之前就定好了:写在这儿的话,
// 等这份模块脚本跑到,页面已经白了一瞬。
const app = createApp(App)
const pinia = createPinia()
app.use(pinia)
@ -33,6 +27,10 @@ async function bootstrap() {
// Restore a previous session before the router guard runs.
useAuthStore().checkAuth()
bindSessionRecovery(useAuthStore(), router)
// 统一门户免登落地:换会话这一趟现在就发出去,与语言包、路由块并行下载。
// 放在组件挂载之后才发,就等于让票据排在所有静态资源后面,浏览器会先画一屏
// 「正在确认你的统一门户身份」再走人 —— 从企业微信卡片点进来的人看见的就是那一下闪。
startSsoLanding()
// 空闲超时:后端配了才生效,窗口值每次现读公开配置,改配置不用重新部署前端
bindSessionIdle(useAuthStore(), router, () =>
Number(appStore.cachedPublicSettings?.session?.idle_minutes || 0)

View File

@ -3,6 +3,7 @@ import { useAuthStore } from '@/stores/auth'
import { applyDocumentTitle } from '@/router/title'
import { clearChunkReloadMark, reloadOnChunkError } from '@/router/chunkReload'
import { landingPath, recordReturnPath } from '@/utils/returnPath'
import { ssoLandingTarget } from '@/utils/ssoLanding'
const routes: RouteRecordRaw[] = [
{
@ -339,7 +340,7 @@ const router = createRouter({
// 权限不够时回落到哪一屏,用的就是 landingPath() 那张表:手机上门户排最后,
// 桌面照旧门户第一。这里不再另立一份顺序,否则「第一屏」和「回退页」会各说一套。
router.beforeEach((to) => {
router.beforeEach(async (to) => {
const authStore = useAuthStore()
if (to.meta.public) {
// 统一门户把票据落到了 /login(有人会把 launch_url 填成登录页):转到落地页处理,
@ -347,6 +348,14 @@ router.beforeEach((to) => {
if (to.name === 'login' && typeof to.query.ticket === 'string' && to.query.ticket) {
return { name: 'sso-callback', query: { ...to.query } }
}
// 免登落地:先把会话换到手,再决定画哪一屏。等的是 bootstrap 一进来就发出去的那一趟
// (同一个凭证只兑一次,这里绝不会多发一次请求),它通常在这里就已经带着会话回来了——
// 于是第一屏画出来就是目标页,中间那一屏「正在确认你的统一门户身份」不必露脸。
// 真失败了(后端拒票、地址上压根没凭证)才放行给落地页去说那一句能看懂的话。
if (to.name === 'sso-callback') {
const landed = await ssoLandingTarget(to.fullPath)
if (landed) return landed
}
// 已经登录又撞上 /login(Hub 上那条 launch_url 被人填成登录页):回第一屏,
// 而不是硬塞门户——手机上第一屏该是卡片那一屏,且得是他有权限的那一屏。
if (to.name === 'login' && authStore.isAuthenticated) {

View File

@ -0,0 +1,102 @@
// @vitest-environment jsdom
/**
* 从企业微信卡片点进来会不会先闪一屏「正在确认你的统一门户身份」,就看这一条守卫。
*
* 改造之前:落地页先挂载、先画出来,再由它的 `onMounted` 去发换会话的请求——这一屏
* 一定被看见一次,闪的就是它。
* 改造之后:守卫先等那一趟(等的是 `main.ts` 一进来就发出去的同一个 promise),
* 换到会话就直接把人送去目标页,`sso-callback` 这条路由连确认都不会确认,组件自然
* 也不会被下载和挂载;只有真失败才把它交出来,让人看见那句能看懂的话。
*
* 这里用一台小路由跑同一条判断(`ssoLandingTarget`),为的是不去拖整张路由表;
* 最后一条断言直接读 `router/index.ts` 的源码,钉住"真路由确实挂了这道闸"。
*/
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { mount } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import { createMemoryHistory, createRouter } from 'vue-router'
import { createI18n } from 'vue-i18n'
import zh from '@/i18n/locales/zh'
import SsoCallbackView from '@/views/auth/SsoCallbackView.vue'
import { useAuthStore } from '@/stores/auth'
import { ssoLandingTarget, _resetSsoLanding } from '@/utils/ssoLanding'
import routerSource from '@/router/index.ts?raw'
function stub() {
setActivePinia(createPinia())
const auth = useAuthStore()
const loginWithCode = vi.fn(async () => ({ user: {}, redirect: '' }))
const loginWithTicket = vi.fn(async () => ({}))
vi.spyOn(auth, 'loginWithCode').mockImplementation(loginWithCode)
vi.spyOn(auth, 'loginWithTicket').mockImplementation(loginWithTicket)
vi.spyOn(auth, 'can').mockImplementation((code: string) => code === 'work:todo')
return { auth, loginWithCode, loginWithTicket }
}
function buildRouter() {
const router = createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/sso', name: 'sso-callback', component: SsoCallbackView, meta: { public: true } },
{ path: '/todo', name: 'my-todo', component: { template: '<div />' } }
]
})
const confirmed: string[] = []
router.beforeEach(async (to) => {
if (to.name === 'sso-callback') {
const landed = await ssoLandingTarget(to.fullPath)
if (landed) return landed
}
return true
})
router.afterEach((to) => confirmed.push(String(to.name ?? to.path)))
return { router, confirmed }
}
beforeAll(() => {
window.matchMedia = ((query: string) => ({
matches: false, media: query, onchange: null,
addListener: () => {}, removeListener: () => {},
addEventListener: () => {}, removeEventListener: () => {}, dispatchEvent: () => false
})) as unknown as typeof window.matchMedia
})
beforeEach(() => {
localStorage.clear()
sessionStorage.clear()
_resetSsoLanding()
window.history.replaceState({}, '', '/sso')
})
describe('免登落地不再先画一屏身份识别', () => {
it('换到会话就直奔目标页:这一屏连确认都没有', async () => {
const double = stub()
const { router, confirmed } = buildRouter()
await router.push('/sso?ticket=G-1&redirect=/todo')
expect(double.loginWithTicket).toHaveBeenCalledTimes(1)
expect(router.currentRoute.value.path).toBe('/todo')
// 只有目标页这一条被确认过:sso-callback 连确认都没走到,组件也就没被下载、没被挂载
expect(confirmed).toEqual(['my-todo'])
})
it('后端拒票时才把这一屏交出来', async () => {
const double = stub()
const { router, confirmed } = buildRouter()
await router.push('/sso?error=SSO_TICKET_EXPIRED')
expect(router.currentRoute.value.name).toBe('sso-callback')
expect(confirmed).toEqual(['sso-callback'])
expect(double.loginWithTicket).not.toHaveBeenCalled()
const wrapper = mount(SsoCallbackView, {
global: {
plugins: [router, createI18n({ legacy: false, locale: 'zh', messages: { zh } })],
stubs: { AuthLayout: { template: '<div><slot /></div>' }, LocaleSwitcher: true }
}
})
await vi.waitFor(() => expect(wrapper.text()).toContain(zh.auth.ssoErrExpired))
})
it('真路由挂的就是这道闸', () => {
expect(routerSource).toContain("if (to.name === 'sso-callback')")
expect(routerSource).toContain('ssoLandingTarget(to.fullPath)')
})
})

View File

@ -0,0 +1,148 @@
// @vitest-environment jsdom
/**
* 免登落地换会话被提到应用挂载之前,这里钉的就是提前的代价:同一次落地只许兑一次。
*
* 改造之后这趟请求有三个可能的调用方——`main.ts` 的 bootstrap、路由守卫、真的挂出来
* 之后的落地页——它们拿到的必须是同一个 promise。票据与短码都是一次性消费
* (对接指南 4.4),多发一次就等于把一次正常登录弄成"票据已被使用"。
*/
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { createPinia, setActivePinia } from 'pinia'
import { useAuthStore } from '@/stores/auth'
import { rememberReturnPath, takeReturnPath } from '@/utils/ssoJump'
import { _resetSsoLanding, startSsoLanding } from '@/utils/ssoLanding'
function stub() {
const pinia = createPinia()
setActivePinia(pinia)
const auth = useAuthStore()
const loginWithCode = vi.fn(async () => ({ user: {}, redirect: '' }))
const loginWithTicket = vi.fn(async () => ({}))
vi.spyOn(auth, 'loginWithCode').mockImplementation(loginWithCode)
vi.spyOn(auth, 'loginWithTicket').mockImplementation(loginWithTicket)
// 挑第一屏要问权限,这里给一个够用的最小口径
vi.spyOn(auth, 'can').mockImplementation((code: string) => code === 'work:todo')
return { loginWithCode, loginWithTicket }
}
/** 把人放在某个地址上,模拟门户 302 回来时浏览器站着的地方。 */
function at(url: string): void {
window.history.replaceState({}, '', url)
}
beforeAll(() => {
window.matchMedia = ((query: string) => ({
matches: false, media: query, onchange: null,
addListener: () => {}, removeListener: () => {},
addEventListener: () => {}, removeEventListener: () => {}, dispatchEvent: () => false
})) as unknown as typeof window.matchMedia
})
beforeEach(() => {
localStorage.clear()
sessionStorage.clear()
_resetSsoLanding()
at('/sso')
})
describe('免登落地这一趟只兑一次', () => {
it('bootstrap、守卫、落地页三处都调,请求也只发一次', async () => {
at('/sso#code=C1')
const double = stub()
const [a, b, c] = await Promise.all([
startSsoLanding(),
startSsoLanding('/sso#code=C1'),
startSsoLanding('/sso?utm=x#code=C1')
])
expect(double.loginWithCode).toHaveBeenCalledTimes(1)
expect(a).toEqual(b)
expect(b).toEqual(c)
expect(a.status).toBe('ok')
})
it('换会话被拒之后再接手这一趟,也不会补发第二次', async () => {
at('/sso?ticket=T-1')
const double = stub()
double.loginWithTicket.mockRejectedValueOnce(new Error('统一门户拒了这张票据'))
const first = await startSsoLanding()
const again = await startSsoLanding('/sso?ticket=T-1')
expect(double.loginWithTicket).toHaveBeenCalledTimes(1)
expect(first.status).toBe('failed')
expect(again).toEqual(first)
if (first.status === 'failed') expect(first.message).toContain('统一门户拒了这张票据')
})
it('换了凭证就重新兑一次:上一条的结论不该拦住下一趟落地', async () => {
const double = stub()
at('/sso#code=C1')
await startSsoLanding()
at('/sso#code=C2')
await startSsoLanding()
expect(double.loginWithCode).toHaveBeenCalledTimes(2)
})
})
describe('免登落地该说什么、该抹什么', () => {
it('?error= 那一屏一个请求都不发', async () => {
at('/sso?error=SSO_STATE_REJECTED')
const double = stub()
const result = await startSsoLanding()
expect(result).toEqual({ status: 'failed', kind: 'error', reason: 'SSO_STATE_REJECTED', message: '' })
expect(double.loginWithCode).not.toHaveBeenCalled()
expect(double.loginWithTicket).not.toHaveBeenCalled()
})
it('地址上没有凭证:这一趟压根没开始', async () => {
const double = stub()
expect(await startSsoLanding()).toEqual({ status: 'none' })
expect(double.loginWithTicket).not.toHaveBeenCalled()
})
it('别的页面上出现 ticket= 不算免登落地,不许把它消费掉', async () => {
at('/todo?ticket=T-9')
const double = stub()
expect(await startSsoLanding()).toEqual({ status: 'none' })
expect(double.loginWithTicket).not.toHaveBeenCalled()
})
it('换到会话就把凭证从地址栏抹掉,state 原样交回后端', async () => {
at('/sso?ticket=T-9&state=abc')
const double = stub()
const result = await startSsoLanding()
expect(double.loginWithTicket).toHaveBeenCalledWith('T-9', 'abc')
expect(result.status).toBe('ok')
expect(window.location.pathname).toBe('/sso')
expect(window.location.search).toBe('')
})
it('后端带回的落地页优先,其次地址栏,最后才是跳出去之前存的那一份', async () => {
const double = stub()
double.loginWithCode.mockResolvedValue({ user: {}, redirect: '/todo/from-backend' })
rememberReturnPath('/work/remembered')
at('/sso?redirect=/work/from-address#code=C9')
const result = await startSsoLanding()
expect(result.status === 'ok' && result.path).toBe('/todo/from-backend')
// 用不上就不取:取一次即清,别让下一次落地没来路可用
expect(takeReturnPath()).toBe('/work/remembered')
})
it('redirect 写成外站就不进,落回他自己有权限的第一屏', async () => {
at('/sso?ticket=T-2&redirect=%2F%2Fevil.example.com%2Fx')
const result = await startSsoLanding()
expect(result.status === 'ok' && result.path).toBe('/todo')
})
it('成功落地清掉自动跳转的预算', async () => {
at('/sso#code=C3')
const double = stub()
// 模拟"这个标签页已经自动跳过两次":门户连着把人退回来时的状态
window.sessionStorage.setItem('unisoa_sso_jumps', `2,${Date.now()}`)
window.sessionStorage.setItem('unisoa_sso_return', '/work/job-1')
await startSsoLanding()
expect(double.loginWithCode).toHaveBeenCalledTimes(1)
// 预算清零,下一次没有会话时重新拿到两次自动跳转的机会
expect(window.sessionStorage.getItem('unisoa_sso_jumps')).toBeNull()
// 来路取回来用掉这一次,不留给下一趟进站
expect(window.sessionStorage.getItem('unisoa_sso_return')).toBeNull()
})
})

View File

@ -0,0 +1,131 @@
/**
* 统一门户免登的落地换会话:赶在首屏挂载之前,把地址上那一样一次性凭证换成本地会话。
*
* 为什么不放在落地页的 `onMounted` 里做:那一屏是 `/sso` 这条路由的懒加载块,
* `router.isReady()` 要等它连同语言包一起下完才 resolve,`app.mount()` 之后组件才
* 把换会话的请求发出去——整个免登因此排在三四个资源往返之后,浏览器先画一屏
* 「正在确认你的统一门户身份」再走人。从企业微信卡片点进来的人看见的就是这一下闪。
* 提到这里之后 `bootstrap()` 一进来就把请求发出去,它与静态资源并行飞,落地页
* 通常根本不会被挂载(见 `router/index.ts` 的 `beforeEach`)。
*
* 三条红线原样保留:
*
* 1. **一趟落地只兑一次**:票据与短码都是一次性的,重试等于自己把这次登录弄失败。
* 同一个凭证不管被谁调、调几遍,都只发一次请求——缓存键就是凭证原文,
* 所以换一个凭证必然重新兑一次,重复拿同一个必然不发第二次;
* 2. **兑完立刻从地址栏抹掉**:不进浏览历史、不进 Referer;
* 3. **`?error=` 一个请求都不许多发**:后端已经拒过,这里只把原因码带回去。
*
* 失败的句子不在这里翻译成人话:这一趟跑起来时语言包可能还在路上。这里只交回
* 稳定原因码与后端原话,怎么说由落地页按语言包定(口径与改造前一致)。
*/
import { useAuthStore } from '@/stores/auth'
import { errorMessage } from '@/utils/oa'
import { safeRedirect } from '@/utils/returnPath'
import { resetAutoJumpBudget, takeReturnPath } from '@/utils/ssoJump'
/** 落地地址上带回来的那一样东西是哪一种。 */
export type SsoEntryKind = 'ticket' | 'code' | 'error' | 'none'
/** 一趟落地的结果:进站路径、一句话说明,或者这一趟压根没有凭证。 */
export type SsoLandingResult =
| { status: 'ok'; kind: 'ticket' | 'code'; path: string }
| { status: 'failed'; kind: SsoEntryKind; reason: string; message: string }
| { status: 'none' }
/** 落地页的路径:Hub 上 `launch_url` 填前端路由或后端回调,最后都落在这里。 */
const LANDING_PATH = '/sso'
/** 地址上那一样东西:`#code=` 优先看片段,也认 `?code=`,免得有人手抄地址时丢掉片段。 */
function readEntry(url: URL): { kind: SsoEntryKind; credential: string } {
const code = (new URLSearchParams(url.hash.replace(/^#/, '')).get('code') || url.searchParams.get('code') || '').trim()
const ticket = (url.searchParams.get('ticket') || '').trim()
const error = (url.searchParams.get('error') || '').trim()
if (error) return { kind: 'error', credential: error }
if (code) return { kind: 'code', credential: code }
if (ticket) return { kind: 'ticket', credential: ticket }
return { kind: 'none', credential: '' }
}
function text(value: unknown): string {
return typeof value === 'string' ? value.trim() : ''
}
/** 把凭证从地址栏抹掉。人已经不在那个地址上时(SPA 内跳过来的)什么都不用做。 */
function scrubFromAddressBar(url: URL): void {
if (window.location.pathname !== url.pathname) return
// 用 replaceState:后退一次又能看到票据的那种事不该发生
window.history.replaceState({}, document.title, window.location.pathname)
}
async function exchange(url: URL, kind: 'ticket' | 'code', credential: string): Promise<SsoLandingResult> {
const authStore = useAuthStore()
// 来路三个来源按顺位取:后端回调带回来的 > 地址栏上的 > 跳去门户之前自己存的那一份
// (Hub 一期不解析 redirect,登录页无感跳出去时把来路暂存在了 ssoJump 里)
const fromAddress = text(url.searchParams.get('redirect'))
const state = text(url.searchParams.get('state'))
try {
let fromBackend = ''
if (kind === 'code') {
const session = await authStore.loginWithCode(credential)
fromBackend = text(session.redirect)
} else {
await authStore.loginWithTicket(credential, state)
}
scrubFromAddressBar(url)
resetAutoJumpBudget()
// 只认站内路径:`//` 与 `/\` 这类写法会被浏览器送去另一台主机
return { status: 'ok', kind, path: safeRedirect(fromBackend || fromAddress || takeReturnPath()) }
} catch (error) {
// 失败一律不再试第二次:这一份凭证已经作废,留在地址栏里只会让人刷新一下又失败一回
scrubFromAddressBar(url)
return { status: 'failed', kind, reason: '', message: errorMessage(error) }
}
}
let pending: Promise<SsoLandingResult> | null = null
let pendingKey = ''
/**
* 发起(或接上)这一趟落地的换会话。
*
* 幂等:`href` 缺省取浏览器当前地址,SPA 内跳过来时由路由守卫把目标地址交进来。
* 同一个凭证第二次调用拿到的是同一个 promise,因此永远不会兑两次。
*/
export function startSsoLanding(href?: string): Promise<SsoLandingResult> {
let url: URL
try {
url = new URL(typeof href === 'string' && href ? href : window.location.href, window.location.origin)
} catch {
return Promise.resolve({ status: 'none' })
}
// 只吃落地页那一个地址:别的页面上出现 `ticket=` 只是巧合,不该被消费掉
if (url.pathname !== LANDING_PATH) return Promise.resolve({ status: 'none' })
const { kind, credential } = readEntry(url)
if (kind === 'none') return Promise.resolve({ status: 'none' })
const key = `${kind}:${credential}`
if (pending && pendingKey === key) return pending
pendingKey = key
pending = kind === 'error'
// 原因码不是秘密,留在地址栏里:这一屏刷新一下还是那句话,比刷新成"没有凭证"好懂
? Promise.resolve<SsoLandingResult>({ status: 'failed', kind, reason: credential, message: '' })
: exchange(url, kind, credential)
return pending
}
/**
* 路由守卫用的那一层:换到会话就回该去的站内路径,换不到回空串(那一屏这才该出现)。
*
* 守卫等的是同一趟请求,所以这一条既不提早也不补发——它只把"成功了就别画那一屏"
* 这一句决定说给路由听。
*/
export async function ssoLandingTarget(fullPath: string): Promise<string> {
const result = await startSsoLanding(fullPath)
return result.status === 'ok' ? result.path : ''
}
/** 单测用:把这一趟的记录清空,免得用例之间共用同一个凭证。 */
export function _resetSsoLanding(): void {
pending = null
pendingKey = ''
}

View File

@ -24,6 +24,7 @@ import { createI18n } from 'vue-i18n'
import zh from '@/i18n/locales/zh'
import { useAppStore, useAuthStore } from '@/stores'
import { rememberReturnPath, takeReturnPath } from '@/utils/ssoJump'
import { _resetSsoLanding } from '@/utils/ssoLanding'
import SsoCallbackView from './SsoCallbackView.vue'
vi.mock('@/api/auth', () => ({ ssoBegin: vi.fn(async () => ({ portal_url: 'https://hub.example.com' })) }))
@ -81,6 +82,8 @@ beforeAll(() => {
beforeEach(() => {
localStorage.clear()
sessionStorage.clear()
// 换会话现在记在 ssoLanding 那一趟上:一个凭证只兑一次,用例之间必须各拿各的凭证
_resetSsoLanding()
})
describe('企业微信卡片点开之后的落地', () => {
@ -136,5 +139,24 @@ describe('企业微信卡片点开之后的落地', () => {
expect(router.currentRoute.value.path).toBe('/sso')
expect(wrapper.text()).toContain('SSO_STATE_REJECTED')
expect(wrapper.text()).toContain(zh.auth.ssoErrState)
// 这一屏得给一条出路:配了门户地址就把「回到统一门户」交回给人自己点
expect(wrapper.text()).toContain(zh.auth.ssoBackToPortal)
})
it('万一还在等:这一屏只接着画进站的骨架,不画登录那套版面', async () => {
// 守卫正常挂着时走不到这里(它在挂载之前就把这一趟等完了),这一屏因此是兜底:
// 兜底也不该让人先撞见一张登录卡——那正是这次要消掉的"闪一下"
const double = stub()
let settle: (value: unknown) => void = () => {}
double.loginWithTicket.mockImplementation(() => new Promise((resolve) => { settle = resolve }))
const { wrapper, router } = await open('/sso?ticket=T-5', double)
expect(wrapper.find('.boot-shell').exists()).toBe(true)
expect(wrapper.find('.card').exists()).toBe(false)
expect(wrapper.text()).not.toContain(zh.auth.ssoSubtitle)
settle({})
await flushPromises()
// 换到会话就让人走:从头到尾这一屏上都没有过一张登录卡
expect(router.currentRoute.value.path).toBe('/todo')
expect(wrapper.find('.card').exists()).toBe(false)
})
})

View File

@ -1,5 +1,21 @@
<template>
<AuthLayout>
<!-- 会话还没换到手:这一屏不画登录那套版面,只把 index.html 里那幅「进站的壳子」接着画一遍
(类名与样式都在那一头,320ms 之内不出现,出现也不刺眼),所以挂载这一下看不出换页。
路由守卫已经把换会话这一趟等在前面了,能走到这里的几乎只有失败那一种。 -->
<div v-if="phase === 'working'" class="boot-shell" aria-hidden="true">
<div class="boot-bar">
<span class="boot-pill boot-w-sm"></span>
<span class="boot-pill boot-w-xs" style="margin-left: auto"></span>
</div>
<div class="boot-main">
<div class="boot-card"><span class="boot-line boot-w-lg"></span><span class="boot-line boot-w-md"></span></div>
<div class="boot-card"><span class="boot-block"></span></div>
<div class="boot-card"><span class="boot-line boot-w-md"></span><span class="boot-line boot-w-sm"></span></div>
</div>
<div class="boot-tabs"><i></i><i></i><i></i><i></i></div>
</div>
<AuthLayout v-else>
<div class="mb-8 text-center">
<div
class="mx-auto flex h-14 w-14 items-center justify-center rounded-2xl bg-primary-600 text-lg font-bold text-white shadow-glow lg:hidden"
@ -12,30 +28,23 @@
</div>
<div class="card p-6 text-center sm:p-8">
<template v-if="phase === 'working'">
<Icon name="refresh" class="mx-auto h-7 w-7 animate-spin text-primary-600" />
<p class="mt-4 text-sm text-gray-600 dark:text-dark-200">{{ workingText }}</p>
</template>
<template v-else>
<Icon name="exclamationTriangle" class="mx-auto h-7 w-7 text-amber-500" />
<p class="mt-4 text-sm font-medium text-gray-800 dark:text-dark-100">{{ message }}</p>
<p class="mt-2 text-xs leading-5 text-gray-500 dark:text-dark-400">{{ t('auth.ssoRetryHint') }}</p>
<!-- 后端回调失败时带回来的是稳定原因码,摆在角落给排障用,不参与翻译 -->
<p v-if="errorCode" class="mt-1 text-[11px] text-gray-400 dark:text-dark-500">{{ errorCode }}</p>
<div class="mt-6 flex flex-col gap-2">
<button v-if="portalUrl" type="button" class="btn btn-primary w-full" @click="toPortal">
<Icon name="externalLink" class="mr-1 h-4 w-4" />
{{ t('auth.ssoBackToPortal') }}
</button>
<!-- 票据换不到会话就不给回本地口令那扇门(对接文档第 10 节):这一屏只把人送回门户。
管理员应急要自己写 /login?local=1,不在这儿留入口。 -->
<button v-if="breakGlass" type="button" class="btn btn-secondary w-full" @click="toLocalLogin">
<Icon name="user" class="mr-1 h-4 w-4" />
{{ t('auth.ssoLocalLogin') }}
</button>
</div>
</template>
<Icon name="exclamationTriangle" class="mx-auto h-7 w-7 text-amber-500" />
<p class="mt-4 text-sm font-medium text-gray-800 dark:text-dark-100">{{ message }}</p>
<p class="mt-2 text-xs leading-5 text-gray-500 dark:text-dark-400">{{ t('auth.ssoRetryHint') }}</p>
<!-- 后端回调失败时带回来的是稳定原因码,摆在角落给排障用,不参与翻译 -->
<p v-if="errorCode" class="mt-1 text-[11px] text-gray-400 dark:text-dark-500">{{ errorCode }}</p>
<div class="mt-6 flex flex-col gap-2">
<button v-if="portalUrl" type="button" class="btn btn-primary w-full" @click="toPortal">
<Icon name="externalLink" class="mr-1 h-4 w-4" />
{{ t('auth.ssoBackToPortal') }}
</button>
<!-- 票据换不到会话就不给回本地口令那扇门(对接文档第 10 节):这一屏只把人送回门户。
管理员应急要自己写 /login?local=1,不在这儿留入口。 -->
<button v-if="breakGlass" type="button" class="btn btn-secondary w-full" @click="toLocalLogin">
<Icon name="user" class="mr-1 h-4 w-4" />
{{ t('auth.ssoLocalLogin') }}
</button>
</div>
</div>
<div class="mt-6 flex items-center justify-center gap-3">
@ -47,19 +56,22 @@
<script setup lang="ts">
/**
* 统一门户免登落地页。
* 统一门户免登落地页:**只负责说失败的那一句话**。
*
* Hub 门户点本系统卡片后会 302 到这里,按 Hub 上登记的落地地址不同,地址上带的东西不同:
*
* * ``?ticket=…&state=…``:``launch_url`` 填的是本前端路由,票据由这个页面交给后端校验;
* * ``?ticket=…&state=…``:``launch_url`` 填的是本前端路由,票据交给后端校验;
* * ``#code=…``:``launch_url`` 填的是后端回调(``GET /api/v1/auth/sso/callback``,别名
* ``/sso/hub``),后端已经验过票,这里只拿一次性短码换会话——票据从没进过浏览器;
* * ``?error=…``:后端回调当场把票拒了,这里只照稳定原因码说一句话,不再发第二次请求。
*
* 这个页面只做三件事:把地址上那一样东西交给后端换会话、把它从地址栏抹掉、把人送进目标页面。
* 换会话本身不在这一页做了:它由 :func:`utils/ssoLanding` 在应用挂载之前就发出去,
* 路由守卫等它回来就直接把人送到目标页(``beforeEach`` 里那一条),这一屏因此通常
* 压根不出现。只有兑失败、或地址上压根没有凭证时才会画到这一页——那时候该看的
* 是一句能看懂的话和回去的那颗按钮,不是又一张登录卡。
*
* 两条来自对接文档的红线:**绝不重试**(票据与短码都是一次性消费,重试等于自己把登录
* 弄失败),落地成功后**立刻把它从地址栏抹掉**(不进浏览历史、不进 Referer)。
* 两条来自对接文档的红线仍然由 ``ssoLanding`` 守着:**绝不重试**(票据与短码都是
* 一次性消费),落地后**立刻把它从地址栏抹掉**(不进浏览历史、不进 Referer)。
*/
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
@ -70,16 +82,12 @@ import LocaleSwitcher from '@/components/common/LocaleSwitcher.vue'
import { ssoBegin } from '@/api/auth'
import { ssoErrorKey } from '@/views/auth/ssoErrors'
import { leaveToPortal } from '@/utils/portal'
import { useAuthStore } from '@/stores/auth'
import { startSsoLanding, type SsoLandingResult } from '@/utils/ssoLanding'
import { useAppStore } from '@/stores/app'
import { safeRedirect } from '@/utils/returnPath'
import { resetAutoJumpBudget, takeReturnPath } from '@/utils/ssoJump'
import { errorMessage } from '@/utils/oa'
const { t } = useI18n()
const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()
const appStore = useAppStore()
const phase = ref<'working' | 'failed'>('working')
@ -87,26 +95,15 @@ const message = ref('')
const portalUrl = ref('')
/** 后端回调带回来的稳定原因码,只用于排障展示。 */
const errorCode = ref('')
/** 这一趟落地带来的到底是哪一样东西,决定屏上的话说哪一句。 */
const entryKind = ref<'ticket' | 'code' | 'error' | 'none'>('none')
/** 免登这一趟的工作说明:交票据与兑短码是两件事,别说成一件。 */
const workingText = computed(() => (entryKind.value === 'code' ? t('auth.ssoWorkingCode') : t('auth.ssoWorking')))
// 应急入口默认不画出来:只有地址上明确写了 ?local=1 才给一次跳去本地口令表单的机会
const breakGlass = computed(() => route.query.local === '1')
function scrubTicketFromUrl(): void {
// 换完会话后把票据与 state 从地址栏抹掉;用 replaceState 免得后退又能看到票据。
window.history.replaceState({}, document.title, window.location.pathname)
}
function targetPath(sessionRedirect = ''): string {
// 来路三个来源按顺位取:后端回调带回来的 > 地址栏上的 > 跳去门户之前自己存的那一份
// (Hub 一期不解析 redirect,登录页无感跳出去时把来路暂存在了 ssoJump 里)
const wanted = firstText(sessionRedirect) || firstText(route.query.redirect) || takeReturnPath()
// 只认站内路径:`//` 与 `/\` 这类写法会被浏览器送去另一台主机
return safeRedirect(wanted)
function failureText(result: SsoLandingResult): string {
// 后端原话优先(换会话被拒时已经是一句人话),其次照稳定原因码查语言包,最后才是"没有凭证"
if (result.status !== 'failed') return ''
if (result.message) return result.message
if (result.reason) return t(ssoErrorKey(result.reason))
return t('auth.ssoNoTicket')
}
async function toPortal() {
@ -119,63 +116,24 @@ async function toPortal() {
}
}
function toLocalLogin() {
function toLocalLogin(): void {
void router.replace({ name: 'login', query: { local: '1' } })
}
/** 后端回调把一次性短码放在 ``#`` 后面;顺手也认 ``?code=``,免得有人手抄地址时丢掉片段。 */
function sessionCode(): string {
const fragment = String(route.hash || '').replace(/^#/, '')
const fromHash = new URLSearchParams(fragment).get('code') || ''
const fromQuery = typeof route.query.code === 'string' ? route.query.code : ''
return String(fromHash || fromQuery).trim()
}
function firstText(value: unknown): string {
return typeof value === 'string' ? value.trim() : ''
}
function fail(reason: string, text: string): void {
errorCode.value = reason
phase.value = 'failed'
message.value = text
}
async function run() {
const ticket = firstText(route.query.ticket)
const state = firstText(route.query.state)
const code = sessionCode()
const errorReason = firstText(route.query.error)
entryKind.value = errorReason ? 'error' : code ? 'code' : ticket ? 'ticket' : 'none'
// 守卫已经等过一趟,这里的 await 通常当场就有结果;凭证与守卫看到的是同一个,
// 所以绝不会因此多发一次请求(ssoLanding 认凭证原文,一个凭证只兑一次)。
const result = await startSsoLanding(route.fullPath)
if (result.status === 'ok') {
await router.replace(result.path)
return
}
// 只有站得住这一屏的人才需要门户地址:成功进站的人一趟请求都不该为它多付
const settings = await appStore.fetchPublicSettings()
portalUrl.value = String(settings?.hub?.portal_url || '')
// 后端已经替我们问过 Hub 了:这里只照原因码说一句话,一次请求都不再发
if (errorReason) {
fail(errorReason, t(ssoErrorKey(errorReason)))
return
}
if (entryKind.value === 'none') {
fail('', t('auth.ssoNoTicket'))
return
}
try {
if (entryKind.value === 'code') {
const session = await authStore.loginWithCode(code)
scrubTicketFromUrl()
resetAutoJumpBudget()
await router.replace(targetPath(session.redirect))
return
}
await authStore.loginWithTicket(ticket, state)
scrubTicketFromUrl()
resetAutoJumpBudget()
await router.replace(targetPath())
} catch (error) {
// 失败一律不再试第二次:票据与短码都是一次性的,重试只会得到同样的拒绝。
scrubTicketFromUrl()
fail('', errorMessage(error))
}
errorCode.value = result.status === 'failed' ? result.reason : ''
message.value = failureText(result)
phase.value = 'failed'
}
onMounted(run)

View File

@ -48,8 +48,10 @@ function injectBranding(html: string, config: { site_name?: string; site_logo?:
}
/**
* Vite 插件:开发模式下注入公开配置到 index.html
* 与生产模式的后端注入行为保持一致,消除闪烁
* Vite 插件:开发模式下注入公开配置到 index.html,与生产那一口同一件事——
* 生产由后端发页时注(backend/app/web_shell.py,两份内容同取 app/public_config.py),
* 画第一笔之前浏览器就知道这一档是免登还是账号密码,不必先问一次 /settings/public
* 再决定画哪一屏。改这里记得同时看那一头。
*/
function injectPublicSettings(backendUrl: string): Plugin {
return {