diff --git a/deploy/portal-integration.compose.yml b/deploy/portal-integration.compose.yml
new file mode 100644
index 0000000..0d037a1
--- /dev/null
+++ b/deploy/portal-integration.compose.yml
@@ -0,0 +1,27 @@
+# Optional overlay for a separately approved, fresh finance integration instance.
+# Never point FINANCE_DATA at the standalone server's real database.
+services:
+ backend:
+ environment:
+ FINANCE_SSO_ENABLED: "true"
+ FINANCE_SSO_SECRET: ${FINANCE_SSO_SECRET}
+ FINANCE_SSO_CALLBACK_URL: ${FINANCE_PUBLIC_URL}/portal-sso
+ finance:
+ image: ${FINANCE_IMAGE}
+ container_name: jinniu-finance-portal-integration
+ ports: ["${TEST_HOST}:18124:4173"]
+ environment:
+ PORTAL_SSO_ENABLED: "1"
+ PORTAL_SSO_SECRET: ${FINANCE_SSO_SECRET}
+ PORTAL_INTERNAL_URL: http://backend:8000
+ PORTAL_PUBLIC_URL: http://${TEST_HOST}:18091
+ APP_DB_PATH: /app/data/app.db
+ APP_STORAGE_DIR: /app/data/files
+ volumes:
+ - ${FINANCE_SOURCE}/server.py:/app/server.py:ro
+ - ${FINANCE_SOURCE}/src:/app/src:ro
+ - ${FINANCE_SOURCE}/web:/app/web:ro
+ - ${FINANCE_DATA}:/app/data
+ healthcheck:
+ test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:4173/healthz',timeout=3)"]
+ depends_on: [backend]
diff --git a/docs/PORTAL-INTEGRATION.md b/docs/PORTAL-INTEGRATION.md
new file mode 100644
index 0000000..2537b5d
--- /dev/null
+++ b/docs/PORTAL-INTEGRATION.md
@@ -0,0 +1,13 @@
+# 统一门户适配(2026-09-22)
+
+分支 feature/portal-integration,基于 main 6eccbe9。代码完成但尚未替换外网测试实例;部署方向等待用户决定。
+
+`PORTAL_SSO_ENABLED=1` 开启门户模式;必须配置独立的 PORTAL_SSO_SECRET、PORTAL_INTERNAL_URL、PORTAL_PUBLIC_URL。若使用 HTTPS,部署时还需相应安全 Cookie 配置。门户配置 FINANCE_SSO_ENABLED、FINANCE_SSO_SECRET、FINANCE_SSO_CALLBACK_URL,回调固定为 `/portal-sso`。
+
+员工在门户中绑定已有财务用户的数字 ID;本地角色及 company_id 继续决定业务权限,不读取门户 admin 作为业务角色。每名员工应有独立本地账号,同一公司可有多名员工;不将多人映射到共享公司登录身份。账户停用及财务本地停用均拒绝访问。门户模式不允许原生登录、登出、改密、创建凭证或重置密码;管理员/出纳页面仍分开。
+
+初始化会增量创建 portal_identity、portal_sessions 两表,不改银行流水、业务计算或原会话表。已有银行数据迁移不包含在本次工作中。全新实例须先配置测试公司和测试业务身份,再绑定门户员工;不会默认生成管理员密码。
+
+候选内网部署 overlay 为 deploy/portal-integration.compose.yml,应叠加现有门户/OA融合 Compose,使用独立 FINANCE_DATA 目录并赋予容器用户 10001 写权限。健康检查使用 `/healthz`,原主页在门户模式跳回门户。FINANCE_IMAGE 应为已准备好依赖的 Python 3.12 财务镜像,代码目录通过 FINANCE_SOURCE 只读挂载。不得把候选测试实例数据路径指向现有正式或独立测试库。
+
+验证命令:`PYTHONPATH=src python -m unittest discover -s tests`。本轮 395 项:391 通过、4 跳过,其中新增 6 项 SSO 回调/权限/隔离测试。外网到内网门户目前不可达,实际财务跨系统端到端部署验收待完成。
diff --git a/server.py b/server.py
index 1dda4ee..91140fb 100644
--- a/server.py
+++ b/server.py
@@ -19,6 +19,7 @@ from bank_importer import (
positions, reminders, settings, subjects,
)
from bank_importer.db import connect, migrate, transaction, utc_now
+from bank_importer import portal_sso
ROOT = Path(__file__).resolve().parent
@@ -26,13 +27,13 @@ WEB_ROOT = ROOT / "web"
MAX_UPLOAD_BYTES = 20 * 1024 * 1024
DB_PATH = Path(os.environ.get("APP_DB_PATH", ROOT / "data" / "app.db"))
STORAGE_DIR = Path(os.environ.get("APP_STORAGE_DIR", ROOT / "data" / "files"))
-SESSION_COOKIE = "cw_session"
+SESSION_COOKIE = "cw_fusion_session" if portal_sso.enabled() else "cw_session"
# Local plain-HTTP deployment: the cookie intentionally carries no Secure
# flag (see docs/decisions/003-auth.md).
COOKIE_FLAGS = "HttpOnly; SameSite=Lax; Path=/"
-class AppHandler(SimpleHTTPRequestHandler):
+class AppHandler(portal_sso.PortalMixin, SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=str(WEB_ROOT), **kwargs)
@@ -44,6 +45,15 @@ class AppHandler(SimpleHTTPRequestHandler):
parsed = urlparse(self.path)
path = parsed.path
query = parse_qs(parsed.query)
+ if path == "/healthz":
+ self._send_json(200, {"status": "ok"})
+ return
+ if path == "/portal-sso":
+ self._portal_callback(query, DB_PATH)
+ return
+ if portal_sso.enabled() and path in {"/", "/index.html", "/login-admin.html", "/login-company.html"}:
+ self._portal_redirect(portal_sso.base_url("PORTAL_PUBLIC_URL"))
+ return
if path == "/api/me":
self._handle_me()
@@ -274,6 +284,10 @@ class AppHandler(SimpleHTTPRequestHandler):
def do_POST(self) -> None:
path = urlparse(self.path).path
+ if portal_sso.enabled() and (path in {"/api/login", "/api/logout", "/api/password/change", "/api/admin/users"}
+ or re.fullmatch(r"/api/admin/users/\d+/reset-password", path)):
+ self._send_json(403, {"message": "账号和登录请前往统一门户管理。"})
+ return
if path == "/api/login":
self._handle_login()
@@ -463,6 +477,11 @@ class AppHandler(SimpleHTTPRequestHandler):
token = self._session_token()
if not token:
return None
+ if portal_sso.enabled():
+ try:
+ return portal_sso.resolve(connection, token)
+ except Exception:
+ return None # Fail closed; no local-password fallback.
return auth.resolve_session(connection, token)
def _require_user(self, connection, *, pending_password_ok: bool = False):
@@ -470,7 +489,7 @@ class AppHandler(SimpleHTTPRequestHandler):
if user is None:
self._send_json(401, {"status": "error", "message": "请先登录。"})
return None
- if user["must_change_password"] and not pending_password_ok:
+ if user["must_change_password"] and not pending_password_ok and not portal_sso.enabled():
self._send_json(
403,
{"status": "error", "message": "首次登录须修改密码后才能继续操作。"},
@@ -619,7 +638,7 @@ class AppHandler(SimpleHTTPRequestHandler):
"status": "ok",
"username": user["username"],
"role": user["role"],
- "must_change_password": bool(user["must_change_password"]),
+ "must_change_password": bool(user["must_change_password"]) and not portal_sso.enabled(),
"company_id": user["company_id"],
"company_name": company_name,
}
@@ -1142,6 +1161,9 @@ class AppHandler(SimpleHTTPRequestHandler):
return
name = str(data.get("name") or "").strip()
username = str(data.get("username") or "").strip()
+ if portal_sso.enabled() and username:
+ self._send_json(403, {"message": "员工账号请在统一门户建立,再配置财务权限绑定。"})
+ return
try:
company_id = master_data.create_company(
connection,
@@ -4416,7 +4438,8 @@ def main() -> None:
connection = connect(DB_PATH)
try:
migrate(connection)
- initial_password = ensure_bootstrap_admin(connection)
+ portal_sso.migrate(connection)
+ initial_password = None if portal_sso.enabled() else ensure_bootstrap_admin(connection)
finally:
connection.close()
if initial_password is not None:
diff --git a/src/bank_importer/portal_sso.py b/src/bank_importer/portal_sso.py
new file mode 100644
index 0000000..517d624
--- /dev/null
+++ b/src/bank_importer/portal_sso.py
@@ -0,0 +1,185 @@
+"""Optional portal identity bridge. Financial role and company scope stay local."""
+import hashlib
+import html
+import io
+import json
+import os
+import re
+import secrets
+from http.cookies import SimpleCookie
+from urllib.parse import urlencode, urlsplit
+from urllib.request import Request, build_opener, HTTPRedirectHandler
+
+from . import auth
+from .db import connect
+
+
+def enabled():
+ return os.environ.get("PORTAL_SSO_ENABLED") == "1"
+
+
+def base_url(name):
+ value = os.environ.get(name, "").rstrip("/")
+ url = urlsplit(value)
+ if (url.scheme not in {"http", "https"} or not url.hostname or url.username
+ or url.password or url.path or url.query or url.fragment):
+ raise ValueError("Portal URL unavailable")
+ return value
+
+
+class NoRedirect(HTTPRedirectHandler):
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
+ return None
+
+
+def call(operation, payload):
+ secret = os.environ.get("PORTAL_SSO_SECRET", "")
+ if len(secret) < 32:
+ raise ValueError("Portal secret unavailable")
+ req = Request(base_url("PORTAL_INTERNAL_URL") + "/api/sso/apps/finance/" + operation,
+ data=json.dumps(payload).encode(),
+ headers={"Content-Type": "application/json", "Authorization": "Bearer " + secret})
+ with build_opener(NoRedirect).open(req, timeout=5) as response:
+ body = response.read(32769)
+ if len(body) > 32768:
+ raise ValueError("Invalid portal response")
+ return json.loads(body)
+
+
+def migrate(connection):
+ connection.executescript("""
+ CREATE TABLE IF NOT EXISTS portal_identity (
+ uid INTEGER PRIMARY KEY REFERENCES users(id), empid TEXT UNIQUE NOT NULL
+ );
+ CREATE TABLE IF NOT EXISTS portal_sessions (
+ token_hash TEXT PRIMARY KEY, handle TEXT NOT NULL,
+ empid TEXT NOT NULL, uid INTEGER NOT NULL REFERENCES users(id)
+ );
+ """)
+
+
+def resolve(connection, token):
+ user = auth.resolve_session(connection, token)
+ if user is None:
+ return None
+ row = connection.execute("SELECT * FROM portal_sessions WHERE token_hash=?",
+ (hashlib.sha256(token.encode()).hexdigest(),)).fetchone()
+ if row is None:
+ return None
+ result = call("introspect", {"session_handle": row["handle"]})
+ who = result.get("identity") or {}
+ if (not result.get("active") or who.get("local_uid") != user["id"]
+ or who.get("empid") != row["empid"] or row["uid"] != user["id"]):
+ auth.revoke_session(connection, token)
+ return None
+ return user
+
+
+class PortalMixin:
+ def _portal_error(self, status, message):
+ home = html.escape(base_url("PORTAL_PUBLIC_URL"), quote=True)
+ body = (''
+ '
金牛财务往来' + html.escape(message)
+ + '
返回统一门户').encode()
+ self.send_response(status)
+ self.send_header("Content-Type", "text/html; charset=utf-8")
+ self.send_header("Cache-Control", "no-store")
+ self.send_header("Referrer-Policy", "no-referrer")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def _portal_redirect(self, target, cookie=None):
+ self.send_response(303)
+ self.send_header("Location", target)
+ self.send_header("Cache-Control", "no-store")
+ self.send_header("Referrer-Policy", "no-referrer")
+ if cookie:
+ self.send_header("Set-Cookie", cookie)
+ self.send_header("Content-Length", "0")
+ self.end_headers()
+
+ def _portal_callback(self, query, db_path):
+ if not enabled():
+ self.send_error(404)
+ return
+ secure = "; Secure" if os.environ.get("PORTAL_COOKIE_SECURE") == "1" else ""
+ flags = "; HttpOnly; SameSite=Lax; Path=/portal-sso" + secure
+ if "ticket" not in query:
+ verifier = secrets.token_hex(32)
+ theme = "night" if query.get("theme") == ["night"] else "day"
+ self._portal_redirect(base_url("PORTAL_PUBLIC_URL") + "/api/sso/apps/finance/authorize?"
+ + urlencode({"challenge": hashlib.sha256(verifier.encode()).hexdigest()}),
+ "cw_portal_proof=" + verifier + "." + theme + flags + "; Max-Age=120")
+ return
+ cookie = SimpleCookie()
+ cookie.load(self.headers.get("Cookie", ""))
+ proof = cookie.get("cw_portal_proof")
+ parts = proof.value.split(".") if proof else []
+ ticket = query["ticket"][0]
+ if len(parts) != 2 or not re.fullmatch("[a-f0-9]{64}", parts[0]) or not re.fullmatch("[a-f0-9]{64}", ticket):
+ self._portal_error(401, "登录请求已失效,请从统一门户重新进入。")
+ return
+ connection = connect(db_path)
+ try:
+ result = call("exchange", {"ticket": ticket, "verifier": parts[0]})
+ who = result["identity"]
+ handle = result["session_handle"]
+ if not re.fullmatch("[a-f0-9]{64}", handle) or not re.fullmatch("[a-f0-9-]{36}", who["empid"]):
+ raise ValueError("Invalid identity")
+ user = connection.execute("SELECT * FROM users WHERE id=? AND status='active'", (who["local_uid"],)).fetchone()
+ if user is None:
+ raise ValueError("Local account unavailable")
+ with connection:
+ connection.execute("INSERT OR IGNORE INTO portal_identity(uid,empid) VALUES (?,?)", (user["id"], who["empid"]))
+ binding = connection.execute("SELECT empid FROM portal_identity WHERE uid=?", (user["id"],)).fetchone()
+ if not binding or binding["empid"] != who["empid"]:
+ raise ValueError("Binding mismatch")
+ token = auth.create_session(connection, user["id"])
+ with connection:
+ connection.execute("INSERT INTO portal_sessions(token_hash,handle,empid,uid) VALUES (?,?,?,?)",
+ (hashlib.sha256(token.encode()).hexdigest(), handle, who["empid"], user["id"]))
+ connection.execute("DELETE FROM portal_sessions WHERE token_hash NOT IN (SELECT token_hash FROM sessions)")
+ auth.audit(connection, "portal_login", actor=user, detail=who["empid"])
+ target = "/admin.html" if user["role"] == "admin" else "/company.html"
+ theme = "night" if parts[1] == "night" else "day"
+ self.send_response(303)
+ self._set_session_cookie(token)
+ self.send_header("Set-Cookie", "cw_portal_proof=" + flags + "; Max-Age=0")
+ self.send_header("Location", target + "?theme=" + theme)
+ self.send_header("Cache-Control", "no-store")
+ self.send_header("Referrer-Policy", "no-referrer")
+ self.send_header("Content-Length", "0")
+ self.end_headers()
+ except Exception:
+ self._portal_error(401, "无法进入,请检查门户授权、账号绑定及子系统可用状态。")
+ finally:
+ connection.close()
+
+ def send_head(self):
+ # Serve the existing two business surfaces, with account controls hidden
+ # before first paint. The API gate separately blocks native credentials.
+ path = urlsplit(self.path).path
+ if enabled() and path in {"/admin.html", "/company.html"}:
+ from pathlib import Path
+ body = Path(self.directory, path[1:]).read_text(encoding="utf-8")
+ home = base_url("PORTAL_PUBLIC_URL")
+ script = ''
+ style = ''
+ body = body.replace('', script + style + '')
+ body = body.replace('