Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat: decouple enterprise login and make auth simulation pluggable

ZYQ5333a80e45c50714
diff --git a/deploy/enterprise/.env.example b/deploy/enterprise/.env.example
index 79e1c1354e..49fb536c98 100644
--- a/deploy/enterprise/.env.example
+++ b/deploy/enterprise/.env.example
@@ -455,12 +455,24 @@ MANAGER_WEB_IMAGE=""
# 控制是否启动Manager 前端模块
IS_UP_MANAGER_WEB=false
-# 用户面产品形态:personal 或 enterprise
-# personal:通过 User Web NodePort 提供独立用户面
-# enterprise:通过 Manager Web 统一登录并内嵌用户面,不暴露 User Web NodePort
-# enterprise 模式必须同时设置 IS_UP_MANAGER_WEB=true
+# 用户面产品形态:personal 或 enterprise;两种模式均通过 User Web NodePort 独立提供。
+# personal:跳过企业登录;enterprise:启用企业登录及用户/组织/组网/Agent 面板。
USER_WEB_MODE=personal
+# 是否模拟企业登录认证。默认 true,使用内置调试身份和三元组,不访问客户身份服务。
+# false:正式身份认证模式,依赖客户侧 manager ID 认证服务。
+# personal 模式始终跳过企业登录,此参数仅在 enterprise 模式生效。
+LOGIN_AUTH_SIMULATE=true
+
+# 当前 User Web 制品是否包含可选的认证模拟插件。内部联调制品为 true;
+# 客户正式制品构建时设为 false,且必须同时设置 LOGIN_AUTH_SIMULATE=false。
+LOGIN_AUTH_SIMULATE_AVAILABLE=true
+
+# 正式模式依赖的认证及 Manager 业务接口。留空时暂时使用部署工具现有的集群内
+# jiuwenclaw-identity 和 jiuwenclaw-manager-server;客户接口就绪后改为客户地址。
+USER_WEB_IDP_TARGET=""
+USER_WEB_MANAGER_TARGET=""
+
# 已废弃,仅兼容旧配置;新部署请使用 USER_WEB_MODE
# ENABLE_USER_WEB_EMBEDDING=false
diff --git a/deploy/enterprise/README.md b/deploy/enterprise/README.md
index a7060cd820..456b3ac4b4 100644
--- a/deploy/enterprise/README.md
+++ b/deploy/enterprise/README.md
@@ -675,26 +675,55 @@ Web 为 JiuwenSwarm 企业版面向终端用户的对话可视化前端,用于
用户面通过 `USER_WEB_MODE` 选择产品形态:
```bash
-# personal:通过 User Web NodePort 提供独立用户面
-# enterprise:通过 Manager Web 统一登录并内嵌用户面,不暴露 User Web NodePort
+# personal:独立用户面,跳过企业登录
+# enterprise:独立用户面,启用企业登录和用户上下文面板
USER_WEB_MODE=personal
```
-`personal` 模式下,用户通过 User Web NodePort 直接使用独立用户面。`enterprise`
-模式下,Manager Web 是唯一对外入口:用户先通过 Identity Center 登录,在 Manager Web
-中选择组网、组织和 Bot,再进入同源 `/chat/` 内嵌用户面。User Web 仍保留供 Manager Web
-访问的 ClusterIP 服务,但部署脚本不会创建其 NodePort;enterprise 模式必须部署 Manager Web:
+登录认证模拟由独立参数控制:
```bash
-USER_WEB_MODE=enterprise
-IS_UP_MANAGER_WEB=true
+# 默认 true:企业模式使用 debug-user/debug-group/debug-gateway/debug-agent,
+# 不请求 Identity/Manager 用户目录接口。
+LOGIN_AUTH_SIMULATE=true
+
+# 正式模式:调用客户侧 manager 提供的 ID 认证和用户目录接口。
+LOGIN_AUTH_SIMULATE=false
+
+# 暂未配置客户接口时可以留空,部署工具会回落到当前集群内 Identity/Manager。
+USER_WEB_IDP_TARGET=""
+USER_WEB_MANAGER_TARGET=""
```
+`LOGIN_AUTH_SIMULATE` 仅接受 `true` 或 `false`。在 `personal` 模式下用户面始终跳过
+企业登录;若同时配置 `LOGIN_AUTH_SIMULATE=false`,部署和启动日志会提示该参数冲突且
+不会改变 personal 行为。正式模式启动时会分别检查 ID 认证服务和 Manager 业务接口的
+连通性并输出明确日志。
+
+认证模拟实现按插件装配。内部联调制品保持 `LOGIN_AUTH_SIMULATE_AVAILABLE=true`;
+客户正式制品使用前端 `npm run build:customer` 构建,并配置
+`LOGIN_AUTH_SIMULATE_AVAILABLE=false`、`LOGIN_AUTH_SIMULATE=false`。客户构建不会将
+`src/auth/simulate/` 内的默认用户和三元组实现打入静态产物,该目录也可从客户源码包
+直接剥离。若不含插件的制品误开模拟认证,部署检查和 User Web 启动均会明确拒绝启动。
+
+`personal` 和 `enterprise` 均通过 User Web NodePort 提供独立入口,不要求部署 Manager Web。
+`enterprise` 仅控制企业登录及用户、组织、组网、Agent 上下文面板。模拟模式完全不依赖
+Manager;正式模式保留对 Manager ID 认证及业务目录接口的调用。
+
+当前客户接口尚未提供时,目标地址留空会使用以下集群内默认值:
+
+```bash
+USER_WEB_IDP_TARGET=http://jiuwenclaw-identity:8770
+USER_WEB_MANAGER_TARGET=http://jiuwenclaw-manager-server:8765
+```
+
+这两个组件仅作为现阶段正式模式联调后端,可通过 `./deploy.sh up manager` 单独部署;
+无参数默认交付不再部署 Manager。客户接口就绪后,只需覆盖两个目标地址,不改变现有接口路径。
+
旧配置 `ENABLE_USER_WEB_EMBEDDING` 仅作兼容输入:`true` 等价于
`USER_WEB_MODE=enterprise`,`false` 等价于 `USER_WEB_MODE=personal`。新部署不应继续使用。
-Manager Web 内嵌入口使用以下同源路由,不需要额外暴露 Identity、Manager Server 或
-Gateway:
+User Web 使用以下同源代理路由访问认证、Manager 业务接口和 Gateway:
| 路径 | 目标服务 | 用途 |
|---|---|---|
@@ -703,6 +732,7 @@ Gateway:
| `/chat/*` | User Web HTTP | 用户面对话界面 |
| `/ws*` | Gateway WebSocket | 用户面默认消息通道 |
| `/gateway-api/*` | Gateway Web HTTP/SSE | 用户面 REST/SSE 通道,与 Manager `/api/v1` 隔离 |
+
| `/file-api/*`、`/share-api/*` | Gateway Web HTTP | 文件与分享接口 |
Manager Web 与 `/chat/` 使用同一浏览器源,登录状态由 Manager Web 统一管理。User Web
diff --git a/deploy/enterprise/args_handler.sh b/deploy/enterprise/args_handler.sh
index 55c8c8c778..1de2c6e27b 100755
--- a/deploy/enterprise/args_handler.sh
+++ b/deploy/enterprise/args_handler.sh
@@ -51,7 +51,7 @@ parse_args() {
}
process_modules() {
- MODULES=("GATEWAY" "WEB" "MANAGER" "RUNTIME")
+ MODULES=("GATEWAY" "WEB" "RUNTIME")
}
# Print help info and exit
diff --git a/deploy/enterprise/check_handler.sh b/deploy/enterprise/check_handler.sh
index 73f4e90e74..b43d84372a 100755
--- a/deploy/enterprise/check_handler.sh
+++ b/deploy/enterprise/check_handler.sh
@@ -23,8 +23,21 @@ check_user_web_mode_config() {
error "USER_WEB_MODE must be personal or enterprise, current value: ${mode}"
fi
check_boolean_value "IS_UP_MANAGER_WEB"
- if [[ "${mode}" == "enterprise" && "${DEPLOY_VARS["IS_UP_MANAGER_WEB"]}" != "true" ]]; then
- error "USER_WEB_MODE=enterprise requires IS_UP_MANAGER_WEB=true"
+ check_boolean_value "LOGIN_AUTH_SIMULATE"
+ check_boolean_value "LOGIN_AUTH_SIMULATE_AVAILABLE"
+ if [[ "${mode}" == "enterprise" && "${DEPLOY_VARS["LOGIN_AUTH_SIMULATE"]}" == "true" && "${DEPLOY_VARS["LOGIN_AUTH_SIMULATE_AVAILABLE"]}" == "false" ]]; then
+ error "配置冲突:LOGIN_AUTH_SIMULATE=true,但当前客户交付制品未包含登录认证模拟插件;请设置 LOGIN_AUTH_SIMULATE=false"
+ fi
+ if [[ "${mode}" == "personal" && "${DEPLOY_VARS["LOGIN_AUTH_SIMULATE"]}" == "false" ]]; then
+ warning "配置冲突:USER_WEB_MODE=personal 始终跳过企业登录;LOGIN_AUTH_SIMULATE=false 不会启用正式身份认证"
+ fi
+ if [[ "${mode}" == "enterprise" && "${DEPLOY_VARS["LOGIN_AUTH_SIMULATE"]}" == "false" ]]; then
+ if [[ -z "${DEPLOY_VARS["USER_WEB_IDP_TARGET"]:-}" ]]; then
+ error "正式身份认证模式缺少 USER_WEB_IDP_TARGET"
+ fi
+ if [[ -z "${DEPLOY_VARS["USER_WEB_MANAGER_TARGET"]:-}" ]]; then
+ error "正式身份认证模式缺少 USER_WEB_MANAGER_TARGET"
+ fi
fi
}
@@ -444,13 +457,6 @@ check_gateway_up_dependency(){
check_web_up_dependency(){
check_user_web_mode_config
- if [ "${DEPLOY_VARS["USER_WEB_MODE"]}" == "enterprise" ] \
- && ! module_is_selected "MANAGER"; then
- if ! check_k8s_resource_exists \
- "deployment" "${DEPLOY_VARS["MANAGER_WEB_NAME"]}" "${DEPLOY_VARS["NAMESPACE"]}"; then
- error "Enterprise User Web requires the Manager Web module to be deployed"
- fi
- fi
check_if_db_up
check_if_obs_up
@@ -461,13 +467,6 @@ check_web_up_dependency(){
check_manager_up_dependency(){
check_user_web_mode_config
- if [ "${DEPLOY_VARS["USER_WEB_MODE"]}" == "enterprise" ] \
- && ! module_is_selected "WEB"; then
- if ! check_k8s_resource_exists \
- "deployment" "${DEPLOY_VARS["WEB_NAME"]}" "${DEPLOY_VARS["NAMESPACE"]}"; then
- error "Enterprise User Web requires the Web module to be deployed"
- fi
- fi
#check_if_rabbitmq_up
check_if_db_up
}
diff --git a/deploy/enterprise/deploy.sh b/deploy/enterprise/deploy.sh
index b6c698eb94..9da9d38486 100755
--- a/deploy/enterprise/deploy.sh
+++ b/deploy/enterprise/deploy.sh
@@ -105,6 +105,34 @@ main() {
DEPLOY_VARS["ENABLE_USER_WEB_EMBEDDING"]=$(
[[ "${DEPLOY_VARS["USER_WEB_MODE"]}" == "enterprise" ]] && printf true || printf false
)
+ if [[ -z "${DEPLOY_VARS["LOGIN_AUTH_SIMULATE"]:-}" ]]; then
+ DEPLOY_VARS["LOGIN_AUTH_SIMULATE"]="true"
+ fi
+ local user_web_idp_defaulted="false"
+ local user_web_manager_defaulted="false"
+ if [[ -z "${DEPLOY_VARS["USER_WEB_IDP_TARGET"]:-}" ]]; then
+ DEPLOY_VARS["USER_WEB_IDP_TARGET"]="http://${DEPLOY_VARS["IDENTITY_NAME"]}:${DEPLOY_VARS["IDENTITY_REST_PORT"]}"
+ user_web_idp_defaulted="true"
+ fi
+ if [[ -z "${DEPLOY_VARS["USER_WEB_MANAGER_TARGET"]:-}" ]]; then
+ DEPLOY_VARS["USER_WEB_MANAGER_TARGET"]="http://${DEPLOY_VARS["MANAGER_SERVER_NAME"]}:${DEPLOY_VARS["MANAGER_REST_PORT"]}"
+ user_web_manager_defaulted="true"
+ fi
+ if [[ "${DEPLOY_VARS["USER_WEB_MODE"]}" == "enterprise" ]]; then
+ if [[ "${DEPLOY_VARS["LOGIN_AUTH_SIMULATE"]}" == "true" ]]; then
+ info "【登录认证模拟调试模式已开启】"
+ elif [[ "${DEPLOY_VARS["LOGIN_AUTH_SIMULATE"]}" == "false" ]]; then
+ info "【正式身份认证模式,依赖manager ID认证服务】"
+ if [[ "${user_web_idp_defaulted}" == "true" ]]; then
+ info "USER_WEB_IDP_TARGET 未配置,暂使用当前集群 Identity:${DEPLOY_VARS["USER_WEB_IDP_TARGET"]}"
+ fi
+ if [[ "${user_web_manager_defaulted}" == "true" ]]; then
+ info "USER_WEB_MANAGER_TARGET 未配置,暂使用当前集群 Manager:${DEPLOY_VARS["USER_WEB_MANAGER_TARGET"]}"
+ fi
+ fi
+ elif [[ "${DEPLOY_VARS["LOGIN_AUTH_SIMULATE"]}" == "false" ]]; then
+ warning "配置冲突:personal 模式仍将跳过企业登录认证"
+ fi
parse_args "$@"
detect_os
diff --git a/deploy/enterprise/global_vars.sh b/deploy/enterprise/global_vars.sh
index 44b719ad94..4c28c748ca 100755
--- a/deploy/enterprise/global_vars.sh
+++ b/deploy/enterprise/global_vars.sh
@@ -122,6 +122,10 @@ declare -A DEPLOY_VARS=(
["ENABLE_EXTERNAL_RABBITMQ"]="false"
["ENABLE_EXTERNAL_REDIS"]="false"
["USER_WEB_MODE"]=""
+ ["LOGIN_AUTH_SIMULATE"]="true"
+ ["LOGIN_AUTH_SIMULATE_AVAILABLE"]="true"
+ ["USER_WEB_IDP_TARGET"]=""
+ ["USER_WEB_MANAGER_TARGET"]=""
["ENABLE_USER_WEB_EMBEDDING"]="false"
["FLUENT_BIT_NAME"]="fluent-bit"
["FLUENT_BIT_IMAGE"]="fluent/fluent-bit:3.0.0"
@@ -144,7 +148,7 @@ declare -A DEPLOY_VARS=(
["GATEWAY_PG_SCHEMA"]="public"
["GATEWAY_REPLICAS"]="1"
["GATEWAY_SQLITE_PATH"]="gateway.db"
- ["IS_UP_MANAGER_WEB"]="true"
+ ["IS_UP_MANAGER_WEB"]="false"
["IDENTITY_NAME"]="jiuwenclaw-identity"
["IDENTITY_REST_PORT"]="8770"
["IDENTITY_DB_NAME"]="identity"
diff --git a/deploy/enterprise/manager_handler.sh b/deploy/enterprise/manager_handler.sh
index 647da55478..8d68719033 100755
--- a/deploy/enterprise/manager_handler.sh
+++ b/deploy/enterprise/manager_handler.sh
@@ -87,15 +87,6 @@ deploy_manager() {
wait_k8s_resource_ready "deployment" "${manager_web_name}" "${namespace}"
success "MANAGER_WEB_NODE_PORT: ${DEPLOY_VARS["MANAGER_WEB_NODE_PORT"]}"
- # WEB 先于 MANAGER 渲染时无法知道 Manager Web 的 NodePort。
- # Manager 就绪后重新渲染并应用 User Web,端口由 kubectl 实时读取。
- if [ "${DEPLOY_VARS["USER_WEB_MODE"]}" == "enterprise" ] \
- && module_is_selected "WEB"; then
- # WEB 已经在前面分配过 NodePort;这里只重新渲染登录跳转地址,
- # 不能再次调用 ensure_available_port,否则会把自身端口判定为冲突。
- gen_web_file
- deploy_web
- fi
fi
}
diff --git a/deploy/enterprise/templates/web.template.yaml b/deploy/enterprise/templates/web.template.yaml
index 9153a0e381..70b5c0f06c 100644
--- a/deploy/enterprise/templates/web.template.yaml
+++ b/deploy/enterprise/templates/web.template.yaml
@@ -40,10 +40,18 @@ spec:
value: "<<USER_WEB_MODE>>"
- name: VITE_ENABLE_USER_WEB_EMBEDDING
value: "<<ENABLE_USER_WEB_EMBEDDING>>"
+ - name: LOGIN_AUTH_SIMULATE
+ value: "<<LOGIN_AUTH_SIMULATE>>"
+ - name: VITE_LOGIN_AUTH_SIMULATE
+ value: "<<LOGIN_AUTH_SIMULATE>>"
+ - name: LOGIN_AUTH_SIMULATE_AVAILABLE
+ value: "<<LOGIN_AUTH_SIMULATE_AVAILABLE>>"
+ - name: VITE_LOGIN_AUTH_SIMULATE_AVAILABLE
+ value: "<<LOGIN_AUTH_SIMULATE_AVAILABLE>>"
- name: USER_WEB_IDP_TARGET
- value: "http://<<IDENTITY_NAME>>:<<IDENTITY_REST_PORT>>"
+ value: "<<USER_WEB_IDP_TARGET>>"
- name: USER_WEB_MANAGER_TARGET
- value: "http://<<MANAGER_SERVER_NAME>>:<<MANAGER_REST_PORT>>"
+ value: "<<USER_WEB_MANAGER_TARGET>>"
- name: FRONTEND_PORT
value: "<<WEB_HTTP_PORT>>"
- name: VITE_WEB_TRANSPORT
diff --git a/deploy/enterprise/tests/test_identity_user_web_deploy.sh b/deploy/enterprise/tests/test_identity_user_web_deploy.sh
index fd091667d6..de03c98d84 100755
--- a/deploy/enterprise/tests/test_identity_user_web_deploy.sh
+++ b/deploy/enterprise/tests/test_identity_user_web_deploy.sh
@@ -5,6 +5,7 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
source "${SCRIPT_DIR}/common.sh"
source "${SCRIPT_DIR}/global_vars.sh"
+source "${SCRIPT_DIR}/args_handler.sh"
source "${SCRIPT_DIR}/cmd_handler.sh"
source "${SCRIPT_DIR}/envfile_handler.sh"
source "${SCRIPT_DIR}/template_handler.sh"
@@ -33,6 +34,11 @@ assert_equal() {
main() {
check_cmd "yq"
+ MODULES=()
+ process_modules
+ assert_equal "GATEWAY WEB RUNTIME" "${MODULES[*]}" "default delivery must exclude Manager"
+ MODULES=()
+
TEST_DIR="$(mktemp -d)"
local test_dir="${TEST_DIR}"
trap cleanup EXIT
@@ -72,17 +78,25 @@ main() {
DEPLOY_VARS["ENABLE_USER_WEB_EMBEDDING"]="true"
gen_web_file
assert_equal \
- "0" \
- "$(yq eval-all '[select(.metadata.name == "jiuwenclaw-web-nodeport")] | length' "${CONFIG["WEB_FILE"]}")" \
- "enterprise mode must not expose the User Web NodePort"
+ "NodePort" \
+ "$(yq eval-all 'select(.metadata.name == "jiuwenclaw-web-nodeport") | .spec.type' "${CONFIG["WEB_FILE"]}")" \
+ "enterprise mode must expose the independent User Web NodePort"
DEPLOY_VARS["IS_UP_MANAGER_WEB"]="false"
- if (check_user_web_mode_config) >/dev/null 2>&1; then
- echo "FAIL: embedded mode must require Manager Web" >&2
- exit 1
- fi
+ DEPLOY_VARS["USER_WEB_IDP_TARGET"]="http://jiuwenclaw-identity:8770"
+ DEPLOY_VARS["USER_WEB_MANAGER_TARGET"]="http://jiuwenclaw-manager-server:8765"
+ check_user_web_mode_config
DEPLOY_VARS["IS_UP_MANAGER_WEB"]="true"
+ DEPLOY_VARS["LOGIN_AUTH_SIMULATE"]="true"
+ check_user_web_mode_config
+
+ DEPLOY_VARS["LOGIN_AUTH_SIMULATE"]="invalid"
+ if check_user_web_mode_config >/dev/null 2>&1; then
+ echo "FAIL: invalid LOGIN_AUTH_SIMULATE value must be rejected" >&2
+ exit 1
+ fi
+ DEPLOY_VARS["LOGIN_AUTH_SIMULATE"]="false"
check_user_web_mode_config
DEPLOY_VARS["USER_WEB_MODE"]="invalid"
diff --git a/deploy/enterprise/web_handler.sh b/deploy/enterprise/web_handler.sh
index 2a9e44b491..056fcdab6b 100755
--- a/deploy/enterprise/web_handler.sh
+++ b/deploy/enterprise/web_handler.sh
@@ -9,11 +9,6 @@ gen_web_file() {
render_config_template "${template_file}" "${file}" "DEPLOY_VARS"
- if [ "${DEPLOY_VARS["USER_WEB_MODE"]}" == "enterprise" ]; then
- local nodeport_name="${DEPLOY_VARS["WEB_NAME"]}-nodeport"
- yq eval 'select(.metadata.name != "'"${nodeport_name}"'")' -i "${file}"
- fi
-
if [ "${DEPLOY_VARS["ENABLE_EXTERNAL_OBS"]}" == "true" ]; then
obs_url="${DEPLOY_VARS["OBS_URL"]}"
fi
@@ -57,9 +52,7 @@ gen_web_file() {
render_web_files() {
render_secret_configmap
- if [ "${DEPLOY_VARS["USER_WEB_MODE"]}" != "enterprise" ]; then
- ensure_available_port "WEB_NODE_PORT"
- fi
+ ensure_available_port "WEB_NODE_PORT"
gen_web_file
}
@@ -71,12 +64,7 @@ deploy_web() {
ensure_secret_configmap
exec_cmd kubectl apply -f ${file}
wait_k8s_resource_ready "deployment" "${name}" "${namespace}"
- if [ "${DEPLOY_VARS["USER_WEB_MODE"]}" == "enterprise" ]; then
- delete_k8s_resource "service" "${name}-nodeport" "${namespace}"
- success "User Web is available through Manager Web; standalone NodePort is disabled"
- else
- success "WEB_NODE_PORT: ${DEPLOY_VARS["WEB_NODE_PORT"]}"
- fi
+ success "WEB_NODE_PORT: ${DEPLOY_VARS["WEB_NODE_PORT"]}"
}
uninstall_web() {
diff --git a/jiuwenswarm/channels/web/app_web.py b/jiuwenswarm/channels/web/app_web.py
index 274d9dcc75..2ecf239ce7 100644
--- a/jiuwenswarm/channels/web/app_web.py
+++ b/jiuwenswarm/channels/web/app_web.py
@@ -68,11 +68,73 @@ def _default_dist_dir() -> Path:
return dist_dir
-def _inject_user_web_runtime_config(document: str, mode: str) -> str:
+def _inject_user_web_runtime_config(
+ document: str,
+ mode: str,
+ login_auth_simulate: bool = True,
+ login_auth_simulate_available: bool = True,
+) -> str:
"""Inject runtime mode values without modifying JavaScript property names."""
- return document.replace("__JIUWEN_USER_WEB_MODE_VALUE__", mode).replace(
- "__JIUWEN_USER_WEB_EMBEDDING_VALUE__",
- "true" if mode == "enterprise" else "false",
+ return (
+ document.replace("__JIUWEN_USER_WEB_MODE_VALUE__", mode)
+ .replace(
+ "__JIUWEN_USER_WEB_EMBEDDING_VALUE__",
+ "true" if mode == "enterprise" else "false",
+ )
+ .replace(
+ "__JIUWEN_LOGIN_AUTH_SIMULATE_VALUE__",
+ "true" if login_auth_simulate else "false",
+ )
+ .replace(
+ "__JIUWEN_LOGIN_AUTH_SIMULATE_AVAILABLE_VALUE__",
+ "true" if login_auth_simulate_available else "false",
+ )
+ )
+
+
+def _parse_login_auth_simulate(raw: str | None) -> bool:
+ value = "true" if raw is None or not raw.strip() else raw.strip().lower()
+ if value == "true":
+ return True
+ if value == "false":
+ return False
+ raise ValueError(
+ f"LOGIN_AUTH_SIMULATE 配置非法:期望 true 或 false,实际为 {raw!r}"
+ )
+
+
+def _probe_http_service(
+ target: str, path: str, service_name: str, timeout: float = 3.0
+) -> tuple[bool, str]:
+ """Probe an authentication dependency; 401/403 still prove reachability."""
+ parsed = urlparse(target)
+ if parsed.scheme not in {"http", "https"} or not parsed.hostname:
+ return False, f"{service_name}地址非法:{target!r}"
+ connection_cls = (
+ http.client.HTTPSConnection if parsed.scheme == "https" else http.client.HTTPConnection
+ )
+ connection = connection_cls(parsed.hostname, parsed.port, timeout=timeout)
+ base_path = parsed.path.rstrip("/")
+ try:
+ connection.request("GET", f"{base_path}{path}")
+ response = connection.getresponse()
+ response.read()
+ if response.status >= 500:
+ return False, f"{service_name}返回 HTTP {response.status}"
+ return True, f"HTTP {response.status}"
+ except (OSError, http.client.HTTPException) as exc:
+ return False, str(exc)
+ finally:
+ connection.close()
+
+
+def _probe_identity_service(target: str, timeout: float = 3.0) -> tuple[bool, str]:
+ return _probe_http_service(target, "/v1/auth/me", "ID认证服务", timeout)
+
+
+def _probe_manager_service(target: str, timeout: float = 3.0) -> tuple[bool, str]:
+ return _probe_http_service(
+ target, "/api/v1/user-console/gateways", "Manager业务接口", timeout
)
@@ -97,6 +159,8 @@ class _SpaStaticHandler(SimpleHTTPRequestHandler):
ws_disable_compress = False
embedding_enabled = False
user_web_mode = "personal"
+ login_auth_simulate = True
+ login_auth_simulate_available = True
logger = logging.getLogger(__name__)
_HOP_BY_HOP_HEADERS = {
@@ -627,7 +691,10 @@ class _SpaStaticHandler(SimpleHTTPRequestHandler):
if self._is_document_request():
index = Path(self.directory or os.getcwd()) / "index.html"
body = _inject_user_web_runtime_config(
- index.read_text(encoding="utf-8"), self.user_web_mode
+ index.read_text(encoding="utf-8"),
+ self.user_web_mode,
+ self.login_auth_simulate,
+ self.login_auth_simulate_available,
).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
@@ -863,6 +930,24 @@ def main() -> None:
legacy_embedding = os.getenv("ENABLE_USER_WEB_EMBEDDING", "")
configured_mode = "enterprise" if legacy_embedding.strip().lower() == "true" else "personal"
_ConfiguredHandler.user_web_mode = configured_mode
+ login_auth_simulate_raw = os.getenv("LOGIN_AUTH_SIMULATE")
+ login_auth_simulate_available_raw = os.getenv("LOGIN_AUTH_SIMULATE_AVAILABLE")
+ try:
+ login_auth_simulate = _parse_login_auth_simulate(
+ login_auth_simulate_raw
+ )
+ login_auth_simulate_available = _parse_login_auth_simulate(
+ login_auth_simulate_available_raw
+ )
+ except ValueError as exc:
+ raise SystemExit(str(exc)) from exc
+ _ConfiguredHandler.login_auth_simulate = login_auth_simulate
+ _ConfiguredHandler.login_auth_simulate_available = login_auth_simulate_available
+ if configured_mode == "enterprise" and login_auth_simulate and not login_auth_simulate_available:
+ raise SystemExit(
+ "配置冲突:LOGIN_AUTH_SIMULATE=true,但当前客户交付制品未包含登录认证模拟插件;"
+ "请设置 LOGIN_AUTH_SIMULATE=false 并接入 manager ID认证服务"
+ )
_ConfiguredHandler.embedding_enabled = configured_mode == "enterprise"
_ConfiguredHandler.web_http_target = web_http_target
_ConfiguredHandler.ws_disable_compress = args.ws_disable_compress
@@ -871,6 +956,50 @@ def main() -> None:
server = ThreadingHTTPServer((args.host, args.port), handler)
logger.info("[jiuwenswarm-web] serving %s", dist_dir)
+ if login_auth_simulate_raw is None or not login_auth_simulate_raw.strip():
+ logger.info(
+ "[jiuwenswarm-web] LOGIN_AUTH_SIMULATE 未配置,按默认值 true 启用登录认证模拟调试"
+ )
+ if configured_mode == "personal":
+ logger.info("[jiuwenswarm-web] personal 模式:跳过企业登录认证")
+ if not login_auth_simulate:
+ logger.warning(
+ "[jiuwenswarm-web] 配置冲突:USER_WEB_MODE=personal 时 "
+ "LOGIN_AUTH_SIMULATE 不参与登录流程,personal 模式仍跳过企业认证"
+ )
+ elif login_auth_simulate:
+ logger.info("[jiuwenswarm-web] 【登录认证模拟调试模式已开启】")
+ else:
+ logger.info(
+ "[jiuwenswarm-web] 【正式身份认证模式,依赖manager ID认证服务】"
+ )
+ missing_targets = []
+ if not _ConfiguredHandler.idp_target:
+ missing_targets.append("USER_WEB_IDP_TARGET")
+ if not _ConfiguredHandler.manager_api_target:
+ missing_targets.append("USER_WEB_MANAGER_TARGET")
+ if missing_targets:
+ logger.error(
+ "[jiuwenswarm-web] 正式登录模式缺少 %s;请配置 manager 认证及业务接口地址",
+ "、".join(missing_targets),
+ )
+ else:
+ probes = (
+ ("manager ID认证服务", "USER_WEB_IDP_TARGET", _probe_identity_service, _ConfiguredHandler.idp_target),
+ ("Manager业务接口", "USER_WEB_MANAGER_TARGET", _probe_manager_service, _ConfiguredHandler.manager_api_target),
+ )
+ for service_name, config_name, probe, target in probes:
+ reachable, detail = probe(target)
+ if reachable:
+ logger.info("[jiuwenswarm-web] %s连通性检查通过:%s", service_name, detail)
+ else:
+ logger.error(
+ "[jiuwenswarm-web] 当前为正式登录模式,%s暂不可用(%s);"
+ "请检查 %s、网络和服务状态",
+ service_name,
+ detail,
+ config_name,
+ )
logger.info("[jiuwenswarm-web] http://%s:%s", args.host, args.port)
logger.info("[jiuwenswarm-web] /api -> %s", api_target)
logger.info("[jiuwenswarm-web] /ws -> %s", ws_target)
diff --git a/jiuwenswarm/channels/web/frontend/index.html b/jiuwenswarm/channels/web/frontend/index.html
index 7c6f230ee3..62de7d973f 100644
--- a/jiuwenswarm/channels/web/frontend/index.html
+++ b/jiuwenswarm/channels/web/frontend/index.html
@@ -13,6 +13,8 @@
<script>
window.__JIUWEN_USER_WEB_MODE__ = '__JIUWEN_USER_WEB_MODE_VALUE__';
window.__JIUWEN_USER_WEB_EMBEDDING__ = '__JIUWEN_USER_WEB_EMBEDDING_VALUE__' === 'true';
+ window.__JIUWEN_LOGIN_AUTH_SIMULATE__ = '__JIUWEN_LOGIN_AUTH_SIMULATE_VALUE__';
+ window.__JIUWEN_LOGIN_AUTH_SIMULATE_AVAILABLE__ = '__JIUWEN_LOGIN_AUTH_SIMULATE_AVAILABLE_VALUE__';
</script>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
diff --git a/jiuwenswarm/channels/web/frontend/package.json b/jiuwenswarm/channels/web/frontend/package.json
index 67d9f11125..c22e5ffcad 100644
--- a/jiuwenswarm/channels/web/frontend/package.json
+++ b/jiuwenswarm/channels/web/frontend/package.json
@@ -8,6 +8,7 @@
"prebuild": "cd ../../../.. && node ./jiuwenswarm/scripts/generate-agent-folders.js",
"dev": "vite",
"build": "tsc && vite build",
+ "build:customer": "tsc && INCLUDE_LOGIN_AUTH_SIMULATE=false VITE_LOGIN_AUTH_SIMULATE_AVAILABLE=false VITE_LOGIN_AUTH_SIMULATE=false vite build",
"test:code-turn-diff-binding": "tsc src/features/code-mode/codeTurnDiffBinding.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/code-turn-diff-binding --skipLibCheck --noEmitOnError && node --test tests/codeTurnDiffBinding.test.mjs",
"test:openai-account-model-state": "tsc src/components/ConfigPanel/openaiAccountModelState.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/openai-account-model-state --skipLibCheck && node --test tests/openaiAccountModelState.test.mjs",
"test:spreadsheet-preview": "esbuild src/components/ArtifactsPanel/spreadsheetWorkbookParser.ts src/components/ArtifactsPanel/spreadsheetPreviewModel.ts src/components/ArtifactsPanel/filePreviewModel.ts src/components/ArtifactsPanel/chartGeometry.ts --bundle --packages=external --platform=node --format=esm --outdir=node_modules/.cache/spreadsheet-preview && node --test tests/spreadsheetPreview.test.mjs",
@@ -22,7 +23,7 @@
"test:file-download-dedup": "tsc src/utils/fileDownloadDedup.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/file-download-dedup --skipLibCheck --noEmitOnError && node --test tests/fileDownloadDedup.test.mjs",
"test:web-http-client": "tsc src/services/webHttpClient.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/web-http-client --skipLibCheck --noEmitOnError && node --test tests/webHttpClient.test.mjs",
"test:runtime-scope": "tsc src/services/runtimeScope.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/runtime-scope --skipLibCheck --noEmitOnError && node --test tests/runtimeScope.test.mjs",
- "test:user-web-entry": "esbuild src/EnterpriseEntry.tsx --bundle --packages=external --platform=node --format=esm --outfile=node_modules/.cache/user-web-entry/EnterpriseEntry.mjs --define:import.meta.env.VITE_USER_WEB_MODE='\"personal\"' --define:import.meta.env.VITE_ENABLE_USER_WEB_EMBEDDING='\"false\"' && node --test tests/userWebEntry.test.mjs",
+ "test:user-web-entry": "esbuild src/EnterpriseEntry.tsx --bundle --packages=external --platform=node --format=esm --outfile=node_modules/.cache/user-web-entry/EnterpriseEntry.mjs --alias:virtual:login-auth-simulate-provider=./src/auth/simulate/available.ts --define:import.meta.env.VITE_USER_WEB_MODE='\"personal\"' --define:import.meta.env.VITE_ENABLE_USER_WEB_EMBEDDING='\"false\"' --define:import.meta.env.VITE_LOGIN_AUTH_SIMULATE='\"false\"' && esbuild src/auth/config.ts src/auth/simulate/SimulatedAuthProvider.ts --bundle --packages=external --platform=node --format=esm --outdir=node_modules/.cache/user-web-entry/auth && node --test tests/userWebEntry.test.mjs",
"test:a2a-ingress-panel": "tsc src/components/A2AIngressPanel/a2aIngressPanelState.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/a2a-ingress-panel-state --skipLibCheck --noEmitOnError && node --test tests/a2aIngressPanelState.test.mjs",
"test:chat-store-streaming": "esbuild src/stores/chatStore.ts --bundle --platform=node --format=esm --outfile=node_modules/.cache/chat-store-streaming/chatStore.mjs --define:import.meta.env.DEV=false && node --test tests/chatStoreStreaming.test.mjs",
"test:settle-historical-tool-executions": "esbuild src/stores/chatStore.ts --bundle --platform=node --format=esm --outfile=node_modules/.cache/chat-store-streaming/chatStore.mjs --define:import.meta.env.DEV=false && node --test tests/settleHistoricalToolExecutions.test.mjs",
diff --git a/jiuwenswarm/channels/web/frontend/src/EnterpriseEntry.tsx b/jiuwenswarm/channels/web/frontend/src/EnterpriseEntry.tsx
index ec593e3e90..a80f8e7244 100644
--- a/jiuwenswarm/channels/web/frontend/src/EnterpriseEntry.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/EnterpriseEntry.tsx
@@ -1,4 +1,7 @@
import { type ReactNode, useCallback, useEffect, useMemo, useState } from 'react';
+import { isLoginAuthSimulateEnabled } from './auth/config';
+import { resolveEnterpriseAuthProvider } from './auth/providerRegistry';
+import { EnterpriseAuthError, type EnterpriseAuthProvider } from './auth/types';
import { isEnterpriseMode } from './edition';
import {
EnterpriseContext,
@@ -7,31 +10,11 @@ import {
type EnterpriseContextValue,
type EnterpriseGateway,
type EnterpriseOrg,
- type EnterpriseUser,
} from './services/enterpriseContext';
import { parseRuntimeScope, setRuntimeScope } from './services/runtimeScope';
-const ACCESS_KEY = 'openjiuwen_access_token';
-const REFRESH_KEY = 'openjiuwen_refresh_token';
-
type EntryPhase = 'loading' | 'ready' | 'empty' | 'error' | 'redirecting';
-class EnterpriseApiError extends Error {
- constructor(
- readonly status: number,
- message: string,
- ) {
- super(message);
- this.name = 'EnterpriseApiError';
- }
-}
-
-interface ManagerResponse<T> {
- code: number;
- message?: string;
- data: T;
-}
-
interface ContextCandidate {
gateway: EnterpriseGateway;
org: EnterpriseOrg;
@@ -72,75 +55,19 @@ export function chooseAgent(agents: EnterpriseAgent[], preferredBotId?: string):
return agents.find(agent => agentRuntimeId(agent) === preferredBotId) ?? agents[0] ?? null;
}
-function accessToken(): string | null {
- return typeof localStorage === 'undefined' ? null : localStorage.getItem(ACCESS_KEY);
-}
-
-function authHeaders(): HeadersInit {
- const token = accessToken();
- return token ? { Authorization: `Bearer ${token}` } : {};
-}
-
-function requestMessage(body: unknown, fallback: string): string {
- if (body && typeof body === 'object') {
- const value = body as Record<string, unknown>;
- if (typeof value.detail === 'string' && value.detail.trim()) return value.detail;
- if (typeof value.message === 'string' && value.message.trim()) return value.message;
- }
- return fallback;
-}
-
-async function requestJson<T>(path: string): Promise<T> {
- let response: Response;
- try {
- response = await fetch(path, { headers: authHeaders() });
- } catch (error) {
- throw new EnterpriseApiError(0, `网络请求失败:${error instanceof Error ? error.message : String(error)}`);
- }
-
- let body: unknown = null;
- try {
- body = await response.json();
- } catch {
- // The status code below remains the source of truth for a non-JSON error.
- }
- if (!response.ok) {
- throw new EnterpriseApiError(response.status, requestMessage(body, `HTTP ${response.status}`));
- }
- return body as T;
-}
-
-async function loadUser(): Promise<EnterpriseUser> {
- return requestJson<EnterpriseUser>('/idp/v1/auth/me');
-}
-
-async function loadOrgs(): Promise<EnterpriseOrg[]> {
- const result = await requestJson<{ orgs: EnterpriseOrg[] }>('/idp/v1/auth/me/orgs');
- return result.orgs ?? [];
-}
-
-async function loadGateways(): Promise<EnterpriseGateway[]> {
- const result = await requestJson<ManagerResponse<{ gateways: EnterpriseGateway[] }>>('/manager-api/v1/user-console/gateways');
- if (result.code !== 200) throw new EnterpriseApiError(result.code, result.message || '加载组网失败');
- return result.data?.gateways ?? [];
-}
-
-async function loadAgents(groupId: string, gatewayId: string): Promise<EnterpriseAgent[]> {
- const query = new URLSearchParams({ group_id: groupId, jiuwenclaw_id: gatewayId });
- const result = await requestJson<ManagerResponse<{ agents: EnterpriseAgent[] }>>(`/manager-api/v1/user-console/agents?${query.toString()}`);
- if (result.code !== 200) throw new EnterpriseApiError(result.code, result.message || '加载 Agent 失败');
- return result.data?.agents ?? [];
-}
-
-async function resolveFirstContext(candidates: ContextCandidate[], preferredBotId?: string): Promise<ResolvedContext | null> {
+async function resolveFirstContext(
+ provider: EnterpriseAuthProvider,
+ candidates: ContextCandidate[],
+ preferredBotId?: string,
+): Promise<ResolvedContext | null> {
let firstError: unknown = null;
for (const candidate of candidates) {
try {
- const agents = await loadAgents(candidate.org.group_id, candidate.gateway.jiuwenclaw_id);
+ const agents = await provider.listAgents(candidate.org.group_id, candidate.gateway.jiuwenclaw_id);
const selected = chooseAgent(agents, preferredBotId);
if (selected) return { ...candidate, agents, selectedBot: agentRuntimeId(selected) };
} catch (error) {
- if (error instanceof EnterpriseApiError && error.status === 401) throw error;
+ if (error instanceof EnterpriseAuthError && error.status === 401) throw error;
firstError ??= error;
}
}
@@ -174,21 +101,6 @@ function activateContext(userId: string, resolved: ResolvedContext, navigate: bo
else window.history.replaceState({}, '', nextUrl);
}
-function clearLogin(): void {
- if (typeof localStorage !== 'undefined') {
- localStorage.removeItem(ACCESS_KEY);
- localStorage.removeItem(REFRESH_KEY);
- }
- if (typeof document !== 'undefined') {
- document.cookie = `${ACCESS_KEY}=; Path=/; Max-Age=0; SameSite=Strict`;
- }
-}
-
-function redirectToLogin(): void {
- clearLogin();
- window.location.replace('/auth');
-}
-
function errorText(error: unknown): string {
return error instanceof Error && error.message ? error.message : '加载企业用户上下文失败';
}
@@ -218,34 +130,26 @@ function EntryStatus({ phase, error, onLogout }: { phase: EntryPhase; error: str
export function EnterpriseEntry({ children }: { children: ReactNode }) {
const enterprise = isEnterpriseMode();
- const [phase, setPhase] = useState<EntryPhase>(() => (enterprise && !accessToken() ? 'redirecting' : 'loading'));
+ const simulateLogin = enterprise && isLoginAuthSimulateEnabled();
+ const provider = useMemo(
+ () => (enterprise ? resolveEnterpriseAuthProvider(simulateLogin) : null),
+ [enterprise, simulateLogin],
+ );
+ const [phase, setPhase] = useState<EntryPhase>(() => (provider && !provider.isAuthenticated() ? 'redirecting' : 'loading'));
const [context, setContext] = useState<EnterpriseContextSnapshot | null>(null);
const [error, setError] = useState('');
const [contextError, setContextError] = useState('');
const [contextSwitching, setContextSwitching] = useState(false);
const logout = useCallback(() => {
- void (async () => {
- const refreshToken = typeof localStorage === 'undefined' ? null : localStorage.getItem(REFRESH_KEY);
- if (refreshToken) {
- try {
- await fetch('/idp/v1/auth/logout', {
- method: 'POST',
- headers: { ...authHeaders(), 'Content-Type': 'application/json' },
- body: JSON.stringify({ refresh_token: refreshToken }),
- });
- } catch {
- // Local logout must still complete when the identity service is unavailable.
- }
- }
- redirectToLogin();
- })();
- }, []);
+ if (provider) void provider.logout();
+ }, [provider]);
useEffect(() => {
- if (!enterprise) return;
- if (!accessToken()) {
- redirectToLogin();
+ if (!enterprise || !provider) return;
+ console.info(provider.startupMessage);
+ if (!provider.isAuthenticated()) {
+ provider.redirectToLogin();
return;
}
@@ -253,8 +157,16 @@ export function EnterpriseEntry({ children }: { children: ReactNode }) {
const bootstrap = async () => {
try {
const preferred = parseRuntimeScope(window.location.search);
- const [user, orgs, gateways] = await Promise.all([loadUser(), loadOrgs(), loadGateways()]);
- const resolved = await resolveFirstContext(orderedContextCandidates(gateways, orgs, preferred.gatewayId, preferred.groupId), preferred.botId);
+ const [user, orgs, gateways] = await Promise.all([
+ provider.getCurrentUser(),
+ provider.listOrganizations(),
+ provider.listGateways(),
+ ]);
+ const resolved = await resolveFirstContext(
+ provider,
+ orderedContextCandidates(gateways, orgs, preferred.gatewayId, preferred.groupId),
+ preferred.botId,
+ );
if (cancelled) return;
if (!resolved) {
setPhase('empty');
@@ -273,8 +185,8 @@ export function EnterpriseEntry({ children }: { children: ReactNode }) {
setPhase('ready');
} catch (bootstrapError) {
if (cancelled) return;
- if (bootstrapError instanceof EnterpriseApiError && bootstrapError.status === 401) {
- redirectToLogin();
+ if (bootstrapError instanceof EnterpriseAuthError && bootstrapError.status === 401) {
+ provider.redirectToLogin();
return;
}
setError(errorText(bootstrapError));
@@ -285,23 +197,23 @@ export function EnterpriseEntry({ children }: { children: ReactNode }) {
return () => {
cancelled = true;
};
- }, [enterprise]);
+ }, [enterprise, provider]);
const switchContext = useCallback(
async (candidates: ContextCandidate[], preferredBotId?: string, missingMessage = '所选范围内暂无可用 Agent') => {
- if (!context || contextSwitching) return;
+ if (!context || contextSwitching || !provider) return;
setContextSwitching(true);
setContextError('');
try {
- const resolved = await resolveFirstContext(candidates, preferredBotId);
+ const resolved = await resolveFirstContext(provider, candidates, preferredBotId);
if (!resolved) {
setContextError(missingMessage);
return;
}
activateContext(context.user.user_id, resolved, true);
} catch (switchError) {
- if (switchError instanceof EnterpriseApiError && switchError.status === 401) {
- redirectToLogin();
+ if (switchError instanceof EnterpriseAuthError && switchError.status === 401) {
+ provider.redirectToLogin();
return;
}
setContextError(errorText(switchError));
@@ -309,7 +221,7 @@ export function EnterpriseEntry({ children }: { children: ReactNode }) {
setContextSwitching(false);
}
},
- [context, contextSwitching],
+ [context, contextSwitching, provider],
);
const contextValue = useMemo<EnterpriseContextValue | null>(() => {
diff --git a/jiuwenswarm/channels/web/frontend/src/auth/config.ts b/jiuwenswarm/channels/web/frontend/src/auth/config.ts
new file mode 100644
index 0000000000..9d9ea9808c
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/auth/config.ts
@@ -0,0 +1,17 @@
+const LOGIN_AUTH_SIMULATE_DEFAULT = true;
+
+export function parseLoginAuthSimulate(raw: unknown): boolean {
+ if (raw === undefined || raw === null || raw === '') return LOGIN_AUTH_SIMULATE_DEFAULT;
+ const normalized = String(raw).trim().toLowerCase();
+ if (normalized === 'true') return true;
+ if (normalized === 'false') return false;
+ throw new Error(`LOGIN_AUTH_SIMULATE 配置非法:期望 true 或 false,实际为 ${String(raw)}`);
+}
+
+export function isLoginAuthSimulateEnabled(): boolean {
+ const injected = window.__JIUWEN_LOGIN_AUTH_SIMULATE__;
+ if (injected !== undefined && injected !== '__JIUWEN_LOGIN_AUTH_SIMULATE_VALUE__') {
+ return parseLoginAuthSimulate(injected);
+ }
+ return parseLoginAuthSimulate(import.meta.env.VITE_LOGIN_AUTH_SIMULATE);
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/auth/manager/ManagerAuthProvider.ts b/jiuwenswarm/channels/web/frontend/src/auth/manager/ManagerAuthProvider.ts
new file mode 100644
index 0000000000..fab7d50fea
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/auth/manager/ManagerAuthProvider.ts
@@ -0,0 +1,102 @@
+import type {
+ EnterpriseAgent,
+ EnterpriseGateway,
+ EnterpriseOrg,
+ EnterpriseUser,
+} from '../../services/enterpriseContext';
+import { EnterpriseAuthError, type EnterpriseAuthProvider } from '../types';
+
+const ACCESS_KEY = 'openjiuwen_access_token';
+const REFRESH_KEY = 'openjiuwen_refresh_token';
+
+interface ManagerResponse<T> {
+ code: number;
+ message?: string;
+ data: T;
+}
+
+function accessToken(): string | null {
+ return typeof localStorage === 'undefined' ? null : localStorage.getItem(ACCESS_KEY);
+}
+
+function authHeaders(): HeadersInit {
+ const token = accessToken();
+ return token ? { Authorization: `Bearer ${token}` } : {};
+}
+
+function requestMessage(body: unknown, fallback: string): string {
+ if (body && typeof body === 'object') {
+ const value = body as Record<string, unknown>;
+ if (typeof value.detail === 'string' && value.detail.trim()) return value.detail;
+ if (typeof value.message === 'string' && value.message.trim()) return value.message;
+ }
+ return fallback;
+}
+
+async function requestJson<T>(path: string): Promise<T> {
+ let response: Response;
+ try {
+ response = await fetch(path, { headers: authHeaders() });
+ } catch (error) {
+ throw new EnterpriseAuthError(0, `网络请求失败:${error instanceof Error ? error.message : String(error)}`);
+ }
+ let body: unknown = null;
+ try {
+ body = await response.json();
+ } catch {
+ // The HTTP status remains authoritative for non-JSON responses.
+ }
+ if (!response.ok) throw new EnterpriseAuthError(response.status, requestMessage(body, `HTTP ${response.status}`));
+ return body as T;
+}
+
+function clearLogin(): void {
+ if (typeof localStorage !== 'undefined') {
+ localStorage.removeItem(ACCESS_KEY);
+ localStorage.removeItem(REFRESH_KEY);
+ }
+ if (typeof document !== 'undefined') {
+ document.cookie = `${ACCESS_KEY}=; Path=/; Max-Age=0; SameSite=Strict`;
+ }
+}
+
+export const managerAuthProvider: EnterpriseAuthProvider = {
+ id: 'manager',
+ startupMessage: '【正式身份认证模式,依赖manager ID认证服务】',
+ isAuthenticated: () => Boolean(accessToken()),
+ redirectToLogin() {
+ clearLogin();
+ window.location.replace('/auth');
+ },
+ getCurrentUser: () => requestJson<EnterpriseUser>('/idp/v1/auth/me'),
+ async listOrganizations() {
+ const result = await requestJson<{ orgs: EnterpriseOrg[] }>('/idp/v1/auth/me/orgs');
+ return result.orgs ?? [];
+ },
+ async listGateways() {
+ const result = await requestJson<ManagerResponse<{ gateways: EnterpriseGateway[] }>>('/manager-api/v1/user-console/gateways');
+ if (result.code !== 200) throw new EnterpriseAuthError(result.code, result.message || '加载组网失败');
+ return result.data?.gateways ?? [];
+ },
+ async listAgents(groupId, gatewayId) {
+ const query = new URLSearchParams({ group_id: groupId, jiuwenclaw_id: gatewayId });
+ const result = await requestJson<ManagerResponse<{ agents: EnterpriseAgent[] }>>(`/manager-api/v1/user-console/agents?${query.toString()}`);
+ if (result.code !== 200) throw new EnterpriseAuthError(result.code, result.message || '加载 Agent 失败');
+ return result.data?.agents ?? [];
+ },
+ async logout() {
+ const refreshToken = typeof localStorage === 'undefined' ? null : localStorage.getItem(REFRESH_KEY);
+ if (refreshToken) {
+ try {
+ await fetch('/idp/v1/auth/logout', {
+ method: 'POST',
+ headers: { ...authHeaders(), 'Content-Type': 'application/json' },
+ body: JSON.stringify({ refresh_token: refreshToken }),
+ });
+ } catch {
+ // Local logout must still complete when the identity service is unavailable.
+ }
+ }
+ this.redirectToLogin();
+ },
+};
diff --git a/jiuwenswarm/channels/web/frontend/src/auth/providerRegistry.ts b/jiuwenswarm/channels/web/frontend/src/auth/providerRegistry.ts
new file mode 100644
index 0000000000..1f1822b62a
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/auth/providerRegistry.ts
@@ -0,0 +1,11 @@
+import { simulatedAuthProvider } from 'virtual:login-auth-simulate-provider';
+import { managerAuthProvider } from './manager/ManagerAuthProvider';
+import type { EnterpriseAuthProvider } from './types';
+
+export function resolveEnterpriseAuthProvider(simulate: boolean): EnterpriseAuthProvider {
+ if (!simulate) return managerAuthProvider;
+ if (!simulatedAuthProvider) {
+ throw new Error('LOGIN_AUTH_SIMULATE=true,但当前交付包未安装登录认证模拟插件');
+ }
+ return simulatedAuthProvider;
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/auth/simulate/SimulatedAuthProvider.ts b/jiuwenswarm/channels/web/frontend/src/auth/simulate/SimulatedAuthProvider.ts
new file mode 100644
index 0000000000..747a1af28b
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/auth/simulate/SimulatedAuthProvider.ts
@@ -0,0 +1,49 @@
+import type { EnterpriseContextSnapshot } from '../../services/enterpriseContext';
+import { parseRuntimeScope } from '../../services/runtimeScope';
+import type { EnterpriseAuthProvider } from '../types';
+
+const DEFAULTS = {
+ userId: 'debug-user',
+ displayName: 'Debug User',
+ groupId: 'debug-group',
+ groupName: 'Debug Organization',
+ gatewayId: 'debug-gateway',
+ gatewayName: 'Debug Gateway',
+ botId: 'debug-agent',
+ botName: 'Debug Agent',
+} as const;
+
+export function buildSimulatedEnterpriseContext(search = ''): EnterpriseContextSnapshot {
+ const preferred = parseRuntimeScope(search);
+ const user = { user_id: preferred.userId || DEFAULTS.userId, display_name: DEFAULTS.displayName };
+ const org = { group_id: preferred.groupId || DEFAULTS.groupId, name: DEFAULTS.groupName };
+ const gateway = {
+ jiuwenclaw_id: preferred.gatewayId || DEFAULTS.gatewayId,
+ jiuwenclaw_name: DEFAULTS.gatewayName,
+ gateway_endpoint: null,
+ };
+ const agent = {
+ template_id: preferred.botId || DEFAULTS.botId,
+ template_name: DEFAULTS.botName,
+ resource_id: preferred.botId || DEFAULTS.botId,
+ };
+ return { user, org, orgs: [org], gateway, gateways: [gateway], agents: [agent], selectedBot: agent.resource_id };
+}
+
+function entryPath(): string {
+ return window.location.pathname.startsWith('/chat') ? '/chat/' : '/';
+}
+
+export const simulatedAuthProvider: EnterpriseAuthProvider = {
+ id: 'simulate',
+ startupMessage: '【登录认证模拟调试模式已开启】使用默认用户、组织、组网和 Agent 候选值',
+ isAuthenticated: () => true,
+ redirectToLogin: () => window.location.replace(entryPath()),
+ getCurrentUser: async () => buildSimulatedEnterpriseContext(window.location.search).user,
+ listOrganizations: async () => buildSimulatedEnterpriseContext(window.location.search).orgs,
+ listGateways: async () => buildSimulatedEnterpriseContext(window.location.search).gateways,
+ listAgents: async () => buildSimulatedEnterpriseContext(window.location.search).agents,
+ async logout() {
+ window.location.replace(entryPath());
+ },
+};
diff --git a/jiuwenswarm/channels/web/frontend/src/auth/simulate/available.ts b/jiuwenswarm/channels/web/frontend/src/auth/simulate/available.ts
new file mode 100644
index 0000000000..6282b5d838
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/auth/simulate/available.ts
@@ -0,0 +1 @@
+export { simulatedAuthProvider } from './SimulatedAuthProvider';
diff --git a/jiuwenswarm/channels/web/frontend/src/auth/simulateUnavailable.ts b/jiuwenswarm/channels/web/frontend/src/auth/simulateUnavailable.ts
new file mode 100644
index 0000000000..5363244ae5
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/auth/simulateUnavailable.ts
@@ -0,0 +1,5 @@
+import type { EnterpriseAuthProvider } from './types';
+
+// Customer builds bind the virtual simulation provider to this empty adapter.
+// This keeps the registry stable while allowing auth/simulate/ to be omitted.
+export const simulatedAuthProvider: EnterpriseAuthProvider | null = null;
diff --git a/jiuwenswarm/channels/web/frontend/src/auth/types.ts b/jiuwenswarm/channels/web/frontend/src/auth/types.ts
new file mode 100644
index 0000000000..dd979be547
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/auth/types.ts
@@ -0,0 +1,28 @@
+import type {
+ EnterpriseAgent,
+ EnterpriseGateway,
+ EnterpriseOrg,
+ EnterpriseUser,
+} from '../services/enterpriseContext';
+
+export interface EnterpriseAuthProvider {
+ readonly id: 'manager' | 'simulate';
+ readonly startupMessage: string;
+ isAuthenticated(): boolean;
+ redirectToLogin(): void;
+ getCurrentUser(): Promise<EnterpriseUser>;
+ listOrganizations(): Promise<EnterpriseOrg[]>;
+ listGateways(): Promise<EnterpriseGateway[]>;
+ listAgents(groupId: string, gatewayId: string): Promise<EnterpriseAgent[]>;
+ logout(): Promise<void>;
+}
+
+export class EnterpriseAuthError extends Error {
+ constructor(
+ readonly status: number,
+ message: string,
+ ) {
+ super(message);
+ this.name = 'EnterpriseAuthError';
+ }
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/vite-env.d.ts b/jiuwenswarm/channels/web/frontend/src/vite-env.d.ts
index b5dda053f6..ccaf6cf8e2 100644
--- a/jiuwenswarm/channels/web/frontend/src/vite-env.d.ts
+++ b/jiuwenswarm/channels/web/frontend/src/vite-env.d.ts
@@ -8,6 +8,8 @@ interface ImportMetaEnv {
readonly VITE_TRANSPORT?: string;
readonly VITE_GATEWAY_HTTP_BASE?: string;
readonly VITE_WEB_HTTP_BASE?: string;
+ readonly VITE_LOGIN_AUTH_SIMULATE?: string;
+ readonly VITE_LOGIN_AUTH_SIMULATE_AVAILABLE?: string;
}
interface ImportMeta {
@@ -47,4 +49,13 @@ interface Window {
/** Set by the User Web server for enterprise embedding mode. */
__JIUWEN_USER_WEB_MODE__?: string;
__JIUWEN_USER_WEB_EMBEDDING__?: boolean;
+ /** Login simulation switch injected by the User Web server. */
+ __JIUWEN_LOGIN_AUTH_SIMULATE__?: boolean | string;
+ /** Whether this frontend artifact contains the optional simulation plugin. */
+ __JIUWEN_LOGIN_AUTH_SIMULATE_AVAILABLE__?: boolean | string;
+}
+
+declare module 'virtual:login-auth-simulate-provider' {
+ import type { EnterpriseAuthProvider } from './auth/types';
+ export const simulatedAuthProvider: EnterpriseAuthProvider | null;
}
diff --git a/jiuwenswarm/channels/web/frontend/tests/userWebEntry.test.mjs b/jiuwenswarm/channels/web/frontend/tests/userWebEntry.test.mjs
index 6f31bde52b..1600ec3662 100644
--- a/jiuwenswarm/channels/web/frontend/tests/userWebEntry.test.mjs
+++ b/jiuwenswarm/channels/web/frontend/tests/userWebEntry.test.mjs
@@ -22,9 +22,12 @@ globalThis.window = {
};
const { EnterpriseEntry, chooseAgent, orderedContextCandidates } = await import('../node_modules/.cache/user-web-entry/EnterpriseEntry.mjs');
+const { parseLoginAuthSimulate } = await import('../node_modules/.cache/user-web-entry/auth/config.js');
+const { buildSimulatedEnterpriseContext } = await import('../node_modules/.cache/user-web-entry/auth/simulate/SimulatedAuthProvider.js');
-function renderEntry(mode) {
+function renderEntry(mode, simulate = false) {
window.__JIUWEN_USER_WEB_MODE__ = mode;
+ window.__JIUWEN_LOGIN_AUTH_SIMULATE__ = simulate;
return renderToStaticMarkup(React.createElement(EnterpriseEntry, null, React.createElement('div', { id: 'user-web-content' }, 'user web content')));
}
@@ -61,6 +64,33 @@ test('enterprise mode loads and validates an authorized context before rendering
assert.doesNotMatch(html, /user web content/);
});
+test('simulated enterprise login uses local defaults without an access token', () => {
+ resetBrowserState();
+ const context = buildSimulatedEnterpriseContext('');
+
+ assert.equal(context.user.user_id, 'debug-user');
+ assert.equal(context.org.group_id, 'debug-group');
+ assert.equal(context.gateway.jiuwenclaw_id, 'debug-gateway');
+ assert.equal(context.selectedBot, 'debug-agent');
+ assert.doesNotMatch(renderEntry('enterprise', true), /正在前往登录页/);
+});
+
+test('simulated enterprise login accepts URL tuple overrides', () => {
+ const context = buildSimulatedEnterpriseContext('?user_id=u1&group_id=g1&gateway_id=gw1&bot_id=b1');
+
+ assert.equal(context.user.user_id, 'u1');
+ assert.equal(context.org.group_id, 'g1');
+ assert.equal(context.gateway.jiuwenclaw_id, 'gw1');
+ assert.equal(context.selectedBot, 'b1');
+});
+
+test('LOGIN_AUTH_SIMULATE accepts only booleans and defaults to true', () => {
+ assert.equal(parseLoginAuthSimulate(undefined), true);
+ assert.equal(parseLoginAuthSimulate('true'), true);
+ assert.equal(parseLoginAuthSimulate(' FALSE '), false);
+ assert.throws(() => parseLoginAuthSimulate('yes'), /期望 true 或 false/);
+});
+
test('context candidates prefer URL values but retain every authorized combination', () => {
const gateways = [
{ jiuwenclaw_id: 'gateway-1', jiuwenclaw_name: 'Gateway 1', gateway_endpoint: null },
diff --git a/jiuwenswarm/channels/web/frontend/vite.config.ts b/jiuwenswarm/channels/web/frontend/vite.config.ts
index 6731f5244c..6e6faab37f 100644
--- a/jiuwenswarm/channels/web/frontend/vite.config.ts
+++ b/jiuwenswarm/channels/web/frontend/vite.config.ts
@@ -319,6 +319,89 @@ function resolveWebHttpPort(wsPort: number): number {
return port
}
+function parseLoginAuthSimulate(raw: string | undefined): boolean {
+ const value = (raw ?? '').trim().toLowerCase()
+ if (!value) return true
+ if (value === 'true') return true
+ if (value === 'false') return false
+ throw new Error(
+ `LOGIN_AUTH_SIMULATE 配置非法:仅支持 true 或 false,当前值为 ${JSON.stringify(raw)}`
+ )
+}
+
+const loginAuthSimulateIncluded = parseLoginAuthSimulate(
+ process.env.INCLUDE_LOGIN_AUTH_SIMULATE ?? process.env.VITE_LOGIN_AUTH_SIMULATE_AVAILABLE
+)
+
+function loginAuthStartupCheck(): Plugin {
+ const userWebMode = (process.env.USER_WEB_MODE || process.env.VITE_USER_WEB_MODE || 'personal')
+ .trim()
+ .toLowerCase()
+ const simulateRaw = process.env.LOGIN_AUTH_SIMULATE ?? process.env.VITE_LOGIN_AUTH_SIMULATE
+ const simulate = parseLoginAuthSimulate(simulateRaw)
+
+ if (userWebMode === 'enterprise' && simulate && !loginAuthSimulateIncluded) {
+ throw new Error(
+ '配置冲突:LOGIN_AUTH_SIMULATE=true,但当前客户交付制品未包含登录认证模拟插件;' +
+ '请设置 LOGIN_AUTH_SIMULATE=false 并接入 manager ID认证服务'
+ )
+ }
+
+ return {
+ name: 'login-auth-startup-check',
+ async configureServer() {
+ if (simulateRaw === undefined || !simulateRaw.trim()) {
+ console.info(
+ '[jiuwenswarm-web] LOGIN_AUTH_SIMULATE 未配置,按默认值 true 启用登录认证模拟调试'
+ )
+ }
+ if (userWebMode !== 'enterprise') {
+ console.info('[jiuwenswarm-web] 单机版模式:跳过企业登录认证')
+ if (!simulate) {
+ console.warn(
+ '[jiuwenswarm-web] 配置冲突:USER_WEB_MODE=personal 始终跳过企业登录;' +
+ 'LOGIN_AUTH_SIMULATE=false 不会启用正式身份认证'
+ )
+ }
+ return
+ }
+ if (simulate) {
+ console.info('[jiuwenswarm-web] 【登录认证模拟调试模式已开启】不调用客户侧 manager ID认证服务')
+ return
+ }
+
+ console.info('[jiuwenswarm-web] 【正式身份认证模式,依赖manager ID认证服务】')
+ const targets = [
+ { name: 'manager ID认证服务', env: 'USER_WEB_IDP_TARGET', target: process.env.USER_WEB_IDP_TARGET, path: '/v1/auth/me' },
+ { name: 'Manager业务接口', env: 'USER_WEB_MANAGER_TARGET', target: process.env.USER_WEB_MANAGER_TARGET, path: '/api/v1/user-console/gateways' },
+ ]
+ const missing = targets.filter(({ target }) => !target).map(({ env }) => env)
+ if (missing.length > 0) {
+ console.error(
+ `[jiuwenswarm-web] 正式登录模式下未配置 ${missing.join('、')};` +
+ '请配置 manager 认证及业务接口地址'
+ )
+ return
+ }
+ for (const item of targets) {
+ const target = item.target!.replace(/\/$/, '')
+ try {
+ const response = await fetch(`${target}${item.path}`, {
+ signal: AbortSignal.timeout(3000),
+ })
+ if (response.status >= 500) throw new Error(`HTTP ${response.status}`)
+ console.info(`[jiuwenswarm-web] ${item.name}连通性检查通过:${target}`)
+ } catch (error) {
+ console.error(
+ `[jiuwenswarm-web] 当前为正式登录模式,${item.name}暂不可用;` +
+ `请检查 ${item.env}(${target}):${error instanceof Error ? error.message : String(error)}`
+ )
+ }
+ }
+ },
+ }
+}
+
const frontendPort = portFromEnv('FRONTEND_PORT', 5173)
const webPort = portFromEnv('WEB_PORT', 19000)
const webTarget =
@@ -333,13 +416,19 @@ const webHttpTarget =
export default defineConfig({
// 相对资源路径同时支持独立根路径与 Manager Web 的 /chat/ 同源转发。
base: './',
- plugins: [suppressWsProxySocketErrors(), devWsTrafficLogger(), react(), svgr()],
+ plugins: [loginAuthStartupCheck(), suppressWsProxySocketErrors(), devWsTrafficLogger(), react(), svgr()],
optimizeDeps: {
include: ['exceljs', 'jszip', 'saxes', 'ssf'],
},
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
+ 'virtual:login-auth-simulate-provider': path.resolve(
+ __dirname,
+ loginAuthSimulateIncluded
+ ? './src/auth/simulate/available.ts'
+ : './src/auth/simulateUnavailable.ts'
+ ),
},
},
server: {
diff --git a/tests/unit_tests/test_app_web_gateway_api_proxy.py b/tests/unit_tests/test_app_web_gateway_api_proxy.py
index 7933443558..cf910ca828 100644
--- a/tests/unit_tests/test_app_web_gateway_api_proxy.py
+++ b/tests/unit_tests/test_app_web_gateway_api_proxy.py
@@ -7,6 +7,7 @@ import pytest
from jiuwenswarm.channels.web.app_web import (
_SpaStaticHandler,
_inject_user_web_runtime_config,
+ _parse_login_auth_simulate,
)
@@ -63,3 +64,16 @@ def test_user_web_runtime_mode_injection_preserves_property_names(
assert f"'{embedding}' === 'true'" in rendered
assert "__JIUWEN_USER_WEB_MODE_VALUE__" not in rendered
assert "__JIUWEN_USER_WEB_EMBEDDING_VALUE__" not in rendered
+ assert "window.__JIUWEN_LOGIN_AUTH_SIMULATE__ = 'true'" in rendered
+ assert "__JIUWEN_LOGIN_AUTH_SIMULATE_VALUE__" not in rendered
+ assert "window.__JIUWEN_LOGIN_AUTH_SIMULATE_AVAILABLE__ = 'true'" in rendered
+ assert "__JIUWEN_LOGIN_AUTH_SIMULATE_AVAILABLE_VALUE__" not in rendered
+
+
+def test_login_auth_simulate_config_is_strict_and_defaults_to_true() -> None:
+ assert _parse_login_auth_simulate(None) is True
+ assert _parse_login_auth_simulate("") is True
+ assert _parse_login_auth_simulate(" TRUE ") is True
+ assert _parse_login_auth_simulate("false") is False
+ with pytest.raises(ValueError, match="期望 true 或 false"):
+ _parse_login_auth_simulate("yes")