Files
37duAutomation/libs/hr_sdk/hr_sdk/auth.py
T
puddy 9873eb1963 restore: 恢复 11-06~11-09 本地未提交改动
- libs: 新增 hr_sdk / hotel_report / dingtalk,更新 desktopauto
- controlplane-next: SDK 管理模块(controller/entity/migrations)与前端视图
- electron-shell: 插件同步、注册表、runner 调整
- plugins: XQ0035/XQ0041/XQ0042/XQ0045_XQ0046/XQ0048/XQ0076/XQ0078 等版本更新
- tests/tools: 新增 SDK 兼容性检查与打包工具(sdk_pack.py、sdk_compat_check.py)
2026-11-09 17:27:10 +08:00

419 lines
15 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""HR 登录原语(纯接口,无浏览器):AES 密码、滑块定位、提交登录、cookie 落盘。
**插件不要调这里**——插件用宿主注入的会话(``ctx.get_session("hr")``),
登录由壳子按账号完成。本模块只服务三类「没有宿主」的场景:
1. 壳子登录子进程(``platform-auth.js`` 拉起 python 调 ``ensure_login()``);
2. CLI / agent / 一次性排查;
3. 离线自测(不联网的那部分)。
登录链路(2026-10 实测):
GET 登录页 → GET 滑块图(shade/origin/cutout + y)
→ 定位缺口 x(diff 法 + 模板匹配互验) → POST 校验滑块
→ POST j_red_security_check/PW(密码 AES-128-ECB)→ GET getCurUserInfo 校验 → 落盘 cookies。
依赖:``requests`` + ``opencv-python-headless``/``numpy`` + ``pycryptodome``(惰性导入,
只用登录时才付这份代价)。
"""
from __future__ import annotations
import base64
import importlib
import json
import os
import random
import time
from typing import Callable, Optional, Tuple
import requests
from .config import REDSEA, USER_AGENT, cookies_file
from .errors import AuthError, ConfigError
from .session import looks_like_login_page
LOGIN_URL = f"{REDSEA}/"
CAPTCHA_GET_URL = f"{REDSEA}/captcha/get/verification/image.mob"
CAPTCHA_CHECK_URL = f"{REDSEA}/captcha/check/verification/result.mob"
LOGIN_POST_URL = f"{REDSEA}/j_red_security_check/PW"
CUR_USER_URL = f"{REDSEA}/PtUsers.mc?method=getCurUserInfo"
#: 前端登录页硬编码的 AES 密钥与 CSRF 常量(接口事实,非我方密钥)
AES_KEY = b"ps_uer_!@#BGYUJN"
CSRF_TOKEN = "RP"
#: 浏览器可见窗口(登录页 .imgBg 340x171 固定、background 原尺寸绘制)
VIEW_W = 340
VIEW_H = 171
TIMEOUT = 15
RETRY_MAX = 5 # 单轮滑块重试次数
LOGIN_ROUND_MAX = 3 # 整轮登录最大重试(项目级 3 次)
LOGGER = Callable[[str], None]
# ==================== 依赖惰性加载 ====================
def _require(module: str, hint: str):
try:
return importlib.import_module(module)
except ImportError: # pragma: no cover - 环境缺依赖
raise ConfigError(f"登录需要 {module}(执行机环境包应已预装):{hint}") from None
def _cv2_np():
return _require("cv2", "pip install opencv-python-headless"), _require("numpy", "pip install numpy")
# ==================== 密码加密 ====================
def aes_encrypt_password(password: str) -> str:
"""AES-128-ECB + PKCS7,key 为前端硬编码常量,输出 base64(等价 CryptoJS)。"""
aes_mod = _require("Crypto.Cipher.AES", "pip install pycryptodome")
pad_mod = _require("Crypto.Util.Padding", "pip install pycryptodome")
cipher = aes_mod.new(AES_KEY, aes_mod.MODE_ECB)
return base64.b64encode(cipher.encrypt(pad_mod.pad(password.encode("utf-8"), 16))
).decode("ascii")
# ==================== 会话与 cookie ====================
def new_session(timeout: float = TIMEOUT) -> requests.Session:
"""建立会话并访问登录页拿基础 cookie(验证码与登录必须同一会话)。"""
session = requests.Session()
session.headers.update({
"User-Agent": USER_AGENT,
"Referer": LOGIN_URL,
"X-Requested-With": "XMLHttpRequest",
})
session.get(LOGIN_URL, timeout=timeout)
return session
def save_cookies(session, path: str = "") -> str:
"""把会话 cookie 落盘为 ``[{name,value,domain,path,expires}]``,返回文件路径。"""
target = path or cookies_file()
items = [{
"name": c.name, "value": c.value, "domain": c.domain,
"path": c.path or "/",
"expires": int(c.expires) if c.expires else None,
} for c in session.cookies]
if not items:
raise AuthError("未获取到 Cookies,无法保存登录态")
os.makedirs(os.path.dirname(os.path.abspath(target)), exist_ok=True)
with open(target, "w", encoding="utf-8") as fp:
json.dump(items, fp, ensure_ascii=False, indent=2)
return target
def load_cookies(path: str = "") -> Optional[list]:
"""读取 cookies 文件;不存在返回 ``None``。"""
target = path or cookies_file()
if not os.path.exists(target):
return None
try:
with open(target, encoding="utf-8") as fp:
data = json.load(fp)
except (OSError, ValueError):
return None
items = data.get("cookies") if isinstance(data, dict) else data
return items or None
def session_alive(*, cookie_path: str = "", validate_url: str = "",
timeout: float = TIMEOUT) -> bool:
"""用 cookies 请求 ``getCurUserInfo``:返回 JSON 视为有效。"""
from .session import session_from_cookies
try:
session = session_from_cookies(cookie_path or cookies_file())
except ConfigError:
return False
try:
resp = session.post(validate_url or CUR_USER_URL, data={}, timeout=timeout)
except requests.RequestException:
return False
if resp.status_code != 200:
return False
return not looks_like_login_page(resp.text or "")
# ==================== 滑块 ====================
def _b64_to_img(b64str: str, flag: int):
cv2, np = _cv2_np()
if not b64str:
return None
try:
buf = base64.b64decode(b64str)
return cv2.imdecode(np.frombuffer(buf, np.uint8), flag)
except Exception: # noqa: BLE001
return None
def _crop_view(img):
"""裁切到浏览器可见窗口(坐标与页面 1:1)。"""
if img is None:
return None
height, width = img.shape[:2]
return img[:min(height, VIEW_H), :min(width, VIEW_W)]
def get_captcha(session, timeout: float = TIMEOUT) -> dict:
"""取滑块图,返回 ``{shade, origin, cutout, y}``(y 为拼图块 top)。"""
cv2, _ = _cv2_np()
data = session.get(CAPTCHA_GET_URL, timeout=timeout).json()
result = data.get("result") or {}
return {
"shade": _crop_view(_b64_to_img(result.get("shadeImage"), cv2.IMREAD_COLOR)),
"origin": _crop_view(_b64_to_img(result.get("originImage"), cv2.IMREAD_COLOR)),
"cutout": _b64_to_img(result.get("cutoutImage"), cv2.IMREAD_UNCHANGED),
"y": int(result.get("y") or 0),
}
def locate_by_diff(shade, origin) -> Tuple[Optional[int], str]:
"""diff 法:两图差异最大连通域的左边界 = 缺口 x。"""
cv2, np = _cv2_np()
if shade is None or origin is None or shade.shape != origin.shape:
return None, "图片缺失或尺寸不一致"
diff = cv2.absdiff(shade, origin).max(axis=2)
mask = (diff > 30).astype(np.uint8) * 255
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))
count, _, stats, _ = cv2.connectedComponentsWithStats(mask)
if count <= 1:
return None, "无差异区域"
best = max(range(1, count), key=lambda i: stats[i, cv2.CC_STAT_AREA])
area = int(stats[best, cv2.CC_STAT_AREA])
x = int(stats[best, cv2.CC_STAT_LEFT])
if area < 300 or area > 12000: # 缺口约 55x55(面积 ~3000)
return None, f"差异区域面积异常({area})"
return x, f"diff(area={area})"
def match_slider_dual(bg_img, cutout) -> Optional[int]:
"""模板匹配缺口(Canny + TM_CCOEFF_NORMED + 白区加权),返回水平距离 px。"""
cv2, np = _cv2_np()
if bg_img is None or cutout is None:
return None
bg_h, bg_w = bg_img.shape[:2]
x_offset = 0
if len(cutout.shape) == 3 and cutout.shape[2] == 4:
alpha = cutout[:, :, 3]
rgb = cutout[:, :, :3]
ys, xs = np.where(alpha > 0)
if len(ys) > 0:
rgb = rgb[np.min(ys):np.max(ys) + 1, np.min(xs):np.max(xs) + 1]
x_offset = np.min(xs)
else:
rgb = cutout[:, :, :3] if len(cutout.shape) == 3 else cutout
s_h, s_w = rgb.shape[:2]
if s_h <= 0 or s_w <= 0 or s_w >= bg_w or s_h >= bg_h:
return None
gray_bg = cv2.GaussianBlur(cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY), (3, 3), 0)
gray_slider = cv2.GaussianBlur(cv2.cvtColor(rgb, cv2.COLOR_BGR2GRAY), (3, 3), 0)
result = cv2.matchTemplate(cv2.Canny(gray_bg, 50, 150),
cv2.Canny(gray_slider, 50, 150),
cv2.TM_CCOEFF_NORMED)
candidates = []
temp = result.copy()
for _ in range(6):
_, max_val, _, max_loc = cv2.minMaxLoc(temp)
if max_val < 0.03:
break
candidates.append((max_val, max_loc))
y0 = max(0, max_loc[1] - s_h // 2)
y1 = min(temp.shape[0], max_loc[1] + s_h // 2)
x0 = max(0, max_loc[0] - s_w // 2)
x1 = min(temp.shape[1], max_loc[0] + s_w // 2)
temp[y0:y1, x0:x1] = -2.0
if not candidates:
return None
right_limit = bg_w - s_w - max(15, int(bg_w * 0.06))
def _whiteness(x, y, w, h):
roi = bg_img[y:y + h, x:x + w]
if roi.size == 0:
return 0.0
return float(np.all(roi > 200, axis=2).mean())
scored = [(val + 0.5 * _whiteness(loc[0], loc[1], s_w, s_h), loc)
for val, loc in candidates if s_w < loc[0] <= right_limit]
best_loc = (max(scored, key=lambda t: t[0])[1] if scored else candidates[0][1])
distance = max(0, best_loc[0] - x_offset)
return min(distance, bg_w - s_w)
def solve_distance(cap: dict) -> Tuple[Optional[int], str]:
"""定位缺口并给出应提交的 x(diff 与模板互验,分歧大则换图)。"""
cutout = cap.get("cutout")
shade = cap.get("shade")
s_w = cutout.shape[1] if cutout is not None else 55
view_w = shade.shape[1] if shade is not None else VIEW_W
x_diff, info = locate_by_diff(cap.get("shade"), cap.get("origin"))
x_tpl = match_slider_dual(cap.get("shade"), cutout)
x, how = None, "无法定位"
if x_diff is not None and x_tpl is not None and abs(x_diff - x_tpl) <= 12:
x, how = x_diff, "diff+tpl 一致"
elif x_diff is not None:
x, how = x_diff, "仅 diff(与模板分歧)"
elif x_tpl is not None:
x, how = x_tpl, "仅模板"
if x is None:
return None, how
if x <= s_w or x > view_w - s_w: # 贴边缺口不可信
return None, f"缺口位置越界({x}, 图宽{view_w})"
return x, how
def check_slider(session, x: int, y: int, timeout: float = TIMEOUT) -> bool:
"""提交滑块校验。"""
resp = session.post(CAPTCHA_CHECK_URL,
params={"x": int(round(x)), "y": int(y)}, timeout=timeout)
try:
return bool(resp.json())
except ValueError:
return False
def submit_login(session, username: str, password: str, x: int, y: int,
timeout: float = TIMEOUT) -> Tuple[bool, str]:
"""提交登录,返回 ``(ok, message)``;``state == "0"`` 视为失败。"""
form = {
"MENU_TYPE": "classic",
"sysCode": "RedseaP",
"j_username": username,
"j_password": aes_encrypt_password(password),
"x": int(round(x)),
"y": int(y),
}
resp = session.post(LOGIN_POST_URL, data=form,
headers={"Csrf-Token": CSRF_TOKEN}, timeout=timeout)
try:
result = resp.json()
except ValueError:
return False, f"登录响应非 JSON(HTTP {resp.status_code})"
if str(result.get("state")) == "0":
return False, str(result.get("meg") or "登录失败")
return True, "登录成功"
# ==================== 对外入口 ====================
def login(username: str = "", password: str = "", *, cookie_path: str = "",
save: bool = True, log: Optional[LOGGER] = None) -> str:
"""完整接口登录,成功返回 cookies 文件路径。
Args:
username/password: 缺省读 ``hr_login_username`` / ``hr_login_password``
cookie_path: 落盘路径(默认 :func:`hr_sdk.config.cookies_file`)
save: 是否落盘(``False`` 时只验证能登录)
log: 日志回调
Raises:
ConfigError: 账号密码缺失
AuthError: 登录失败(账号密码错 / 滑块连续不过)
"""
username = (username or os.getenv("hr_login_username", "")).strip()
password = password or os.getenv("hr_login_password", "")
if not username or not password:
raise ConfigError("缺少登录配置:hr_login_username / hr_login_password")
log = log or (lambda msg: None)
for rnd in range(1, LOGIN_ROUND_MAX + 1):
try:
session = new_session()
except requests.RequestException as exc:
log(f"[WARN] 建立会话失败({rnd}/{LOGIN_ROUND_MAX}):{exc}")
time.sleep(1)
continue
for attempt in range(1, RETRY_MAX + 1):
try:
cap = get_captcha(session)
except (requests.RequestException, ValueError) as exc:
log(f"[WARN] 取滑块图失败:{exc}")
time.sleep(1)
continue
shade, y = cap.get("shade"), cap.get("y", 0)
if shade is None or not (0 <= y <= shade.shape[0] - 55):
time.sleep(0.5)
continue
x, how = solve_distance(cap)
if x is None:
log(f"[INFO] 缺口定位失败({how}),换图")
time.sleep(random.uniform(0.3, 0.8))
continue
if not check_slider(session, x, y):
log(f"[INFO] 滑块校验未通过(x={x}, y={y}, {how}),换图")
time.sleep(random.uniform(0.5, 1.2))
continue
ok, message = submit_login(session, username, password, x, y)
if not ok:
raise AuthError(f"登录失败:{message}") # 账号密码类错误,重试无意义
path = save_cookies(session, cookie_path) if save else (cookie_path
or cookies_file())
log(f"[INFO] HR 登录成功,cookies 已保存:{path}")
return path
time.sleep(1)
raise AuthError(f"登录失败:{LOGIN_ROUND_MAX} 轮 × {RETRY_MAX} 次滑块均未通过")
def ensure_login(username: str = "", password: str = "", *, force: bool = False,
cookie_path: str = "", log: Optional[LOGGER] = None) -> dict:
"""确保存在有效登录态(优先复用 cookies),返回外壳兼容的 dict。
Returns:
``{"success": bool, "cookie_path": str, "message": str, "relogin": bool}``
"""
log = log or (lambda msg: None)
path = cookie_path or cookies_file()
if not force and session_alive(cookie_path=path):
log("[INFO] 复用缓存登录态")
return {"success": True, "cookie_path": path, "message": "复用缓存登录态",
"relogin": False}
try:
saved = login(username, password, cookie_path=path, log=log)
except (AuthError, ConfigError) as exc:
return {"success": False, "cookie_path": path, "message": str(exc),
"relogin": False}
return {"success": True, "cookie_path": saved, "message": "登录成功", "relogin": True}
__all__ = [
"AES_KEY",
"CAPTCHA_CHECK_URL",
"CAPTCHA_GET_URL",
"CSRF_TOKEN",
"CUR_USER_URL",
"LOGIN_POST_URL",
"LOGIN_ROUND_MAX",
"LOGIN_URL",
"RETRY_MAX",
"TIMEOUT",
"VIEW_H",
"VIEW_W",
"aes_encrypt_password",
"check_slider",
"ensure_login",
"get_captcha",
"load_cookies",
"locate_by_diff",
"login",
"match_slider_dual",
"new_session",
"save_cookies",
"session_alive",
"solve_distance",
"submit_login",
]